Cookies 是使用 cookies 模块来管理,通过 Malagu 中间件集成进来。

创建 Cookie 管理器

  1. import { Context } from '../context';
  2. import { Component, Value } from '@malagu/core';
  3. import * as _Cookies from 'cookies';
  4. import { Cookies } from './cookies-protocol';
  5. @Component()
  6. export class CookiesFactory {
  7. @Value('malagu.cookies.keys')
  8. protected keys?: string[];
  9. @Value('malagu.cookies.secure')
  10. protected secure?: boolean;
  11. async create(): Promise<Cookies> {
  12. const cookies = new _Cookies(Context.getRequest() as any, Context.getResponse() as any, {
  13. keys: this.keys,
  14. secure: this.secure
  15. });
  16. return <Cookies>cookies;
  17. }
  18. }

集成 Cookie 管理器

  1. @Component(Middleware)
  2. export class CookiesMiddleware implements Middleware {
  3. @Autowired(CookiesFactory)
  4. protected readonly cookiesFactory: CookiesFactory;
  5. async handle(ctx: Context, next: () => Promise<void>): Promise<void> {
  6. if (ctx.request) {
  7. Context.setCookies(await this.cookiesFactory.create());
  8. }
  9. await next();
  10. }
  11. readonly priority = COOKIES_MIDDLEWARE_PRIORITY;
  12. }

获取 Cookie

  1. import { Context } from '@malagu/web/lib/node';
  2. const foo = Context.getCookies().get('foo');

设置 Cookie

  1. import { Context } from '@malagu/web/lib/node';
  2. Context.getCookies().set('foo', 'bar');