Koa Framework - Tuong-Nguyen/JavaScript-Structure GitHub Wiki
Features
- Minimal with Middlewares
// Add a middleware
app.use(async (ctx, next) => {
ctx.body = 'Hello World!';
});
- Call next to execute next middleware. Otherwise, it is not called.
- Future: async - await (ES8): no callback
async function foo() {
const userId = 42;
const user = await User.findById(userId);
return user.name;
}
- await for waiting an asynchronous (async) function to return.
- try/catch is used for handling exception.
http://koajs.com/)
API References (- Application:
- contains an array of middlewares which are cascading
const Koa = require('koa');
const app = new Koa();
// x-response-time
app.use(async function (ctx, next) {
const start = new Date();
await next();
const ms = new Date() - start;
ctx.set('X-Response-Time', `${ms}ms`);
});
// logger
app.use(async function (ctx, next) {
const start = new Date();
await next();
const ms = new Date() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});
// response
app.use(ctx => {
ctx.body = 'Hello World';
});
app.listen(3000);
- Context: encapsulate request, response objects.
- A context is created per request.
- context.req: Node's request object
- context.res: Node's response object
- context.request: Koa's request object (abstraction of Node's request) provides additional functionality
- context.response: Koa's response object (abstraction of Node's response) provides additional functionality
- context.state: recommended namespace for passing information through middlewares and views
https://www.tutorialspoint.com/koajs/
Libraries
Middlewares
- koa-static
- koa-bodyparser
- koa-router
- koa-views: render html using different template engine.
- koa-session: Simple session middleware for Koa. default is cookie-based session and support external store.
- koa-mount: Mount other Koa applications as middleware.
Supported libraries
- nconf: Key-Value store which can load data from argv - env - file setting. (Preferred!)
- dotenv: allow us to define values in .env file and get them to process.env namespace
- Winston: node logger
- [koa-morgan]: Http logger which logs http request and response
Database
- mongodb-migration: tool & library for migrating mongo database which can be used in integration with database.
- koa-mongo