Skip to content

Instantly share code, notes, and snippets.

@ericmuyser ericmuyser/api.js
Created Feb 22, 2016

Embed
What would you like to do?
Barebones Node.js API
module.exports = function(app) {
function sendResponse(res, callback, code, message, data) {
var data = {code: code, message: message, data: data};
var content;
if (callback) {
content = callback + '(' + JSON.stringify(data) + ')';
res.writeHead(200, {
'Content-Length': lengthInUtf8Bytes(content),
'Content-Type': "application/javascript"
});
}
else {
content = JSON.stringify(data);
res.writeHead(200, {
'Content-Length': lengthInUtf8Bytes(content),
'Content-Type': "application/json"
});
}
res.write(content);
res.end();
}
function lengthInUtf8Bytes(str) {
// Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence.
var m = encodeURIComponent(str).match(/%[89ABab]/g);
return str.length + (m ? m.length : 0);
}
var SUCCESS_CODE = 10,
ERROR_CODE = 11;
// TODO: compiling this list from route definitions would be cleaner
var api = {
routes: {
put: {
'pages': function (match, req, res, next) {
var queryData = url.parse(req.url, true).query;
}
},
delete: {
'users': function (match, req, res, next) {
var queryData = url.parse(req.url, true).query;
var id = queryData['id'];
}
},
post: {
'pages': function (match, req, res, next) {
var queryData = url.parse(req.url, true).query;
},
'account/register': function (match, req, res, next) {
passport.authenticate('signup', function (err, user) {
});
})(req, res, next);
},
'account/login': function (match, req, res, next) {
passport.authenticate('signin', function (err, user) {
});
})(req, res, next);
}
},
get: {
'session': function (match, req, res, next) {
},
'pages/([0-9]+)': function (match, req, res, next) {
var queryData = url.parse(req.url, true).query;
},
}
}
};
return function (req, res, next) {
var requestType = req.method.toLowerCase();
for (var route in api.routes[requestType]) {
var match = new RegExp("/v1/" + route).exec(req.url);
if (match) {
console.log('Routing to ' + req.method + ' ' + route, match);
api.routes[requestType][route](match, req, res, next);
return; // we'll let the route take it from here
}
}
// there were no matches
next();
};
};
var express = require('express');
var app = express();
// use cookieParser, passport, etc.
var api = require('./api')(app);
app.use(api);
app.listen(5061);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.