diff --git a/adapters/db/mssqldb.js b/adapters/db/mssqldb.js index 89771d9..5d74e9f 100644 --- a/adapters/db/mssqldb.js +++ b/adapters/db/mssqldb.js @@ -253,54 +253,51 @@ module.exports = { ensurePoolInitialized(ctx, function() { - _this.exec.safeExecute(ctx, function() - { - var queryString = query.getQueryString(); - var queryParams = query.getQueryParams(); - console.log("-------------------------------------------------"); - console.log("Sending query to database:"); - console.log(queryString); - console.log("Query parameters:"); - console.log(queryParams); + var queryString = query.getQueryString(); + var queryParams = query.getQueryParams(); + console.log("-------------------------------------------------"); + console.log("Sending query to database:"); + console.log(queryString); + console.log("Query parameters:"); + console.log(queryParams); - var request = new pool.sql.Request(pool); - for (var key in queryParams) + var request = new pool.sql.Request(pool); + for (var key in queryParams) + { + if (!queryParams.hasOwnProperty(key)) + continue; + var paramValue = queryParams[key]; + if (typeof (paramValue) === "number" && Math.abs(paramValue) > 2147483647) { - if (!queryParams.hasOwnProperty(key)) - continue; - var paramValue = queryParams[key]; - if (typeof (paramValue) === "number" && Math.abs(paramValue) > 2147483647) - { - request.input(key, pool.sql.BigInt, paramValue); - } - else - { - request.input(key, paramValue); - } + request.input(key, pool.sql.BigInt, paramValue); + } + else + { + request.input(key, paramValue); } - request.query(queryString, function (err, dbResponse) + } + request.query(queryString, function (err, dbResponse) + { + if (err) { - if (err) + if (!!completeCb) + _this.exec.safeCallback(ctx, completeCb); + console.log(err); + _this.exec.sendErrorResponse(ctx, "a07f", 500, "error while sending query to database"); + } + else + { + _this.exec.safeCallback(ctx, function () { - if (!!completeCb) - _this.exec.safeExecute(ctx, completeCb); - console.log(err); - throw new _this.exec.Error("a07f", 500, "error while sending query to database"); - } - else + successCb(dbResponse.recordset); + }); + if (!!completeCb) { - _this.exec.safeExecute(ctx, function () - { - successCb(dbResponse.recordset); - }); - if (!!completeCb) - { - _this.exec.safeExecute(ctx, completeCb); - } + _this.exec.safeCallback(ctx, completeCb); } - }); - console.log("-------------------------------------------------"); + } }); + console.log("-------------------------------------------------"); }); } @@ -313,7 +310,7 @@ module.exports = { if(!!pool) { - callback(); + _this.exec.safeCallback(ctx, callback); return; } var sql = require("mssql"); @@ -322,10 +319,11 @@ module.exports = if (err) { console.log(err); - throw new _this.exec.Error("f8cb", 500, "error while connecting to database"); + _this.exec.sendErrorResponse(ctx, "f8cb", 500, "error while connecting to database"); + return; } pool.sql = sql; - callback(); + _this.exec.safeCallback(ctx, callback); }); } diff --git a/adapters/db/mysqldb.js b/adapters/db/mysqldb.js index 6ad1909..6fbca2b 100644 --- a/adapters/db/mysqldb.js +++ b/adapters/db/mysqldb.js @@ -253,39 +253,36 @@ module.exports = { ensurePoolInitialized(ctx, function() { - _this.exec.safeExecute(ctx, function() - { - var queryString = query.getQueryString(); - var queryParams = query.getQueryParams(); - console.log("-------------------------------------------------"); - console.log("Sending query to database:"); - console.log(queryString); - console.log("Query parameters:"); - console.log(queryParams); + var queryString = query.getQueryString(); + var queryParams = query.getQueryParams(); + console.log("-------------------------------------------------"); + console.log("Sending query to database:"); + console.log(queryString); + console.log("Query parameters:"); + console.log(queryParams); - pool.query(queryString, queryParams, function (error, results, fields) + pool.query(queryString, queryParams, function (error, results, fields) + { + if (error) { - if (error) + if (!!completeCb) + _this.exec.safeCallback(ctx, completeCb); + console.log(error); + _this.exec.sendErrorResponse(ctx, "a07f", 500, "error while sending query to database"); + } + else + { + _this.exec.safeCallback(ctx, function () { - if (!!completeCb) - _this.exec.safeExecute(ctx, completeCb); - console.log(error); - throw new _this.exec.Error("a07f", 500, "error while sending query to database"); - } - else + successCb(results); + }); + if (!!completeCb) { - _this.exec.safeExecute(ctx, function () - { - successCb(results); - }); - if (!!completeCb) - { - _this.exec.safeExecute(ctx, completeCb); - } + _this.exec.safeCallback(ctx, completeCb); } - }); - console.log("-------------------------------------------------"); + } }); + console.log("-------------------------------------------------"); }); } @@ -298,7 +295,7 @@ module.exports = { if(!!pool) { - callback(); + _this.exec.safeCallback(ctx, callback); return; } var sql = require("mysql"); @@ -322,7 +319,7 @@ module.exports = multipleStatements: true }); pool.sql = sql; - callback(); + _this.exec.safeCallback(ctx, callback); } /** diff --git a/adapters/storage/azureStorage.js b/adapters/storage/azureStorage.js index b8c275d..f2d84e8 100644 --- a/adapters/storage/azureStorage.js +++ b/adapters/storage/azureStorage.js @@ -42,37 +42,34 @@ module.exports = var form = new (_this.multiparty.Form)(); form.on('part', function(stream) { - _this.exec.safeExecute(ctx, function() + _this.exec.safeCallback(ctx, function() { isFirstPartReceived = true; if (!stream.filename) - throw new _this.exec.Error("ffce", 400, "submitted file is not a valid file"); + _this.exec.throwError("ffce", 400, "submitted file is not a valid file"); var size = stream.byteCount - stream.byteOffset; var name = _this.guid() + stream.filename.substring(stream.filename.lastIndexOf(".")); provider.createBlockBlobFromStream(ctx.config.storage.azureStorageContainerName, name, stream, size, { contentSettings: { contentType: _this.mime.lookup(name) } - }, + }, function(error) { - callback(error, name); + _this.exec.safeCallback(ctx, function() + { + callback(error, name); + }); }); }); }); form.on('progress', function(bytesReceived, bytesExpected) { - _this.exec.safeExecute(ctx, function() - { - if(!isFirstPartReceived && bytesReceived >= bytesExpected) - throw new _this.exec.Error("171d", 400, "error while parsing the first part"); - }); + if(!isFirstPartReceived && bytesReceived >= bytesExpected) + _this.exec.sendErrorResponse(ctx, "171d", 400, "error while parsing the first part"); }); form.on('error', function(err) { - _this.exec.safeExecute(ctx, function() - { - throw new _this.exec.Error("ead9", 400, "error while parsing form data"); - }); + _this.exec.sendErrorResponse(ctx, "ead9", 400, "error while parsing form data"); }); form.parse(req); } diff --git a/adapters/storage/localHostStorage.js b/adapters/storage/localHostStorage.js index c10780d..e1622a4 100644 --- a/adapters/storage/localHostStorage.js +++ b/adapters/storage/localHostStorage.js @@ -45,7 +45,7 @@ module.exports = }); form.on('file', function(name, file) { - _this.exec.safeExecute(ctx, function() + _this.exec.safeCallback(ctx, function() { var tempPath = file.path; var tempName = path.basename(tempPath); @@ -59,10 +59,7 @@ module.exports = }); form.on('error', function(err) { - _this.exec.safeExecute(ctx, function() - { - throw new _this.exec.Error("8651", 400, "error while parsing form data"); - }); + _this.exec.sendErrorResponse(ctx, "8651", 400, "error while parsing form data"); }); form.parse(req); } diff --git a/adapters/storage/s3Storage.js b/adapters/storage/s3Storage.js index 571a01c..cedccc6 100644 --- a/adapters/storage/s3Storage.js +++ b/adapters/storage/s3Storage.js @@ -49,11 +49,11 @@ module.exports = }); form.on('part', function(stream) { - _this.exec.safeExecute(ctx, function() + _this.exec.safeCallback(ctx, function() { isFirstPartReceived = true; if (!stream.filename) - throw new _this.exec.Error("8dad", 400, "submitted file is not a valid file"); + _this.exec.throwError("8dad", 400, "submitted file is not a valid file"); var name = _this.guid() + stream.filename.substring(stream.filename.lastIndexOf(".")); provider.upload( { @@ -72,18 +72,12 @@ module.exports = }); form.on('progress', function(bytesReceived, bytesExpected) { - _this.exec.safeExecute(ctx, function() - { - if(!isFirstPartReceived && bytesReceived >= bytesExpected) - throw new _this.exec.Error("49ef", 400, "error while parsing the first part"); - }); + if(!isFirstPartReceived && bytesReceived >= bytesExpected) + _this.exec.sendErrorResponse(ctx, "49ef", 400, "error while parsing the first part"); }); form.on('error', function(err) { - _this.exec.safeExecute(ctx, function() - { - throw new _this.exec.Error("a95a", 400, "error while parsing form data"); - }); + _this.exec.sendErrorResponse(ctx, "a95a", 400, "error while parsing form data"); }); form.parse(req); } diff --git a/handlers/create.js b/handlers/create.js index 7781c44..013f4ec 100644 --- a/handlers/create.js +++ b/handlers/create.js @@ -108,7 +108,7 @@ module.exports = var requiredField = requiredFields[i]; if(!requestBody.hasOwnProperty(requiredField) || !requestBody[requiredField]) { - throw new _this.exec.Error("86c5", 400, "missing required field " + requiredFields[i]); + _this.exec.throwError("86c5", 400, "missing required field " + requiredFields[i]); } } if(ctx.entity === "user") @@ -116,7 +116,7 @@ module.exports = _this.auth.verifyAuthSupported(ctx); if(requestBody.password !== requestBody.confirmpassword) { - throw new _this.exec.Error("1b9e", 400, "password doesn't match the confirmation"); + _this.exec.throwError("1b9e", 400, "password doesn't match the confirmation"); } validateEmail(requestBody.email); verifyPwdRequirements(requestBody.password, ctx.config.auth.passwordReqs); @@ -173,7 +173,7 @@ module.exports = var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; if(!re.test(email)) { - throw new _this.exec.Error("dbaa", 400, "email is not valid: " + email); + _this.exec.throwError("dbaa", 400, "email is not valid: " + email); } } @@ -186,23 +186,23 @@ module.exports = { if(newPassword.length < passwordReqs.minLength) { - throw new _this.exec.Error("ef60", 400, "password must be at least " + passwordReqs.minLength + " characters long"); + _this.exec.throwError("ef60", 400, "password must be at least " + passwordReqs.minLength + " characters long"); } if (passwordReqs.lowercaseChar && !newPassword.match(/[a-z]/)) { - throw new _this.exec.Error("8c5e", 400, "password must contain at least one lowercase character."); + _this.exec.throwError("8c5e", 400, "password must contain at least one lowercase character."); } if(passwordReqs.uppercaseChar && !newPassword.match(/[A-Z]/)) { - throw new _this.exec.Error("d625", 400, "password must contain at least one uppercase character."); + _this.exec.throwError("d625", 400, "password must contain at least one uppercase character."); } if (passwordReqs.digitChar && !newPassword.match(/[0-9]/)) { - throw new _this.exec.Error("6db6", 400, "password must contain at least one numeric character."); + _this.exec.throwError("6db6", 400, "password must contain at least one numeric character."); } if (passwordReqs.specialChar && !newPassword.match(/[!#$%&()*+,-./:;<=>?@[\]^_`{|}~]/)) { - throw new _this.exec.Error("8b26", 400, "password must contain at least one special character (!#$%&()*+,-./:;<=>?@[\]^_`{|}~)."); + _this.exec.throwError("8b26", 400, "password must contain at least one special character (!#$%&()*+,-./:;<=>?@[\]^_`{|}~)."); } } diff --git a/handlers/createAsset.js b/handlers/createAsset.js index ebed637..d79ca7f 100644 --- a/handlers/createAsset.js +++ b/handlers/createAsset.js @@ -26,27 +26,24 @@ module.exports = function execute(ctx, req) { if (!ctx.config.storage) - throw new _this.exec.Error("e668", 500, "file upload is not supported for this site"); + _this.exec.throwError("e668", 500, "file upload is not supported for this site"); if(!ctx.userId) - throw new _this.exec.Error("4f53", 401, "anonymous upload is not supported"); + _this.exec.throwError("4f53", 401, "anonymous upload is not supported"); _this.helper.onBeginWriteRequest(ctx, "create", _this.db, null, { "ownerid": ctx.userId }, function(record, requestBody) { _this.storage.uploadFile(ctx, req, function (error, name) { - _this.exec.safeExecute(ctx, function() + if (error) { - if (error) - { - throw new _this.exec.Error("d2d0", 500, "error while uploading file to storage system"); - } - else + _this.exec.sendErrorResponse(ctx, "d2d0", 500, "error while uploading file to storage system"); + } + else + { + _this.db.insert(ctx, "asset", ["ownerid", "filename"], [ctx.userId, name], function (insertedId) { - _this.db.insert(ctx, "asset", ["ownerid", "filename"], [ctx.userId, name], function (insertedId) - { - ctx.res.send(insertedId.toString()); - }); - } - }); + ctx.res.send(insertedId.toString()); + }); + } }); }); } diff --git a/handlers/delete.js b/handlers/delete.js index 51a09c8..b595c7e 100644 --- a/handlers/delete.js +++ b/handlers/delete.js @@ -28,7 +28,7 @@ module.exports = _this.helper.onBeginWriteRequest(ctx, "delete", _this.db, recordId, null, function(record, requestBody) { if(ctx.entity === "user" && record.domain !== "local") - throw new _this.exec.Error("d789", 400, "updating external user info is not supported"); + _this.exec.throwError("d789", 400, "updating external user info is not supported"); _this.db.deleteRecord(ctx, ctx.entity, recordId, function(dbResponse) { ctx.res.send(dbResponse); diff --git a/handlers/deleteAsset.js b/handlers/deleteAsset.js index a99a2fd..007f849 100644 --- a/handlers/deleteAsset.js +++ b/handlers/deleteAsset.js @@ -26,29 +26,26 @@ module.exports = function execute (ctx, recordId) { if (!ctx.config.storage) - throw new _this.exec.Error("51be", 500, "file delete is not supported for this site"); + _this.exec.throwError("51be", 500, "file delete is not supported for this site"); if(!ctx.userId) - throw new _this.exec.Error("2c74", 401, "anonymous asset deletion is not supported"); + _this.exec.throwError("2c74", 401, "anonymous asset deletion is not supported"); _this.helper.onBeginWriteRequest(ctx, "delete", _this.db, recordId, null, function(record, requestBody) { if (!record.filename) - throw new _this.exec.Error("cd03", 500, "failed to get file name for the requested record"); + _this.exec.throwError("cd03", 500, "failed to get file name for the requested record"); _this.storage.deleteFile(ctx, record.filename, function (error) { - _this.exec.safeExecute(ctx, function() + if (error) { - if (error) - { - throw new _this.exec.Error("2020", 500, "Asset removal failed: " + error); - } - else - { - _this.db.deleteRecord(ctx, "asset", recordId, function(dbResponse) - { - ctx.res.send("Asset removed"); - }); - } - }); + _this.exec.sendErrorResponse(ctx, "2020", 500, "Asset removal failed: " + error); + } + else + { + _this.db.deleteRecord(ctx, "asset", recordId, function(dbResponse) + { + ctx.res.send("Asset removed"); + }); + } }); }); } diff --git a/handlers/read.js b/handlers/read.js index 3e2fa90..a880ac1 100644 --- a/handlers/read.js +++ b/handlers/read.js @@ -30,7 +30,7 @@ module.exports = if (requestParams.accessType === "private") { // private read mode. add owner role directly, add ownerid condition later - if (!ctx.userId) throw new _this.exec.Error("a058", 401, "Unauthorized"); + if (!ctx.userId) _this.exec.throwError("a058", 401, "Unauthorized"); ctx.userRoles.push("owner"); } @@ -107,7 +107,7 @@ module.exports = var val = parseInt(condition.getValue(fieldName)); if(!isNaN(val) && val !== ctx.userId) { - throw new _this.exec.Error("a19c", 401, "Unauthorized"); + _this.exec.throwError("a19c", 401, "Unauthorized"); } condition.children.push(new _this.condition.Condition(ctx.entity, fieldName, "=", ctx.userId)); } diff --git a/handlers/update.js b/handlers/update.js index 500d53e..90f05a1 100644 --- a/handlers/update.js +++ b/handlers/update.js @@ -36,11 +36,11 @@ module.exports = { } if(Object.keys(updateData).length === 0) { - throw new _this.exec.Error("582e", 400, "bad request"); + _this.exec.throwError("582e", 400, "bad request"); } if(ctx.entity === "user" && record.domain !== "local") { - throw new _this.exec.Error("511f", 400, "updating external user info is not supported"); + _this.exec.throwError("511f", 400, "updating external user info is not supported"); } var condition = new _this.condition.Condition(ctx.entity, "id", "=", recordId); _this.db.update(ctx, ctx.entity, updateData, condition, function(dbResponse) diff --git a/models/condition.js b/models/condition.js index 12f1339..fdb8ac2 100644 --- a/models/condition.js +++ b/models/condition.js @@ -108,7 +108,7 @@ module.exports = var fields = ctx.config.entities[ctx.entity].fields; if(!fields.hasOwnProperty(fieldName)) { - throw new _this.exec.Error("9d1b", 400, "unrecognized field " + fieldName + " found in condition"); + _this.exec.throwError("9d1b", 400, "unrecognized field " + fieldName + " found in condition"); } var fieldType = ctx.config.entities[ctx.entity].fields[fieldName].type; if(fieldType === "int") diff --git a/package.json b/package.json index 664ec42..e411165 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "orion-api", - "version": "1.2.12", + "version": "1.2.13", "description": "REST API server application", "main": "index.js", "repository": { diff --git a/services/auth.js b/services/auth.js index 9512f53..79f565e 100644 --- a/services/auth.js +++ b/services/auth.js @@ -43,7 +43,7 @@ module.exports = } catch(e) { - throw new _this.exec.Error("5192", 401, "invalid token"); + _this.exec.throwError("5192", 401, "invalid token"); } } if(ctx.userRoles.length === 0) @@ -64,7 +64,7 @@ module.exports = { verifyAuthSupported(ctx); if(!userName || !password) - throw new _this.exec.Error("003a", 400, "invalid login"); + _this.exec.throwError("003a", 400, "invalid login"); _this.db.quickFind( ctx, ["id", "password", "roles", "domain", "firstname", "lastname"], @@ -74,10 +74,10 @@ module.exports = { // verify login if(!user) - throw new _this.exec.Error("13c2", 400, "user not found with userName " + userName); - if(user.domain !== "local") throw new _this.exec.Error("24a7", 400, "external user login is not supported in this endpoint"); + _this.exec.throwError("13c2", 400, "user not found with userName " + userName); + if(user.domain !== "local") _this.exec.throwError("24a7", 400, "external user login is not supported in this endpoint"); var hashedInput = _this.hashPassword(ctx, password); - if(hashedInput !== user.password) throw new _this.exec.Error("003a", 400, "invalid login"); + if(hashedInput !== user.password) _this.exec.throwError("003a", 400, "invalid login"); // generate token createAndSendToken(ctx, user.id, "local", "", user.roles, user.firstname, user.lastname); } @@ -108,29 +108,32 @@ module.exports = }); response.on('end', function() { - var parsed = JSON.parse(body); - if(!parsed.hasOwnProperty("id")) - throw new _this.exec.Error("3f9c", 400, "bad request"); - _this.db.quickFind(ctx, ["id", "roles"], "user", {"domainid": parsed.id}, function(readResponse) + _this.exec.safeCallback(ctx, function() { - if(!readResponse) + var parsed = JSON.parse(body); + if(!parsed.hasOwnProperty("id")) + _this.exec.throwError("3f9c", 400, "bad request"); + _this.db.quickFind(ctx, ["id", "roles"], "user", {"domainid": parsed.id}, function(readResponse) { - _this.db.insert( - ctx, - "user", - ["domain", "domainid", "roles", "email", "firstname", "lastname", "createdtime"], - ["fb", parsed.id, "member", parsed.email, parsed.first_name, parsed.last_name, new Date().getTime()], - function(createResponse) - { - var id = createResponse[0].identity.toString(); - createAndSendToken(ctx, id, "fb", parsed.id, "member", parsed.first_name, parsed.last_name); - } - ); - } - else - { - createAndSendToken(ctx, readResponse.id, "fb", parsed.id, readResponse.roles, parsed.first_name, parsed.last_name); - } + if(!readResponse) + { + _this.db.insert( + ctx, + "user", + ["domain", "domainid", "roles", "email", "firstname", "lastname", "createdtime"], + ["fb", parsed.id, "member", parsed.email, parsed.first_name, parsed.last_name, new Date().getTime()], + function(createResponse) + { + var id = createResponse[0].identity.toString(); + createAndSendToken(ctx, id, "fb", parsed.id, "member", parsed.first_name, parsed.last_name); + } + ); + } + else + { + createAndSendToken(ctx, readResponse.id, "fb", parsed.id, readResponse.roles, parsed.first_name, parsed.last_name); + } + }); }); }); } @@ -157,7 +160,7 @@ module.exports = function verifyAuthSupported(ctx) { if (!ctx.config.auth) - throw new _this.exec.Error("94e8", 500, "Authentication is not supported for this site"); + _this.exec.throwError("94e8", 500, "Authentication is not supported for this site"); } //---------------------------------------------- diff --git a/services/exec.js b/services/exec.js index 7a6941a..e311387 100644 --- a/services/exec.js +++ b/services/exec.js @@ -75,11 +75,12 @@ module.exports = } /** - * Execute the given function and catch any exception that comes out of it + * Execute a callback and catch any exception that comes out of it. + * It's the responsibility of the caller to wrap the callback call with this function. * @param {any} ctx Request context - * @param {any} fn Function to execute + * @param {any} fn Callback function to execute */ - function safeExecute(ctx, fn) + function safeCallback(ctx, fn) { try { @@ -91,6 +92,26 @@ module.exports = } } + /** + * Throw an Error object up the call stack + */ + function throwError(tag, statusCode, msg) + { + throw new Error(tag, statusCode, msg); + } + + /** + * Send an error response + */ + function sendErrorResponse(ctx, tag, statusCode, msg) + { + _this.handleError(new Error(tag, statusCode, msg), ctx.req, ctx.res); + } + + //---------------------------------------------- + // PPRIVATE + //---------------------------------------------- + /** * Construct a new Error object. This will contain all details about an error. */ @@ -101,10 +122,6 @@ module.exports = this.msg = msg; } - //---------------------------------------------- - // PPRIVATE - //---------------------------------------------- - /** * Parse an error string and construct a new Error object. */ @@ -114,8 +131,9 @@ module.exports = } this.handleError = handleError; - this.safeExecute = safeExecute; - this.Error = Error; + this.safeCallback = safeCallback; + this.throwError = throwError; + this.sendErrorResponse = sendErrorResponse; _construct(); } }; \ No newline at end of file diff --git a/services/helper.js b/services/helper.js index 3a0d497..efae0d7 100644 --- a/services/helper.js +++ b/services/helper.js @@ -107,8 +107,11 @@ module.exports = resolveForeignKeys(ctx, requestBody, db, function (requestBody) { if (!!isWriteAllowedFn && !isWriteAllowedFn(action, ctx.userRoles, ctx.userId, null, requestBody)) - throw new _this.exec.Error("c75f", 400, "bad create request. operation not allowed."); - callback(null, requestBody); + _this.exec.throwError("c75f", 400, "bad create request. operation not allowed."); + _this.exec.safeCallback(ctx, function() + { + callback(null, requestBody); + }); }); } else @@ -116,7 +119,7 @@ module.exports = db.findRecordById(ctx, ctx.entity, recordId, function(record) { if(!record) - throw new _this.exec.Error("7e13", 400, "record not found with id " + recordId); + _this.exec.throwError("7e13", 400, "record not found with id " + recordId); record = _this.fixDataKeysAndTypes(ctx, record); if((ctx.entity === "user" && ctx.userId === record.id) || (ctx.entity !== "user" && ctx.userId === record.ownerid)) { @@ -124,8 +127,11 @@ module.exports = } validateRoles(ctx, action); if (!!isWriteAllowedFn && !isWriteAllowedFn(action, ctx.userRoles, ctx.userId, record, requestBody)) - throw new _this.exec.Error("29c8", 400, "bad " + action + " request. operation not allowed."); - callback(record, requestBody); + _this.exec.throwError("29c8", 400, "bad " + action + " request. operation not allowed."); + _this.exec.safeCallback(ctx, function() + { + callback(record, requestBody); + }); }); } } @@ -139,7 +145,7 @@ module.exports = function validateRoles(ctx, action) { if (!ctx.config.entities[ctx.entity].allowedRoles[action].containsAny(ctx.userRoles)) - throw new _this.exec.Error("c327", 401, "Unauthorized"); + _this.exec.throwError("c327", 401, "Unauthorized"); } //---------------------------------------------- @@ -193,7 +199,12 @@ module.exports = fieldNamesToResolve.push(fieldName); } if(fieldNamesToResolve.length === 0) - callback(requestBody); + { + _this.exec.safeCallback(ctx, function() + { + callback(requestBody); + }); + } else { var op = { active: fieldNamesToResolve.length, isCallbackCalled: false }; @@ -223,7 +234,10 @@ module.exports = requestBody[fk.resolvedKeyName] = _this.fixDataKeysAndTypes(ctx, record); if(op.active <= 0 && !op.isCallbackCalled) { - callback(requestBody); + _this.exec.safeCallback(ctx, function() + { + callback(requestBody); + }); op.isCallbackCalled = true; } }); diff --git a/test/tests/tests-item.js b/test/tests/tests-item.js index 21cb58f..6f17f72 100644 --- a/test/tests/tests-item.js +++ b/test/tests/tests-item.js @@ -17,7 +17,7 @@ module.exports = function(runner, params) 'post', {"name":"item123"}, params.user1Token, - [{"name":"insertError","params":[]}], + [], null, 400 ); diff --git a/test/tests/tests-user.js b/test/tests/tests-user.js index d38d61e..0cda30d 100644 --- a/test/tests/tests-user.js +++ b/test/tests/tests-user.js @@ -6,8 +6,8 @@ module.exports = function(runner, params) 'post', {"username":"testuser","password":"testpassword","confirmPassword":"testpassword","email":"invalidemail","firstName":"firstName","lastName":"lastName"}, null, - [{"name":"insertError","params":[]}], - [{"lastinsertedid":"1"}], + [], + [], 400 ); @@ -17,8 +17,8 @@ module.exports = function(runner, params) 'post', {"username":"testuser","password":"testpassword","email":"test@test.com","firstName":"firstName","lastName":"lastName"}, null, - [{"name":"insertError","params":[]}], - [{"lastinsertedid":"1"}], + [], + [], 400 ); @@ -28,8 +28,8 @@ module.exports = function(runner, params) 'post', {"username":"testuser","password":"test","confirmPassword":"test","email":"test@test.com","firstName":"firstName","lastName":"lastName"}, null, - [{"name":"insertError","params":[]}], - [{"lastinsertedid":"1"}], + [], + [], 400 );