Use throws syntax for errors in SchemasRouter.

This commit is contained in:
Nikita Lutsenko
2016-03-02 21:38:06 -08:00
parent 2afebf955f
commit 99cb05ea1e
4 changed files with 27 additions and 44 deletions

View File

@@ -8,13 +8,10 @@ import PromiseRouter from '../PromiseRouter';
import * as middleware from "../middlewares";
function classNameMismatchResponse(bodyClass, pathClass) {
return Promise.resolve({
status: 400,
response: {
code: Parse.Error.INVALID_CLASS_NAME,
error: 'class name mismatch between ' + bodyClass + ' and ' + pathClass,
}
});
throw new Parse.Error(
Parse.Error.INVALID_CLASS_NAME,
`Class name mismatch between ${bodyClass} and ${pathClass}.`
);
}
function mongoSchemaAPIResponseFields(schema) {
@@ -63,23 +60,15 @@ function createSchema(req) {
return classNameMismatchResponse(req.body.className, req.params.className);
}
}
var className = req.params.className || req.body.className;
const className = req.params.className || req.body.className;
if (!className) {
return Promise.resolve({
status: 400,
response: {
code: 135,
error: 'POST ' + req.path + ' needs class name',
}
});
throw new Parse.Error(135, `POST ${req.path} needs a 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,
}));
.then(result => ({ response: mongoSchemaToSchemaAPIResponse(result) }));
}
function modifySchema(req) {

View File

@@ -333,29 +333,22 @@ function buildMergedSchemaObject(mongoObject, putRequest) {
// enabled) before calling this function.
Schema.prototype.addClassIfNotExists = function(className, fields) {
if (this.data[className]) {
return Promise.reject({
code: Parse.Error.INVALID_CLASS_NAME,
error: 'class ' + className + ' already exists',
});
throw new Parse.Error(Parse.Error.INVALID_CLASS_NAME, `Class ${className} already exists.`);
}
var mongoObject = mongoSchemaFromFieldsAndClassName(fields, className);
let mongoObject = mongoSchemaFromFieldsAndClassName(fields, className);
if (!mongoObject.result) {
return Promise.reject(mongoObject);
}
return this.collection.insertOne(mongoObject.result)
.then(result => result.ops[0])
.catch(error => {
if (error.code === 11000) { //Mongo's duplicate key error
return Promise.reject({
code: Parse.Error.INVALID_CLASS_NAME,
error: 'class ' + className + ' already exists',
});
}
return Promise.reject(error);
});
.then(result => result.ops[0])
.catch(error => {
if (error.code === 11000) { //Mongo's duplicate key error
throw new Parse.Error(Parse.Error.INVALID_CLASS_NAME, `Class ${className} already exists.`);
}
return Promise.reject(error);
});
};
// Returns a promise that resolves successfully to the new schema