UNPKG

content-type-router

Version:

This is a strictly structured router module designed for internal use only. It assumes all incoming request are either json, text or file/blob via POST method. It doesn't parse flexible parameter in path either.

55 lines (44 loc) 1.91 kB
# 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. ```javascript 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: ```json { "buffer": [], "contentType": "image/png", "category": "image" } ``` # Handler A handler function should always have a signature like this: ```javascript 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.