The recommended titbit in this issue is a Web backend framework for the node.js environment, supporting HTTP/HTTPS/HTTP2, and supporting configuration switching. Provides middleware and grouping mechanism. And provides many extensions for quickly building services.
titbit core function
- Request context design masks interface differences.
- Middleware pattern.
- Route grouping and naming.
- The middleware groups the execution according to the route.
- Middleware matches request method and routing execution.
- Start the daemon process: use the cluster module.
- Displays the load of the child process.
- body data is parsed by default.
- Support for enabling HTTP/1.1 or HTTP/2 services through configuration.
- Enable the HTTPS service (HTTPS must be enabled for HTTP/2 services).
- Limit the number of requests.
- Limits the maximum number of accesses to a single IP over a period of time.
- IP blacklist and IP whitelist.
- In cluster mode, the monitoring child process restarts if it exceeds the maximum memory limit.
- Automatic load mode is optional: a new child process is created according to the load to handle the request, and the initial state is restored when idle.
Installation
npm i titbit
Can also be installed using yarn:
yarn add titbit
Example: Add a route
'use strict'
const titbit = require('titibit')
const app = new titbit()
app.get('/', async c => {
//data is of type string|Buffer. You can set c.res.encoding to the encoding of the returned data. The default is 'utf8'.
c.res.body = 'success'
})
// The default listener is 0.0.0.0, with the same parameters as the native interface listen.
app.run(1234)
Route and request type
The starting line of HTTP gives the request type, also known as: Request method. Current request method:
GET POST PUT DELETE OPTIONS TRACE HEAD PATCH
示例:
'use strict';
const titbit = require('titibit');
const app = new titbit({
debug: true
});
app.get('/', async c => {
c.res.body = 'success';
});
app.get('/p', async c => {
c.res.body = `${c.method} ${c.routepath}`;
});
app.post('/', async c => {
// Return uploaded data
c.res.body = c.body;
});
app.put('/p', async c => {
c.res.body = {
method : c.method,
body : c.body,
query : c.query
};
});
// The default listener is 0.0.0.0, with the same parameters as the native interface listen.
app.run(8080);
Get URL parameters and form data
- Query string in the URL (? a=1& Arguments of the form b=2) are resolved into c.query.
- The form submission data is parsed into C.bDY.
The content-type of the form is application/x-www-form-urlencoded
'use strict';
const titbit = require('titbit');
var app = new titbit();
var {router} = app;
router.get('/q', async c => {
// in the URL? The subsequent query string is parsed into query.
c.res.body = c.query; // Returns JSON text, the main difference is that the content-type in the header is text/json
});
router.post('/p', async c => {
//POST, PUT the submitted data is saved to the body, if it is a form it is automatically parsed, otherwise just the original text value is saved,
// Middleware can be used to process a variety of data.
c.res.body = c.body;
});
app.run(2019);
body Maximum data size limit
'use strict'
const titbit = require('titbit')
const app = new titbit({
// The maximum amount of data allowed for a POST or PUT request is approximately 20M.
// The unit is bytes.
maxBody: 20000000
})
//...
app.run(1234)
Middleware
Middleware is a very useful pattern, which is somewhat different in different languages, but in essence there is no difference. The operation mechanism of middleware allows developers to better organize code and facilitate the implementation of complex logic requirements. In fact, the entire framework runs on middleware patterns.
At the design level, the middleware of this framework can also identify different request types according to route groups, and determine whether to execute or skip to the next layer, so the speed is very fast, and multiple routes and groups have their own middleware, which does not conflict with each other, and will not make meaningless calls. The reference form is as follows:
/*
The second parameter can be left blank, indicating that the middleware is enabled globally.
Now the second parameter indicates that only the POST request method is executed, and the route grouping must be /api.
Based on this design, it can be guaranteed to perform on demand without doing too many meaningless operations.
*/
app.add(async (c, next) => {
console.log('before');
await next();
console.log('after');
}, {method: 'POST', group: '/api'});
titbit完整的流程图示
Log
The framework itself provides the global logging function, when using cluster mode (using daemon interface to run the service), using the initialization option globoalLog can enable global logging, and can specify the log file, in single process mode, the log will be output to the terminal. At this point the log can still be saved to a file using output redirection and error output redirection.
Message event processing
Based on message events, in daemon mode (based on the cluster module), a setMsgEvent function is provided to obtain and process event messages sent by child processes.
This requires that the message sent by the worker process must be an object, where the type attribute is required, representing the name of the message event. The data in other fields can be customized.
Other
- titbit will have a last-wrapped middleware to do the final processing after running, so setting the value of c.res.body will return data. The default will detect some simple text type and automatically set the content-type (text/plain, text/HTML, application/json). Note that this is done without setting the content-type.
- limits the maximum url length by default, and also sets a maximum memory usage depending on the hardware.
- All of this can be extended and overwritten by configuration options or middleware, with both limitations and freedom.