Web应用开发框架-koa(三)——koa中间件之概念、洋葱模型-执行顺序、异步中间件、koa-compose中间件合成-compsoe函数
中间件
1.logger
Koa 的最大特色,也是最重要的一个设计,就是中间件(middleware)。为了理解中间件,我们先看一下 Logger (打印日志)功能的实现。
最简单的写法就是在main
函数里面增加一行。
const main = ctx => {
console.log(`${
Date.now()} ${
ctx.request.method} ${
ctx.request.url}`); ctx.response.body = 'Hello World'; };
2. 中间件的概念
上一个例子里面的 Logger 功能,可以拆分成一个独立函数。
const logger = (ctx, next) => {
console.log(`${
Date.now()} ${
ctx.request.method} ${
ctx.request.url}`); next(); } app.use(logger);
实例1
logger.js
var koa = require('koa'); var app = new koa(); var route = require('koa-route'); // 中间件 - 日志 中间件 // 中间件的核心其实是 koa在use里面注入的 next方法 var logger = (ctx, next) => {
next(); console.log(` 中间件执行--- 方法: ${
ctx.request.method} 路径: ${
ctx.request.path}`); } const main = (ctx, next) => {
// console.log(`方法: ${ctx.request.method} 路径: ${ctx.request.path}`); ctx.response.body = 'hello world'; next(); console.log('main') } const qita = (ctx, next) => {
// console.log(`方法: ${ctx.request.method} 路径: ${ctx.request.path}`); ctx.response.body = 'qita'; next(); } app.use(logger); app.use(route.get('/', main)); // 1. 路径 2. ctx函数 app.use(route.get('/qita', qita)); app.listen(3000); // 起服务 , 监听3000端口
3.中间件执行顺序
const one = (ctx, next) => {
console.log('>> one'); next(); console.log('<< one'); } const two = (ctx, next) => {
console.log('>> two'); next(); console.log('<< two'); } const three = (ctx, next) => {
console.log('>> three'); next(); console.log('<< three'); } app.use(one); app.use(two); app.use(three);
结果如下:
>> one >> two >> three << three << two << one
洋葱模型
其实就是想向我们表达,调用next的时候,中间件的代码执行顺序是什么。
实例2
model.js
var koa = require('koa'); var app = new koa(); // next前面的代码,按照use的顺序执行,next后面的代码反着执行。 // koa结论: next方法其实就是指的, 当前执行函数的下一个use里面的方法。 const one = (ctx, next) => {
console.log('>> one'); next(); // tow console.log('<< one'); } const two = (ctx, next) => {
console.log('>> two'); next(); // three console.log('<< two'); } const three = (ctx, next) => {
console.log('>> three'); next(); // 空 console.log('<< three'); } // 他们3个都是中间件, next app.use(one); app.use(two); app.use(three); app.listen(3000);
4.异步中间件
迄今为止,所有例子的中间件都是同步的,不包含异步操作。如果有异步操作(比如读取数据库),中间件就必须写成 async 函数。请看
const fs = require('fs.promised'); const Koa = require('koa'); const app = new Koa(); const main = async function (ctx, next) {
ctx.response.type = 'html'; ctx.response.body = await fs.readFile('./demos/template.html', 'utf8'); }; app.use(main); app.listen(3000);
实例3
async.js
var koa = require('koa'); var app = new koa(); // next前面的代码,按照use的顺序执行,next后面的代码反着执行。 var log3 = function() {
return new Promise((res, rej) => {
setTimeout(() => {
console.log('<< three'); res() }, 2000); }); } // koa结论: next方法其实就是指的, 当前执行函数的下一个use里面的方法。 const one = async function(ctx, next) {
console.log('>> one'); await next(); // tow console.log('<< one'); } const two = async function(ctx, next) {
console.log('>> two'); await next(); // three console.log('<< two'); } // koa支持 es7 async和 await const three = async function(ctx, next) {
console.log('>> three'); next(); // 空 // console.log('<< three'); // await setTimeout(() => { // await需要 promise // console.log('<< three') // }; await log3(); } // three(); // 他们3个都是中间件, next app.use(one); app.use(two); app.use(three); app.listen(3000);
5. 中间件的合成
koa-compose模块可以将多个中间件合成为一个。
const compose = require('koa-compose'); const logger = (ctx, next) => {
console.log(`${
Date.now()} ${
ctx.request.method} ${
ctx.request.url}`); next(); } const main = ctx => {
ctx.response.body = 'Hello World'; }; const middlewares = compose([logger, main]); app.use(middlewares);
compose简单介绍
var greeting = (firstName, lastName) => 'hello, ' + firstName + ' ' + lastName var toUpper = str => str.toUpperCase() var fn = compose(toUpper, greeting) console.log(fn('jack', 'smith')) // Hello Jack Smith
compose
的参数是函数,返回的也是一个函数- 因为除了第一个函数的接受参数,其他函数的接受参数都是上一个函数的返回值,所以初始函数的参数是
多元
的,而其他函数的接受值是一元
的 compsoe
函数可以接受任意的参数,所有的参数都是函数,且执行方向是自右向左
的,初始函数一定放到参数的最右面
到此这篇Web应用开发框架-koa(三)——koa中间件之概念、洋葱模型-执行顺序、异步中间件、koa-compose中间件合成-compsoe函数的文章就介绍到这了,更多相关内容请继续浏览下面的相关推荐文章,希望大家都能在编程的领域有一番成就!参考链接: https://segmentfault.com/a/94749
版权声明:
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若内容造成侵权、违法违规、事实不符,请将相关资料发送至xkadmin@xkablog.com进行投诉反馈,一经查实,立即处理!
转载请注明出处,原文链接:https://www.xkablog.com/yd-ios/10794.html