简体   繁体   English

NestJs:根据外部 API 调用返回修改后的响应

[英]NestJs: return modified response based on external API call

I am new to NestJs, Graphql, typescript.我是 NestJs、Graphql、typescript 的新手。

I need to make an external API call which is basically Graphql query itself, modify the response if needed and return the response for the original request/query in this case test which is the query name.我需要进行外部 API 调用,这基本上是 Graphql 查询本身,如果需要修改响应,并在本例test中返回原始请求/查询的响应,即查询名称。

I have the following code我有以下代码

@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;
  }

The BlogPost is the ObjectType which looks like: BlogPostObjectType ,它看起来像:

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

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

I have placed console.log as well to see the external API call response which is:我还放置了 console.log 以查看外部 API 调用响应,即:

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

but the Graphql response for the query is:但查询的 Graphql 响应是:

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

total is null where the API call returns total value 1; total是 null 其中 API 调用返回total 1;

How can be the mapping done with flexibility here so that the query response looks the same?如何在这里灵活地完成映射,以使查询响应看起来相同?

GraphQL is expecting your return data in the shape of GraphQL 期望您的返回数据为

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

But you're actually returning data in the shape of但是您实际上以以下形式返回数据

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

So the GraphQL engine can't understand the return type.所以 GraphQL 引擎无法理解返回类型。 You need to map your data to the proper return like so:您需要将您的数据 map 正确返回,如下所示:

@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;
  }

You are returning data which is not the same type as BlogPost .您返回的data类型与BlogPost You should return this instead你应该返回这个

return {total: data.queryContentContentsWithTotal.total}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM