【问题标题】:Nodejs + Typescript: How to define response structure with modelNodejs + Typescript:如何用模型定义响应结构
【发布时间】:2018-09-01 16:49:27
【问题描述】:

我是 nodejsexpress 的新手。

我正在尝试使用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


    【解决方案1】:

    现在,当您的代码被转译为 JavaScript 时,它会简单地返回 await this.userService.updateUser(req.body) 的结果。

    您需要从data 变量创建UserResponse 的新实例。在UserResponse 的实例中显式设置要设置的所有字段。然后你必须返回 UserResponse 的实例而不是 data 变量。

    例子:

    const response = new UserResponse();
    response._id = data._id;
    response.email = data.email;
    response.firstName = data.firstName;
    response.lastName = data.lastName;
    return response;
    

    我可能会为UserResponse 创建一个接受所需参数的新构造函数。

    【讨论】:

    • 您能否提供一个简单的示例来说明如何实现这一目标?我应该喜欢new UserResonse()等等吗?
    • 是的,你必须这样做。添加了一个示例。
    猜你喜欢
    • 2023-03-14
    • 2018-06-04
    • 2021-08-17
    • 1970-01-01
    • 2021-11-29
    • 1970-01-01
    • 2017-09-18
    • 2023-03-08
    • 2012-06-03
    相关资源
    最近更新 更多