Skip to content

Instantly share code, notes, and snippets.

@yarax
Last active September 2, 2016 08:01
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yarax/e68c76233f5600363fd8943a43afe480 to your computer and use it in GitHub Desktop.
Save yarax/e68c76233f5600363fd8943a43afe480 to your computer and use it in GitHub Desktop.
const http = require('http');
// Swagger-like API description
const api = {
'/users': {
'get': {
'parameters': {
'role': {
'in': 'query'
},
'session_id': {
'in': 'cookies'
}
},
'x-handler': 'getUsers'
}
}
};
function getUsers(role, session_id) {
return checkSession(session_id)
.then(getUserByRole(role));
}
/**
* @param {Object} req node req object
* @return {Array} params
*/
function prepareParamsBasedOnSchema(req) {
// processing request, including all possible HTTP cases
}
function getHandlerForRequest(req) {
// retrieving handler from current req based on schema
}
/**
* @param res node res object
* @returns {function()}
*/
function formResponseBasedOnSchema(res) {
return (result) => {
// Filling headers according to schema
// Sending result
}
}
function errorHandler(res) {
return (error) => {
// log error and send some response
}
}
http.createServer((req, res) => {
const params = prepareParamsBasedOnSchema(req);
const handler = getHandlerForRequest(req);
handler.apply(null, params)
.then(formResponseBasedOnSchema(res))
.catch(errorHandler(res));
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment