setLocaleToCtx.middleware.ts 782 B

123456789101112131415161718192021222324
  1. import { IMiddleware } from '@midwayjs/core';
  2. import { Middleware } from '@midwayjs/decorator';
  3. import { NextFunction, Context } from '@midwayjs/koa';
  4. import { head, last } from 'lodash';
  5. @Middleware()
  6. export class SetLocaleToCtxMiddleware implements IMiddleware<Context, NextFunction> {
  7. resolve() {
  8. return async (ctx: Context, next: NextFunction) => {
  9. const cookies = ctx.request.headers.cookie;
  10. let arr = cookies.split(';');
  11. arr = arr.filter(f => f.includes('locale='));
  12. // 没找到locale就默认使用中文
  13. if (arr.length <= 0) arr = ['locale=zh-cn'];
  14. const a2 = head(arr).split('=');
  15. const locale = last(a2);
  16. ctx.locale = locale;
  17. await next();
  18. };
  19. }
  20. static getName(): string {
  21. return 'setLocale';
  22. }
  23. }