视图的职责是基于模型渲染真正的内容响应给客户端,同时还需要告诉浏览器内容类型 content-type。
定义
export interface View {readonly contentType: string;render(model: any): Promise<void>;support(viewName: string): Promise<boolean>;}
实现
@Component(View)export class JsonView implements View {static VIEW_NAME = 'json';readonly contentType = 'application/json';readonly priority = 500;async render(model: any): Promise<void> {const response = Context.getCurrent().response;response.body = JSON.stringify(model);}support(viewName: string): Promise<boolean> {return Promise.resolve(viewName === JsonView.VIEW_NAME);}}
使用
@Controller('users')export class UserController {@Get(':id')@View(JsonView.VIEW_NAME)get(@Param() id: string) {...}}
