• 云开发 Laf
  • 小火柴系列!!! 一周一技:在云函数实现简单的中间件函数

云函数挂载在 init ,后续还可以继续扩展

import FunctionContext from '@lafjs/cloud'

interface Middleware {
  (ctx: FunctionContext, next: () => Promise<void>): Promise<void>;
}

function compose(middlewares: Middleware[]) {
  return async (ctx: FunctionContext) => {
    const exec = async (index: number) => {
      if (index === middlewares.length) return;

      const middleware = middlewares[index];

      const next = () => exec(index + 1);

      await middleware(ctx, next);
    };

    return exec(0);
  }
}

const logger: Middleware = async (ctx, next) => {
   console.log('logger')
  next()
};

const auth: Middleware = async (ctx, next) => {
  console.log('auth')
  next()
};

const app = compose([logger, auth]);

export default async function (ctx: FunctionContext) {
  await app(ctx);
  
  // main logic
}

demo: 在中间件模式中,context对象是各个中间件共享的,可以用来在中间件之间传递数据和信息。

const logger: Middleware = async (ctx, next) => {
   // 在ctx中写入用户信息
  ctx.user = ['adds'];
   console.log('logger')
  next()
};

const auth: Middleware = async (ctx, next) => {
  console.log('auth')
  console.log(ctx.user)
  next()
};
[2023-07-18 11:30:07]
'logger'
[2023-07-18 11:30:07]
'auth'
[2023-07-18 11:30:07]
[ 'adds' ]

代码比较粗犷,后续再封装优化