Files
kami-parse-server/src/Routers/FunctionsRouter.js

93 lines
2.7 KiB
JavaScript
Raw Normal View History

// FunctionsRouter.js
2016-02-19 23:47:44 -05:00
var express = require('express'),
Parse = require('parse/node').Parse,
triggers = require('../triggers');
2016-02-19 23:47:44 -05:00
import PromiseRouter from '../PromiseRouter';
import _ from 'lodash';
function parseDate(params) {
return _.mapValues(params, (obj) => {
if (Array.isArray(obj)) {
return obj.map((item) => {
if (item && item.__type == 'Date') {
return new Date(item.iso);
} else if (item && typeof item === 'object') {
return parseDate(item);
} else {
return item;
}
});
} else if (obj && obj.__type == 'Date') {
return new Date(obj.iso);
} else if (obj && typeof obj === 'object') {
return parseDate(obj);
} else {
return obj;
}
});
}
2016-02-19 23:47:44 -05:00
export class FunctionsRouter extends PromiseRouter {
2016-02-19 23:47:44 -05:00
mountRoutes() {
this.route('POST', '/functions/:functionName', FunctionsRouter.handleCloudFunction);
}
2016-02-19 23:47:44 -05:00
static createResponseObject(resolve, reject) {
return {
success: function(result) {
resolve({
response: {
result: Parse._encode(result)
}
});
},
error: function(code, message) {
if (!message) {
message = code;
code = Parse.Error.SCRIPT_FAILED;
}
reject(new Parse.Error(code, message));
2016-02-19 23:47:44 -05:00
}
}
}
2016-02-19 23:47:44 -05:00
static handleCloudFunction(req) {
var applicationId = req.config.applicationId;
var theFunction = triggers.getFunction(req.params.functionName, applicationId);
var theValidator = triggers.getValidator(req.params.functionName, applicationId);
if (theFunction) {
let params = Object.assign({}, req.body, req.query);
params = parseDate(params);
2016-02-19 23:47:44 -05:00
var request = {
params: params,
2016-02-19 23:47:44 -05:00
master: req.auth && req.auth.isMaster,
user: req.auth && req.auth.user,
installationId: req.info.installationId,
log: req.config.loggerController && req.config.loggerController.adapter,
headers: req.headers
2016-02-19 23:47:44 -05:00
};
if (theValidator && typeof theValidator === "function") {
var result = theValidator(request);
2016-02-19 23:47:44 -05:00
if (!result) {
throw new Parse.Error(Parse.Error.VALIDATION_ERROR, 'Validation failed.');
2016-02-19 23:47:44 -05:00
}
}
return new Promise(function (resolve, reject) {
var response = FunctionsRouter.createResponseObject(resolve, reject);
// Force the keys before the function calls.
Parse.applicationId = req.config.applicationId;
Parse.javascriptKey = req.config.javascriptKey;
Parse.masterKey = req.config.masterKey;
theFunction(request, response);
2016-02-19 23:47:44 -05:00
});
} else {
throw new Parse.Error(Parse.Error.SCRIPT_FAILED, 'Invalid function.');
}
}
}