0

我的 GraphQL 服务器以这种结构返回数据:

{
    data: {
        login: {
            success: boolean,
            type: string,
            details: string,
            data: any
        }
    }
}

我希望我的应用程序(Angular)接收数据并将其反序列化为一个 Response 对象,该对象具有以下结构:

{
    success: boolean,
    type: string,
    details: string,
    data: any
}

目前,我正在做的是使用 Apollo.query() 从 GraphQL 服务器获取数据。然后订阅它返回的 observable,然后从响应中选择 res.data.login 字段并将其分配给一个新的 Response 对象。

这是类响应:

// Object to hold response data received from server
export class Response implements Deserializable {
    // Member data
    success: boolean;                                                   // To store success or failure code
    type: string;                                                       // To store type of response
    details: string;                                                    // To store additional details
    data: any;                                                          // To store returned data

    // Member methods
    // Method to deserialize input data into this object
    deserialize(data: any): this {
        Object.assign(this, data);
        return this;
    }
}

这是 Angular 服务 user.service.ts:

// Sending input credentials to backend and getting back response
return this.apolloClient.query({
    query: loginUserQuery(cred),
    context: options
});

这是订阅它的组件的代码:

this.userService.loginUser(new UserCredential().deserialize({ email: this.email, pass: this.pass }))
       .subscribe((rawRes) => {
           // Parsing raw response to a Reponse object
           const res = new Response().deserialize(rawRes.data.login);

现在这个只是完成了这项工作,但我很确定有一种更优雅的方法可以将 rawRes 解析为 Response 对象。如果有,那是什么?

4

0 回答 0