Skip to content

Instantly share code, notes, and snippets.

@utkarshrai003
Created March 10, 2017 04:39
Show Gist options
  • Save utkarshrai003/04937b05be0abe892c319f65f9f84102 to your computer and use it in GitHub Desktop.
Save utkarshrai003/04937b05be0abe892c319f65f9f84102 to your computer and use it in GitHub Desktop.
// statusCode could be
// 200 - successfull
// 201 - successfully created
// data - could be array, object, string anything
// meta - any extra information that needs to be appended
// self - path for current api call
var success_response = (statusCode, data, meta = {}, self, res) => {
let resBody = {
status: statusCode,
data: data,
meta: meta,
self: self
}
res.ok(resBody);
}
// statusCode could be
// 400 - not successfull
// 401 - unauthorized
// 402 - unprocessable entity
// 500 - serve error
// error - are array of errors
// messsage - custom message to address the errors
var error_response = (statusCode, errors, message, self, res) => {
sails.log(errors);
let resBody = {
status: statusCode,
errors: errors,
message: message,
self: self
}
switch(statusCode) {
case 400:
res.badRequest(resBody);
break;
case 401:
res.unauthorized(resBody);
break;
case 403:
res.forbidden(resBody);
break;
case 404:
res.notFound(resBody);
break;
case 500:
res.serverError(resBody);
break;
}
};
// statusCode - 200, 400, 401, 500 etc
// data - array, object, string etc
module.exports = function(statusCode, data = {}, meta= {}) {
var req = this.req;
var res = this.res;
var statusCode = arguments[0];
var data, errors, meta, message, response;
sails.log(arguments);
res.status(statusCode);
if(statusCode >= 200 && statusCode < 300) {
data = arguments[1] || {};
meta = arguments[2] || {};
success_response(statusCode, data, meta, req.route.path, res);
}
else {
errors = arguments[1] || [];
message = arguments[2] || '';
error_response(statusCode, errors, message, req.route.path, res);
}
sails.log("Response sent !!");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment