【发布时间】:2018-09-01 16:49:27
【问题描述】:
我是 nodejs 和 express 的新手。
我正在尝试使用ts-express-decorators 创建一个休息服务。
在我的controller 中,我有一个POST 方法,它更新用户数据并返回更新后的结果。
但我尝试更新的集合中很少有我不想发送给用户的字段。
我的controller.ts
import { Controller, Get, PathParams, Authenticated, Required, Req, Post, Res, BodyParams } from 'ts-express-decorators';
import { Returns } from 'ts-express-decorators/lib/swagger';
@Controller('/users')
@Authenticated()
export class UserController {
constructor(private userService: UserService) { }
@Post('/update')
@Returns(UserResponse)
async updateUser(
@Req() req,
@Res() res) {
const data = await this.userService.updateUser(req.body)
return data;
}
}
这是user.ts
export class UserResponse {
@JsonProperty()
email: string;
@JsonProperty()
firstName: string;
@JsonProperty()
lastName: string;
@JsonProperty()
picture?: string;
@JsonProperty()
_id: string;
}
我想在UserResponse 类中构建我的响应。但目前它从集合中返回 json 将所有数据。
service.ts
async updateUser(data) {
return await this.userRepository.findByIdAndUpdate({_id: data.id}, data);
}
样板中的默认方法遵循相同的结构。
请指出我缺少什么或有更好的选择来实现这一点。
我可以在 controller.ts 中重构响应 json,但我不希望这样做。
我目前的回应:
{
"_id": "5b6aee50f31f19156c014933",
"email": "test@gmail.com",
"password": "ZAUzmguxklW7769Uc0CrUi",
"firstName": "Test",
"lastName": "Test",
"__v": 0,
"picture": "",
"tokens": []
}
预期响应:
{
"_id": "5b6aee50f31f19156c014933",
"email": "test@gmail.com",
"firstName": "Test",
"lastName": "Test",
"picture": ""
}
【问题讨论】:
标签: node.js typescript decorator