snapi2
Version:
An API-first RESTful server framework built on Swagger and Restify
93 lines (84 loc) • 2.71 kB
JavaScript
// Generated by CoffeeScript 1.12.7
;
var Promise, error, registerRoute, restifyMethod, restifyPath, simplifySwaggerParams, swagger2;
Promise = require('bluebird');
swagger2 = require('swagger2-utils');
error = require('./error');
restifyMethod = function(method) {
if (method === 'delete') {
return 'del';
} else {
return method;
}
};
restifyPath = function(path) {
path = path.split('{').join(':');
return path.split('}').join('');
};
exports.simplifySwaggerParams = simplifySwaggerParams = function(swaggerParams) {
var param, paramName, params, ref;
if (swaggerParams == null) {
swaggerParams = {};
}
params = {};
for (paramName in swaggerParams) {
param = swaggerParams[paramName];
switch ((ref = param.schema) != null ? ref.type : void 0) {
case 'number':
case 'integer':
if (typeof param.value !== 'number') {
param.value = param.value - 0;
}
break;
case 'boolean':
if (typeof param.value !== 'boolean') {
param.value = (function() {
switch (param.value) {
case 'true':
return true;
case 'false':
return false;
default:
throw new Error("Invalid boolean value: " + param.value);
}
})();
}
}
params[paramName] = param.value;
}
return params;
};
registerRoute = function(server, method, path, handler) {
method = restifyMethod(method);
path = restifyPath(path);
return server[method]({
url: path
}, function(request, response, next) {
return Promise["try"](function() {
var params, ref;
params = simplifySwaggerParams(request != null ? (ref = request.swagger) != null ? ref.params : void 0 : void 0);
return handler(request, params);
}).then(function(result) {
return server.responder.respond(result, response, next);
})["catch"](function(err) {
return server.responder.errorResponse(err, response, next);
});
});
};
exports.registerRoutes = function(server, apiSpec, opts) {
var i, len, operation, operations, results, routeHandlers;
if (!opts.routeHandlers) {
throw new error.MissingRouteHandlersConfigError;
}
routeHandlers = opts.routeHandlers;
operations = swagger2.createOperationsList(apiSpec);
results = [];
for (i = 0, len = operations.length; i < len; i++) {
operation = operations[i];
if (routeHandlers[operation.operationId] == null) {
throw new error.MissingRouteHandlerError(operation);
}
results.push(registerRoute(server, operation.method, operation.path, routeHandlers[operation.operationId]));
}
return results;
};