BVB Source Codes

parse-server Show FunctionsRouter.js Source code

Return Download parse-server: download FunctionsRouter.js Source code - Download parse-server Source code - Type:.js
  1. // FunctionsRouter.js
  2.  
  3. var Parse = require('parse/node').Parse,
  4.   triggers = require('../triggers');
  5.  
  6. import PromiseRouter from '../PromiseRouter';
  7. import { promiseEnforceMasterKeyAccess } from '../middlewares';
  8. import { jobStatusHandler } from '../StatusHandler';
  9. import _ from 'lodash';
  10. import { logger } from '../logger';
  11.  
  12. function parseObject(obj) {
  13.   if (Array.isArray(obj)) {
  14.     return obj.map((item) => {
  15.       return parseObject(item);
  16.     });
  17.   } else if (obj && obj.__type == 'Date') {
  18.     return Object.assign(new Date(obj.iso), obj);
  19.   } else if (obj && obj.__type == 'File') {
  20.     return Parse.File.fromJSON(obj);
  21.   } else if (obj && typeof obj === 'object') {
  22.     return parseParams(obj);
  23.   } else {
  24.     return obj;
  25.   }
  26. }
  27.  
  28. function parseParams(params) {
  29.   return _.mapValues(params, parseObject);
  30. }
  31.  
  32. export class FunctionsRouter extends PromiseRouter {
  33.  
  34.   mountRoutes() {
  35.     this.route('POST', '/functions/:functionName', FunctionsRouter.handleCloudFunction);
  36.     this.route('POST', '/jobs/:jobName', promiseEnforceMasterKeyAccess, function(req) {
  37.       return FunctionsRouter.handleCloudJob(req);
  38.     });
  39.     this.route('POST', '/jobs', promiseEnforceMasterKeyAccess, function(req) {
  40.       return FunctionsRouter.handleCloudJob(req);
  41.     });
  42.   }
  43.  
  44.   static handleCloudJob(req) {
  45.     const jobName = req.params.jobName || req.body.jobName;
  46.     const applicationId = req.config.applicationId;
  47.     const jobHandler = jobStatusHandler(req.config);
  48.     const jobFunction = triggers.getJob(jobName, applicationId);
  49.     if (!jobFunction) {
  50.       throw new Parse.Error(Parse.Error.SCRIPT_FAILED, 'Invalid job.');
  51.     }
  52.     let params = Object.assign({}, req.body, req.query);
  53.     params = parseParams(params);
  54.     const request = {
  55.       params: params,
  56.       log: req.config.loggerController,
  57.       headers: req.headers,
  58.       jobName
  59.     };
  60.     const status = {
  61.       success: jobHandler.setSucceeded.bind(jobHandler),
  62.       error: jobHandler.setFailed.bind(jobHandler),
  63.       message: jobHandler.setMessage.bind(jobHandler)
  64.     }
  65.     return jobHandler.setRunning(jobName, params).then((jobStatus) => {
  66.       request.jobId = jobStatus.objectId
  67.       // run the function async
  68.       process.nextTick(() => {
  69.         jobFunction(request, status);
  70.       });
  71.       return {
  72.         headers: {
  73.           'X-Parse-Job-Status-Id': jobStatus.objectId
  74.         },
  75.         response: {}
  76.       }
  77.     });
  78.   }
  79.  
  80.   static createResponseObject(resolve, reject, message) {
  81.     return {
  82.       success: function(result) {
  83.         resolve({
  84.           response: {
  85.             result: Parse._encode(result)
  86.           }
  87.         });
  88.       },
  89.       error: function(code, message) {
  90.         if (!message) {
  91.           message = code;
  92.           code = Parse.Error.SCRIPT_FAILED;
  93.         }
  94.         reject(new Parse.Error(code, message));
  95.       },
  96.       message: message
  97.     }
  98.   }
  99.  
  100.   static handleCloudFunction(req) {
  101.     const functionName = req.params.functionName;
  102.     const applicationId = req.config.applicationId;
  103.     const theFunction = triggers.getFunction(functionName, applicationId);
  104.     const theValidator = triggers.getValidator(req.params.functionName, applicationId);
  105.     if (theFunction) {
  106.       let params = Object.assign({}, req.body, req.query);
  107.       params = parseParams(params);
  108.       var request = {
  109.         params: params,
  110.         master: req.auth && req.auth.isMaster,
  111.         user: req.auth && req.auth.user,
  112.         installationId: req.info.installationId,
  113.         log: req.config.loggerController,
  114.         headers: req.headers,
  115.         functionName
  116.       };
  117.  
  118.       if (theValidator && typeof theValidator === "function") {
  119.         var result = theValidator(request);
  120.         if (!result) {
  121.           throw new Parse.Error(Parse.Error.VALIDATION_ERROR, 'Validation failed.');
  122.         }
  123.       }
  124.  
  125.       return new Promise(function (resolve, reject) {
  126.         const userString = (req.auth && req.auth.user) ? req.auth.user.id : undefined;
  127.         const cleanInput = logger.truncateLogMessage(JSON.stringify(params));
  128.         var response = FunctionsRouter.createResponseObject((result) => {
  129.           try {
  130.             const cleanResult = logger.truncateLogMessage(JSON.stringify(result.response.result));
  131.             logger.info(`Ran cloud function ${functionName} for user ${userString} `
  132.               + `with:\n  Input: ${cleanInput }\n  Result: ${cleanResult }`, {
  133.                 functionName,
  134.                 params,
  135.                 user: userString,
  136.               });
  137.             resolve(result);
  138.           } catch (e) {
  139.             reject(e);
  140.           }
  141.         }, (error) => {
  142.           try {
  143.             logger.error(`Failed running cloud function ${functionName} for `
  144.               + `user ${userString} with:\n  Input: ${cleanInput}\n  Error: `
  145.               + JSON.stringify(error), {
  146.                 functionName,
  147.                 error,
  148.                 params,
  149.                 user: userString
  150.               });
  151.             reject(error);
  152.           } catch (e) {
  153.             reject(e);
  154.           }
  155.         });
  156.         // Force the keys before the function calls.
  157.         Parse.applicationId = req.config.applicationId;
  158.         Parse.javascriptKey = req.config.javascriptKey;
  159.         Parse.masterKey = req.config.masterKey;
  160.         theFunction(request, response);
  161.       });
  162.     } else {
  163.       throw new Parse.Error(Parse.Error.SCRIPT_FAILED, `Invalid function: "${functionName}"`);
  164.     }
  165.   }
  166. }
  167.  
downloadFunctionsRouter.js Source code - Download parse-server Source code
Related Source Codes/Software:
react-boilerplate - 2017-06-07
webtorrent - Streaming torrent client for the web ... 2017-06-06
machine-learning-for-software-engineers - A complete daily plan for studying to become a mac... 2017-06-06
upterm - A terminal emulator for the 21st century. 2017-06-06
lottie-android - Render After Effects animations natively on Androi... 2017-06-07
AsyncDisplayKit - Smooth asynchronous user interfaces for iOS apps. ... 2017-06-07
ionicons - The premium icon font for Ionic ... 2017-06-07
storybook - 2017-06-07
prettier - Prettier is an opinionated JavaScript formatter. ... 2017-06-08
CRYENGINE - CRYENGINE is a powerful real-time game development... 2017-06-11
postal - 2017-06-11
reactide - Reactide is the first dedicated IDE for React web ... 2017-06-11
rkt - rkt is a pod-native container engine for Linux. It... 2017-06-11
uWebSockets - Tiny WebSockets https://for... 2017-06-11
realworld - TodoMVC for the RealWorld - Exemplary fullstack Me... 2017-06-11
goreplay - GoReplay is an open-source tool for capturing and ... 2017-06-10
pyenv - Simple Python version management 2017-06-10
redux-saga - An alternative side effect model for Redux apps ... 2017-06-10
angular-starter - 2017-06-10

 Back to top