snapi2
Version:
An API-first RESTful server framework built on Swagger and Restify
78 lines (64 loc) • 1.99 kB
JavaScript
// Generated by CoffeeScript 1.12.7
;
var Promise, Responder, Response, codes, errors, jsonStream, stream;
Promise = require('bluebird');
errors = require('restify-errors');
stream = require('stream');
jsonStream = require('JSONStream');
Response = require('./response').Response;
codes = {
successWithBody: 200,
successNoBody: 204,
movedPermanently: 301,
found: 302,
internalError: 500,
invalidCredentials: 401,
notAuthorized: 403
};
module.exports = Responder = (function() {
function Responder(logger) {
this.logger = logger;
}
Responder.prototype.errorResponse = function(err, response, next) {
this.logger.log.error(err);
if (err instanceof errors.InvalidCredentialsError) {
response.header('Www-Authenticate', 'Basic');
}
return next(err);
};
Responder.prototype.respondStream = function(result, response) {
var ref;
response.writeHead(200, {
'Content-Type': 'application/json; charset=utf-8'
});
if (result.objectMode || ((ref = result._readableState) != null ? ref.objectMode : void 0)) {
return result.pipe(jsonStream.stringify()).pipe(response);
} else {
return result.pipe(response);
}
};
Responder.prototype.respond = function(result, response, next) {
var body, header, ref, statusCode, value;
if (result instanceof Error) {
return this.errorResponse(result, response, next);
}
if (result instanceof stream.Stream) {
return this.respondStream(result, response);
}
body = result;
statusCode = result != null ? codes.successWithBody : codes.successNoBody;
if (result instanceof Response) {
ref = result.headers;
for (header in ref) {
value = ref[header];
response.header(header, value);
}
body = result.body;
statusCode = result.statusCode;
}
response.send(statusCode, body);
return next();
};
Responder.prototype.codes = codes;
return Responder;
})();