Skip to content Navigation Menu Toggle navigation Sign in Appearance settings PlatformAI CODE CREATIONGitHub CopilotWrite better code with AIGitHub Copilot appDirect agents from issue to mergeMCP RegistryNewIntegrate external toolsDEVELOPER WORKFLOWSActionsAutomate any workflowCodespacesInstant dev environmentsIssuesPlan and track workCode ReviewManage code changesAPPLICATION SECURITYGitHub Advanced SecurityFind and fix vulnerabilitiesCode securitySecure your code as you buildSecret protectionStop leaks before they startEXPLOREWhy GitHubDocumentationBlogChangelogMarketplaceView all featuresSolutionsBY COMPANY SIZEEnterprisesSmall and medium teamsStartupsNonprofitsBY USE CASEApp ModernizationDevSecOpsDevOpsCI/CDView all use casesBY INDUSTRYHealthcareFinancial servicesManufacturingGovernmentView all industriesView all solutionsResourcesEXPLORE BY TOPICAISoftware DevelopmentDevOpsSecurityView all topicsEXPLORE BY TYPECustomer storiesEvents & webinarsEbooks & reportsBusiness insightsGitHub SkillsSUPPORT & SERVICESDocumentationCustomer supportCommunity forumTrust centerPartnersView all resourcesOpen SourceCOMMUNITYGitHub SponsorsFund open source developersPROGRAMSSecurity LabMaintainer CommunityAcceleratorGitHub StarsArchive ProgramREPOSITORIESTopicsTrendingCollectionsEnterpriseENTERPRISE SOLUTIONSEnterprise platformAI-powered developer platformAVAILABLE ADD-ONSGitHub Advanced SecurityEnterprise-grade security featuresCopilot for BusinessEnterprise-grade AI featuresPremium SupportEnterprise-grade 24/7 supportPricing Search or jump to... Search code, repositories, users, issues, pull requests... Search Clear Search syntax tips Provide feedback We read every piece of feedback, and take your input very seriously. Include my email address so I can be contacted Saved searches Use saved searches to filter your results more quickly Name Query To see all available qualifiers, see our documentation. Sign in Sign up Appearance settings Resetting focus You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session. Dismiss alert {{ message }} Uh oh! There was an error while loading. Please reload this page. parse-community / parse-server Public Uh oh! There was an error while loading. Please reload this page. Notifications You must be signed in to change notification settings Fork 4.8k Star 21.4k Code Issues 372 Pull requests 132 Actions Projects Wiki Security and quality 118 Insights Additional navigation options Code Issues Pull requests Actions Projects Wiki Security and quality Insights FilesExpand file tree alphaBreadcrumbsparse-server/src/PromiseRouter.jsCopy pathBlameMore file actionsBlameMore file actions Latest commit HistoryHistoryHistory210 lines (190 loc) · 5.97 KB alphaBreadcrumbsparse-server/src/PromiseRouter.jsCopy pathTopFile metadata and controlsCodeBlame210 lines (190 loc) · 5.97 KBRawCopy raw fileDownload raw fileOpen symbols panelEdit and raw actions123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210// A router that is based on promises rather than req/res/next.// This is intended to replace the use of express.Router to handle// subsections of the API surface.// This will make it easier to have methods like 'batch' that// themselves use our routing information, without disturbing express// components that external developers may be modifying. import Parse from 'parse/node';import express from 'express';import log from './logger';import { inspect } from 'util';const Layer = require('router/lib/layer'); function validateParameter(key, value) { if (key == 'className') { if (value.match(/_?[A-Za-z][A-Za-z_0-9]*/)) { return value; } } else if (key == 'objectId') { if (value.match(/[A-Za-z0-9]+/)) { return value; } } else { return value; }} export default class PromiseRouter { // Each entry should be an object with: // path: the path to route, in express format // method: the HTTP method that this route handles. // Must be one of: POST, GET, PUT, DELETE // handler: a function that takes request, and returns a promise. // Successful handlers should resolve to an object with fields: // status: optional. the http status code. defaults to 200 // response: a json object with the content of the response // location: optional. a location header constructor(routes = [], appId) { this.routes = routes; this.appId = appId; this.mountRoutes(); } // Leave the opportunity to // subclasses to mount their routes by overriding mountRoutes() {} // Merge the routes into this one merge(router) { for (var route of router.routes) { this.routes.push(route); } } route(method, path, ...handlers) { switch (method) { case 'POST': case 'GET': case 'PUT': case 'DELETE': break; default: throw 'cannot route method: ' + method; } let handler = handlers[0]; if (handlers.length > 1) { handler = function (req) { return handlers.reduce((promise, handler) => { return promise.then(() => { return handler(req); }); }, Promise.resolve()); }; } this.routes.push({ path: path, method: method, handler: handler, layer: new Layer(path, null, handler), }); } // Returns an object with: // handler: the handler that should deal with this request // params: any :-params that got parsed from the path // Returns undefined if there is no match. match(method, path) { for (var route of this.routes) { if (route.method != method) { continue; } const layer = route.layer || new Layer(route.path, null, route.handler); const match = layer.match(path); if (match) { const params = layer.params; Object.keys(params).forEach(key => { params[key] = validateParameter(key, params[key]); }); return { params: params, handler: route.handler }; } } } // Mount the routes on this router onto an express app (or express router) mountOnto(expressApp) { this.routes.forEach(route => { const method = route.method.toLowerCase(); const handler = makeExpressHandler(this.appId, route.handler); expressApp[method].call(expressApp, route.path, handler); }); return expressApp; } expressRouter() { return this.mountOnto(express.Router()); } tryRouteRequest(method, path, request) { var match = this.match(method, path); if (!match) { throw new Parse.Error(Parse.Error.INVALID_JSON, 'cannot route ' + method + ' ' + path); } request.params = match.params; return new Promise((resolve, reject) => { match.handler(request).then(resolve, reject); }); }} // A helper function to make an express handler out of a a promise// handler.// Express handlers should never throw; if a promise handler throws we// just treat it like it resolved to an error.function makeExpressHandler(appId, promiseHandler) { return function (req, res, next) { try { const url = maskSensitiveUrl(req); const body = Object.assign({}, req.body); const method = req.method; const headers = req.headers; log.logRequest({ method, url, headers, body, }); promiseHandler(req) .then( result => { if (!result.response && !result.location && !result.text) { log.error('the handler did not include a "response" or a "location" field'); throw 'control should not get here'; } log.logResponse({ method, url, result }); var status = result.status || 200; res.status(status); if (result.headers) { Object.keys(result.headers).forEach(header => { res.set(header, result.headers[header]); }); } if (result.text) { res.send(result.text); return; } if (result.location) { res.set('Location', result.location); // Override the default expressjs response // as it double encodes %encoded chars in URL if (!result.response) { res.send('Found. Redirecting to ' + result.location); return; } } res.json(result.response); }, error => { next(error); } ) .catch(e => { log.error(`Error generating response. ${inspect(e)}`, { error: e }); next(e); }); } catch (e) { log.error(`Error handling request: ${inspect(e)}`, { error: e }); next(e); } };} function maskSensitiveUrl(req) { let maskUrl = req.originalUrl.toString(); const shouldMaskUrl = req.method === 'GET' && req.originalUrl.includes('/login') && !req.originalUrl.includes('classes'); if (shouldMaskUrl) { maskUrl = log.maskSensitiveUrl(maskUrl); } return maskUrl;} You can’t perform that action at this time.