At the heart of KOA is the middleware mechanism, where CTX objects are eventually returned after each middleware process. We can use the official koa-compose for this chain treatment.
The use of koa – compose
Let’s take a look at how libraries are used in general. The simplest interface to get a list of users:
async function findUsers(ctx) {
try {
ctx.body = awaitCall another method to the database to find the user ({query: ctx.request.query })
} catch (err) {
ctx.status = 404
ctx.body = { err, message: err.message }
}
}
Copy the code
We want to check the interface’s query parameters, and the code we use to check should be generic, abstracting a validatorMiddleware:
async function validatorMiddleware(ctx, next) {
// verify the query parameters
await next() // Call the next middleware
}
Copy the code
When we export the interface we will use koa-compose to do this:
const compose = require('koa-compose')
module.exports = compose([
validatorMiddleware,
findUsers
])
Copy the code
The source code
How does KoA-Compose combine multiple middleware components? The source code for Koa-compose is very simple, with only a few dozen lines (source address: github.com/koajs/compo…). :
'use strict'
/** * Expose compositor. */
module.exports = compose
/** * Compose `middleware` returning * a fully valid middleware comprised * of all those which are passed. * * @param {Array} middleware * @return {Function} * @api public */
function compose (middleware) {
if (!Array.isArray(middleware)) throw new TypeError('Middleware stack must be an array! ')
for (const fn of middleware) {
if (typeoffn ! = ='function') throw new TypeError('Middleware must be composed of functions! ')}/** * @param {Object} context * @return {Promise} * @api public */
return function (context, next) {
// last called middleware #
let index = - 1
return dispatch(0)
function dispatch (i) {
if (i <= index) return Promise.reject(new Error('next() called multiple times'))
index = i
let fn = middleware[i]
if (i === middleware.length) fn = next
if(! fn)return Promise.resolve()
try {
return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
} catch (err) {
return Promise.reject(err)
}
}
}
}
Copy the code
- Use the index variable to cache the number of middleware calls to prevent multiple calls to next() in some middleware:
let index = - 1
return dispatch(0)
function dispatch (i) {
if (i <= index) return Promise.reject(new Error('next() called multiple times'))... }Copy the code
- To recursively call the middleware in the Middleware array:
function dispatch (i) {... let fn = middleware[i] ... try {return Promise.resolve(fn(context, dispatch.bind(null, i + 1)));
} catch (err) {
return Promise.reject(err)
}
}
Copy the code
- According to the array subscript, judge that the last middleware has been called (there is no next middleware), return a Promise object with the depressing state, and return the middleware of the next layer (function unstack) :
if (i === middleware.length) fn = next
if(! fn)return Promise.resolve()
Copy the code
reference
Take you into the world of KOA2 (KOA2 source talk) : imhjm.com/article/591…