Cookies 是使用 cookies 模块来管理,通过 Malagu 中间件集成进来。
创建 Cookie 管理器
import { Context } from '../context';
import { Component, Value } from '@malagu/core';
import * as _Cookies from 'cookies';
import { Cookies } from './cookies-protocol';
@Component()
export class CookiesFactory {
@Value('malagu.cookies.keys')
protected keys?: string[];
@Value('malagu.cookies.secure')
protected secure?: boolean;
async create(): Promise<Cookies> {
const cookies = new _Cookies(Context.getRequest() as any, Context.getResponse() as any, {
keys: this.keys,
secure: this.secure
});
return <Cookies>cookies;
}
}
集成 Cookie 管理器
@Component(Middleware)
export class CookiesMiddleware implements Middleware {
@Autowired(CookiesFactory)
protected readonly cookiesFactory: CookiesFactory;
async handle(ctx: Context, next: () => Promise<void>): Promise<void> {
if (ctx.request) {
Context.setCookies(await this.cookiesFactory.create());
}
await next();
}
readonly priority = COOKIES_MIDDLEWARE_PRIORITY;
}
获取 Cookie
import { Context } from '@malagu/web/lib/node';
const foo = Context.getCookies().get('foo');
设置 Cookie
import { Context } from '@malagu/web/lib/node';
Context.getCookies().set('foo', 'bar');