Refactors routers

This commit is contained in:
Florent Vilmart
2016-02-19 23:47:44 -05:00
parent 067946c66c
commit 3c4d5159b4
14 changed files with 281 additions and 271 deletions

View File

@@ -0,0 +1,20 @@
// AnalyticsRouter.js
var Parse = require('parse/node').Parse;
import PromiseRouter from '../PromiseRouter';
// Returns a promise that resolves to an empty object response
function ignoreAndSucceed(req) {
return Promise.resolve({
response: {}
});
}
export class AnalyticsRouter extends PromiseRouter {
mountRoutes() {
this.route('POST','/events/AppOpened', ignoreAndSucceed);
this.route('POST','/events/:eventName', ignoreAndSucceed);
}
}

View File

@@ -4,8 +4,8 @@ import rest from '../rest';
import url from 'url';
export class ClassesRouter {
// Returns a promise that resolves to a {response} object.
export class ClassesRouter extends PromiseRouter {
handleFind(req) {
let body = Object.assign(req.body, req.query);
let options = {};
@@ -97,15 +97,13 @@ export class ClassesRouter {
return {response: {}};
});
}
getExpressRouter() {
var router = new PromiseRouter();
router.route('GET', '/classes/:className', (req) => { return this.handleFind(req); });
router.route('GET', '/classes/:className/:objectId', (req) => { return this.handleGet(req); });
router.route('POST', '/classes/:className', (req) => { return this.handleCreate(req); });
router.route('PUT', '/classes/:className/:objectId', (req) => { return this.handleUpdate(req); });
router.route('DELETE', '/classes/:className/:objectId', (req) => { return this.handleDelete(req); });
return router;
mountRoutes() {
this.route('GET', '/classes/:className', (req) => { return this.handleFind(req); });
this.route('GET', '/classes/:className/:objectId', (req) => { return this.handleGet(req); });
this.route('POST', '/classes/:className', (req) => { return this.handleCreate(req); });
this.route('PUT', '/classes/:className/:objectId', (req) => { return this.handleUpdate(req); });
this.route('DELETE', '/classes/:className/:objectId', (req) => { return this.handleDelete(req); });
}
}

View File

@@ -0,0 +1,55 @@
// functions.js
var express = require('express'),
Parse = require('parse/node').Parse;
import PromiseRouter from '../PromiseRouter';
export class FunctionsRouter extends PromiseRouter {
mountRoutes() {
this.route('POST', '/functions/:functionName', FunctionsRouter.handleCloudFunction);
}
static createResponseObject(resolve, reject) {
return {
success: function(result) {
resolve({
response: {
result: Parse._encode(result)
}
});
},
error: function(error) {
reject(new Parse.Error(Parse.Error.SCRIPT_FAILED, error));
}
}
}
static handleCloudFunction(req) {
if (Parse.Cloud.Functions[req.params.functionName]) {
var request = {
params: Object.assign({}, req.body, req.query),
master: req.auth && req.auth.isMaster,
user: req.auth && req.auth.user,
installationId: req.info.installationId
};
if (Parse.Cloud.Validators[req.params.functionName]) {
var result = Parse.Cloud.Validators[req.params.functionName](request);
if (!result) {
throw new Parse.Error(Parse.Error.SCRIPT_FAILED, 'Validation failed.');
}
}
return new Promise(function (resolve, reject) {
var response = FunctionsRouter.createResponseObject(resolve, reject);
Parse.Cloud.Functions[req.params.functionName](request, response);
});
} else {
throw new Parse.Error(Parse.Error.SCRIPT_FAILED, 'Invalid function.');
}
}
}

View File

@@ -0,0 +1,96 @@
import PromiseRouter from '../PromiseRouter';
var request = require("request");
var rest = require("../rest");
var Auth = require("../Auth");
// TODO move validation logic in IAPValidationController
const IAP_SANDBOX_URL = "https://sandbox.itunes.apple.com/verifyReceipt";
const IAP_PRODUCTION_URL = "https://buy.itunes.apple.com/verifyReceipt";
const APP_STORE_ERRORS = {
21000: "The App Store could not read the JSON object you provided.",
21002: "The data in the receipt-data property was malformed or missing.",
21003: "The receipt could not be authenticated.",
21004: "The shared secret you provided does not match the shared secret on file for your account.",
21005: "The receipt server is not currently available.",
21006: "This receipt is valid but the subscription has expired.",
21007: "This receipt is from the test environment, but it was sent to the production environment for verification. Send it to the test environment instead.",
21008: "This receipt is from the production environment, but it was sent to the test environment for verification. Send it to the production environment instead."
}
function appStoreError(status) {
status = parseInt(status);
var errorString = APP_STORE_ERRORS[status] || "unknown error.";
return { status: status, error: errorString }
}
function validateWithAppStore(url, receipt) {
return new Promise(function(fulfill, reject) {
request.post({
url: url,
body: { "receipt-data": receipt },
json: true,
}, function(err, res, body) {
var status = body.status;
if (status == 0) {
// No need to pass anything, status is OK
return fulfill();
}
// receipt is from test and should go to test
if (status == 21007) {
return validateWithAppStore(IAP_SANDBOX_URL);
}
return reject(body);
});
});
}
function getFileForProductIdentifier(productIdentifier, req) {
return rest.find(req.config, req.auth, '_Product', { productIdentifier: productIdentifier }).then(function(result){
const products = result.results;
if (!products || products.length != 1) {
// Error not found or too many
throw new Parse.Error(Parse.Error.OBJECT_NOT_FOUND, 'Object not found.')
}
var download = products[0].download;
return Promise.resolve({response: download});
});
}
export class IAPValidationRouter extends PromiseRouter {
handleRequest(req) {
let receipt = req.body.receipt;
const productIdentifier = req.body.productIdentifier;
if (!receipt || ! productIdentifier) {
// TODO: Error, malformed request
throw new Parse.Error(Parse.Error.INVALID_JSON, "missing receipt or productIdentifier");
}
// Transform the object if there
// otherwise assume it's in Base64 already
if (typeof receipt == "object") {
if (receipt["__type"] == "Bytes") {
receipt = receipt.base64;
}
}
if (process.env.NODE_ENV == "test" && req.body.bypassAppStoreValidation) {
return getFileForProductIdentifier(productIdentifier, req);
}
return validateWithAppStore(IAP_PRODUCTION_URL, receipt).then( () => {
return getFileForProductIdentifier(productIdentifier, req);
}, (error) => {
return Promise.resolve({response: appStoreError(error.status) });
});
}
mountRoutes() {
this.route("POST","/validate_purchase", this.handleRequest);
}
}

View File

@@ -50,14 +50,12 @@ export class InstallationsRouter extends ClassesRouter {
return super.handleDelete(req);
}
getExpressRouter() {
let router = new PromiseRouter();
router.route('GET','/installations', req => { return this.handleFind(req); });
router.route('GET','/installations/:objectId', req => { return this.handleGet(req); });
router.route('POST','/installations', req => { return this.handleCreate(req); });
router.route('PUT','/installations/:objectId', req => { return this.handleUpdate(req); });
router.route('DELETE','/installations/:objectId', req => { return this.handleDelete(req); });
return router;
mountRoutes() {
this.route('GET','/installations', req => { return this.handleFind(req); });
this.route('GET','/installations/:objectId', req => { return this.handleGet(req); });
this.route('POST','/installations', req => { return this.handleCreate(req); });
this.route('PUT','/installations/:objectId', req => { return this.handleUpdate(req); });
this.route('DELETE','/installations/:objectId', req => { return this.handleDelete(req); });
}
}

View File

@@ -29,14 +29,12 @@ export class RolesRouter extends ClassesRouter {
return super.handleDelete(req);
}
getExpressRouter() {
let router = new PromiseRouter();
router.route('GET','/roles', req => { return this.handleFind(req); });
router.route('GET','/roles/:objectId', req => { return this.handleGet(req); });
router.route('POST','/roles', req => { return this.handleCreate(req); });
router.route('PUT','/roles/:objectId', req => { return this.handleUpdate(req); });
router.route('DELETE','/roles/:objectId', req => { return this.handleDelete(req); });
return router;
mountRoutes() {
this.route('GET','/roles', req => { return this.handleFind(req); });
this.route('GET','/roles/:objectId', req => { return this.handleGet(req); });
this.route('POST','/roles', req => { return this.handleCreate(req); });
this.route('PUT','/roles/:objectId', req => { return this.handleUpdate(req); });
this.route('DELETE','/roles/:objectId', req => { return this.handleDelete(req); });
}
}

View File

@@ -0,0 +1,279 @@
// schemas.js
var express = require('express'),
Parse = require('parse/node').Parse,
Schema = require('../Schema');
import PromiseRouter from '../PromiseRouter';
// TODO: refactor in a SchemaController at one point...
function masterKeyRequiredResponse() {
return Promise.resolve({
status: 401,
response: {error: 'master key not specified'},
})
}
function classNameMismatchResponse(bodyClass, pathClass) {
return Promise.resolve({
status: 400,
response: {
code: Parse.Error.INVALID_CLASS_NAME,
error: 'class name mismatch between ' + bodyClass + ' and ' + pathClass,
}
});
}
function mongoSchemaAPIResponseFields(schema) {
var fieldNames = Object.keys(schema).filter(key => key !== '_id' && key !== '_metadata');
var response = fieldNames.reduce((obj, fieldName) => {
obj[fieldName] = Schema.mongoFieldTypeToSchemaAPIType(schema[fieldName])
return obj;
}, {});
response.ACL = {type: 'ACL'};
response.createdAt = {type: 'Date'};
response.updatedAt = {type: 'Date'};
response.objectId = {type: 'String'};
return response;
}
function mongoSchemaToSchemaAPIResponse(schema) {
return {
className: schema._id,
fields: mongoSchemaAPIResponseFields(schema),
};
}
function getAllSchemas(req) {
if (!req.auth.isMaster) {
return masterKeyRequiredResponse();
}
return req.config.database.collection('_SCHEMA')
.then(coll => coll.find({}).toArray())
.then(schemas => ({response: {
results: schemas.map(mongoSchemaToSchemaAPIResponse)
}}));
}
function getOneSchema(req) {
if (!req.auth.isMaster) {
return masterKeyRequiredResponse();
}
return req.config.database.collection('_SCHEMA')
.then(coll => coll.findOne({'_id': req.params.className}))
.then(schema => ({response: mongoSchemaToSchemaAPIResponse(schema)}))
.catch(() => ({
status: 400,
response: {
code: 103,
error: 'class ' + req.params.className + ' does not exist',
}
}));
}
function createSchema(req) {
if (!req.auth.isMaster) {
return masterKeyRequiredResponse();
}
if (req.params.className && req.body.className) {
if (req.params.className != req.body.className) {
return classNameMismatchResponse(req.body.className, req.params.className);
}
}
var className = req.params.className || req.body.className;
if (!className) {
return Promise.resolve({
status: 400,
response: {
code: 135,
error: 'POST ' + req.path + ' needs class name',
},
});
}
return req.config.database.loadSchema()
.then(schema => schema.addClassIfNotExists(className, req.body.fields))
.then(result => ({ response: mongoSchemaToSchemaAPIResponse(result) }))
.catch(error => ({
status: 400,
response: error,
}));
}
function modifySchema(req) {
if (!req.auth.isMaster) {
return masterKeyRequiredResponse();
}
if (req.body.className && req.body.className != req.params.className) {
return classNameMismatchResponse(req.body.className, req.params.className);
}
var submittedFields = req.body.fields || {};
var className = req.params.className;
return req.config.database.loadSchema()
.then(schema => {
if (!schema.data[className]) {
return Promise.resolve({
status: 400,
response: {
code: Parse.Error.INVALID_CLASS_NAME,
error: 'class ' + req.params.className + ' does not exist',
}
});
}
var existingFields = schema.data[className];
for (var submittedFieldName in submittedFields) {
if (existingFields[submittedFieldName] && submittedFields[submittedFieldName].__op !== 'Delete') {
return Promise.resolve({
status: 400,
response: {
code: 255,
error: 'field ' + submittedFieldName + ' exists, cannot update',
}
});
}
if (!existingFields[submittedFieldName] && submittedFields[submittedFieldName].__op === 'Delete') {
return Promise.resolve({
status: 400,
response: {
code: 255,
error: 'field ' + submittedFieldName + ' does not exist, cannot delete',
}
});
}
}
var newSchema = Schema.buildMergedSchemaObject(existingFields, submittedFields);
var mongoObject = Schema.mongoSchemaFromFieldsAndClassName(newSchema, className);
if (!mongoObject.result) {
return Promise.resolve({
status: 400,
response: mongoObject,
});
}
// Finally we have checked to make sure the request is valid and we can start deleting fields.
// Do all deletions first, then a single save to _SCHEMA collection to handle all additions.
var deletionPromises = []
Object.keys(submittedFields).forEach(submittedFieldName => {
if (submittedFields[submittedFieldName].__op === 'Delete') {
var promise = req.config.database.connect()
.then(() => schema.deleteField(
submittedFieldName,
className,
req.config.database.db,
req.config.database.collectionPrefix
));
deletionPromises.push(promise);
}
});
return Promise.all(deletionPromises)
.then(() => new Promise((resolve, reject) => {
schema.collection.update({_id: className}, mongoObject.result, {w: 1}, (err, docs) => {
if (err) {
reject(err);
}
resolve({ response: mongoSchemaToSchemaAPIResponse(mongoObject.result)});
})
}));
});
}
// A helper function that removes all join tables for a schema. Returns a promise.
var removeJoinTables = (database, prefix, mongoSchema) => {
return Promise.all(Object.keys(mongoSchema)
.filter(field => mongoSchema[field].startsWith('relation<'))
.map(field => {
var joinCollectionName = prefix + '_Join:' + field + ':' + mongoSchema._id;
return new Promise((resolve, reject) => {
database.dropCollection(joinCollectionName, (err, results) => {
if (err) {
reject(err);
} else {
resolve();
}
})
});
})
);
};
function deleteSchema(req) {
if (!req.auth.isMaster) {
return masterKeyRequiredResponse();
}
if (!Schema.classNameIsValid(req.params.className)) {
return Promise.resolve({
status: 400,
response: {
code: Parse.Error.INVALID_CLASS_NAME,
error: Schema.invalidClassNameMessage(req.params.className),
}
});
}
return req.config.database.collection(req.params.className)
.then(coll => new Promise((resolve, reject) => {
coll.count((err, count) => {
if (err) {
reject(err);
} else if (count > 0) {
resolve({
status: 400,
response: {
code: 255,
error: 'class ' + req.params.className + ' not empty, contains ' + count + ' objects, cannot drop schema',
}
});
} else {
coll.drop((err, reply) => {
if (err) {
reject(err);
} else {
// We've dropped the collection now, so delete the item from _SCHEMA
// and clear the _Join collections
req.config.database.collection('_SCHEMA')
.then(coll => new Promise((resolve, reject) => {
coll.findAndRemove({ _id: req.params.className }, [], (err, doc) => {
if (err) {
reject(err);
} else if (doc.value === null) {
//tried to delete non-existant class
resolve({ response: {}});
} else {
removeJoinTables(req.config.database.db, req.config.database.collectionPrefix, doc.value)
.then(resolve, reject);
}
});
}))
.then(resolve.bind(undefined, {response: {}}), reject);
}
});
}
});
}))
.catch( (error) => {
if (error.message == 'ns not found') {
// If they try to delete a non-existant class, thats fine, just let them.
return Promise.resolve({ response: {} });
}
return Promise.reject(error);
});
}
export class SchemasRouter extends PromiseRouter {
mountRoutes() {
this.route('GET', '/schemas', getAllSchemas);
this.route('GET', '/schemas/:className', getOneSchema);
this.route('POST', '/schemas', createSchema);
this.route('POST', '/schemas/:className', createSchema);
this.route('PUT', '/schemas/:className', modifySchema);
this.route('DELETE', '/schemas/:className', deleteSchema);
}
}

View File

@@ -48,15 +48,13 @@ export class SessionsRouter extends ClassesRouter {
});
}
getExpressRouter() {
let router = new PromiseRouter();
router.route('GET','/sessions/me', req => { return this.handleMe(req); });
router.route('GET', '/sessions', req => { return this.handleFind(req); });
router.route('GET', '/sessions/:objectId', req => { return this.handleGet(req); });
router.route('POST', '/sessions', req => { return this.handleCreate(req); });
router.route('PUT', '/sessions/:objectId', req => { return this.handleUpdate(req); });
router.route('DELETE', '/sessions/:objectId', req => { return this.handleDelete(req); });
return router;
mountRoutes() {
this.route('GET','/sessions/me', req => { return this.handleMe(req); });
this.route('GET', '/sessions', req => { return this.handleFind(req); });
this.route('GET', '/sessions/:objectId', req => { return this.handleGet(req); });
this.route('POST', '/sessions', req => { return this.handleCreate(req); });
this.route('PUT', '/sessions/:objectId', req => { return this.handleUpdate(req); });
this.route('DELETE', '/sessions/:objectId', req => { return this.handleDelete(req); });
}
}

View File

@@ -138,20 +138,18 @@ export class UsersRouter extends ClassesRouter {
return Promise.resolve(success);
}
getExpressRouter() {
let router = new PromiseRouter();
router.route('GET', '/users', req => { return this.handleFind(req); });
router.route('POST', '/users', req => { return this.handleCreate(req); });
router.route('GET', '/users/me', req => { return this.handleMe(req); });
router.route('GET', '/users/:objectId', req => { return this.handleGet(req); });
router.route('PUT', '/users/:objectId', req => { return this.handleUpdate(req); });
router.route('DELETE', '/users/:objectId', req => { return this.handleDelete(req); });
router.route('GET', '/login', req => { return this.handleLogIn(req); });
router.route('POST', '/logout', req => { return this.handleLogOut(req); });
router.route('POST', '/requestPasswordReset', () => {
mountRoutes() {
this.route('GET', '/users', req => { return this.handleFind(req); });
this.route('POST', '/users', req => { return this.handleCreate(req); });
this.route('GET', '/users/me', req => { return this.handleMe(req); });
this.route('GET', '/users/:objectId', req => { return this.handleGet(req); });
this.route('PUT', '/users/:objectId', req => { return this.handleUpdate(req); });
this.route('DELETE', '/users/:objectId', req => { return this.handleDelete(req); });
this.route('GET', '/login', req => { return this.handleLogIn(req); });
this.route('POST', '/logout', req => { return this.handleLogOut(req); });
this.route('POST', '/requestPasswordReset', () => {
throw new Parse.Error(Parse.Error.COMMAND_UNAVAILABLE, 'This path is not implemented yet.');
});
return router;
}
}