HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Asynchronous lightweight JSON API

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
asynchronouslightweightapijson

Problem

I am writing a lightweight JSON API, and I come from a PHP background, so I have some questions/reviews about async node.js code.

This is my code so far:

main.js

var http = require('http');
var api = require('./api.js');

api.addRoute({
    'method': 'POST',
    'url': '/users',
    'input': {
        'fullName': {
            type: String,
            required: true,
            min: 2,
            max: 64
        },
        'email': {
            type: String,
            required: true,
            match: /^(.*)@(.*).(.*)$/,
            min: 2,
            max: 64
        },
        'password': {
            type: String,
            required: true,
            min: 2,
            max: 64
        }
    },
    'description': 'Create an user account.'
});

var server = http.createServer(api.handleRequest).listen(3000);


api.js

```
var api = exports;
var routes = [];

var postMaxSize = 1000;
var postTotalReceived = 0;

function getInput(req, res, callback){
if(req.method === 'POST' || req.method === 'PUT'){
var queryString = require('querystring');
var inputData = '';

req.on('data', function(data){
if(data.length < postMaxSize && postTotalReceived < postMaxSize){
inputData += data;
postTotalReceived += data.length;
} else {
res.statusCode = 413;
res.end('max-size');
}
});

req.on('end', function(){
callback(queryString.parse(inputData));
});
} else {
callback(false);
}
};

api.addRoute = function(route){
routes.push(route);
}

function getRoute(req, res, callback){
for(var i = 0; i < routes.length; i++){
if(routes[i]['method'] === req.method){ // If the request method matches.
if(typeof(routes[i]['url'] === 'string') && routes[i]['url'] === req.url){
callback(routes[i]);
}
} else {
var matches = req.ur

Solution

From a once over:

  • Not sure why you are not parsing the querystring for GET requests? It seems wrong



  • if(data.length



  • Not sure what happens in your code after setting the 413, it seems you have some loose ends there. You could consider redefining callback to function(){}



-
I would not store the routes as an array, the lookup time is too slow in my mind, instead I would store the routes in an object like this:

api.addRoute = function(route){
  routes[route.method][route.url] = route;
}


  • I read your code several times, it seems as if even if the method of a route does not match you will still execute the route if the url` matches through a regex. If so, then that is completely wrong.

Code Snippets

api.addRoute = function(route){
  routes[route.method][route.url] = route;
}

Context

StackExchange Code Review Q#14416, answer score: 2

Revisions (0)

No revisions yet.