【问题标题】:NestJs: return modified response based on external API callNestJs:根据外部 API 调用返回修改后的响应
【发布时间】:2021-05-19 16:15:47
【问题描述】:

我是 NestJs、Graphql、打字稿的新手。

我需要进行一个基本上是 Graphql 查询本身的外部 API 调用,如果需要修改响应,并在本例中返回原始请求/查询的响应 test,即查询名称。

我有以下代码

@Query(returns => BlogPost) // @objectType
  async test() {
    const endpoint = 'https://testing.org/api/content/project-dev/graphql' 
    const graphQLClient = new GraphQLClient(endpoint, {
      headers: {
        authorization: 'Bearer xxxx',
      },
    })
    const query = gql`
      {
        queryContentContentsWithTotal(top: 10) {
          total
        }
      }`

    const data = await graphQLClient.request(query)
    console.log(JSON.stringify(data, undefined, 2))
    return data;
  }

BlogPostObjectType,看起来像:

import { Field, ObjectType } from '@nestjs/graphql';

@ObjectType()
export class BlogPost {
  @Field({ nullable: true })
  total!: number;
}

我还放置了 console.log 以查看外部 API 调用响应:

{
  "queryContentContentsWithTotal": {
    "total": 1
  }
}

但查询的 Graphql 响应是:

{
  "data": {
    "test": {
      "total": null // this needs to be 1 
    }
  }
}

total 为 null,API 调用返回 total 值 1;

如何在此处灵活地进行映射以使查询响应看起来相同?

【问题讨论】:

    标签: node.js typescript graphql nestjs typeorm


    【解决方案1】:

    GraphQL 期望您返回的数据格式为

    {
      "total": "number of some sort"
    }
    

    但你实际上是以

    的形式返回数据
    {
      "queryContentContentsWithTotal": {
        "total": 1
      }
    }
    

    所以 GraphQL 引擎无法理解返回类型。您需要将数据映射到正确的返回值,如下所示:

    @Query(returns => BlogPost) // @objectType
      async test() {
        const endpoint = 'https://testing.org/api/content/project-dev/graphql' 
        const graphQLClient = new GraphQLClient(endpoint, {
          headers: {
            authorization: 'Bearer xxxx',
          },
        })
        const query = gql`
          {
            queryContentContentsWithTotal(top: 10) {
              total
            }
          }`
    
        const data = await graphQLClient.request(query)
        console.log(JSON.stringify(data, undefined, 2))
        return data.queryContentContentsWithTotal;
      }
    

    【讨论】:

      【解决方案2】:

      您返回的dataBlogPost 的类型不同。你应该返回这个

      return {total: data.queryContentContentsWithTotal.total}
      

      【讨论】:

        猜你喜欢
        • 2019-11-10
        • 2020-01-27
        • 2020-07-10
        • 2021-12-03
        • 2020-07-28
        • 2018-04-14
        • 2020-04-24
        • 2021-03-22
        • 1970-01-01
        相关资源
        最近更新 更多