content-type-router

1.3.0 • Public • Published

Entrance

You need to pass 4 parameters to the init() function: request, response, environment object and router map.

  • request is the same object from http.createServer callback.
  • response is the same object from http.createServer callback.
  • env is anything you want to pass to your handler. For example database object.
  • map is a string/function mapping const. It indicates which handler function should a request with specific path be mapped to.
const router = require('mime-router');
const file = require('./local_modules/object/file.js'); // Your handler module
const test = require('./local_modules/object/test.js'); // Your handler module
const map = {
    '/test/server': test.server,
    '/file/upload': file.upload,
};
const env = {
    database: null // Let's say you want to pass a database to the handler too
}
const server = http.createServer(function (req, res) {
    router.init(req, res, env, map);
});
server.listen(process.env.PORT || 8000);

Processing

  • If the request contentType is application/json, the module will process and transform the body into a json object.
  • If the request contentType is text/plain, the module will pass the text directly.
  • If the request contentType is almost everything else, the module will assume it's a file and form up an object like this:
{
    "buffer": [],
    "contentType": "image/png",
    "category": "image"
}

Handler

A handler function should always have a signature like this:

function handler(req, res, env, data) {
    // Deal with the data
}

Depends on the Content-Type in request header, data will be:

  • JSON object if Content-Type is "application/json".
  • String if Content-Type is "text/plain".
  • JSON object listing in the Processing section if Content-Type is anything else.

Readme

Keywords

Package Sidebar

Install

npm i content-type-router

Weekly Downloads

0

Version

1.3.0

License

MIT

Last publish

Collaborators

  • tclzcja