Node.js NestJs:基于外部API调用返回修改后的响应

Node.js NestJs:基于外部API调用返回修改后的响应,node.js,typescript,graphql,nestjs,typeorm,Node.js,Typescript,Graphql,Nestjs,Typeorm,我不熟悉NestJs、Graphql和typescript 我需要进行一个基本上是Graphql查询本身的外部API调用,如果需要修改响应,并返回原始请求/查询的响应(在本例中为test,即查询名称) 我有以下代码 @Query(returns => BlogPost) // @objectType async test() { const endpoint = 'https://testing.org/api/content/project-dev/graphql'

我不熟悉NestJs、Graphql和typescript

我需要进行一个基本上是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;
  }
BlogPost
ObjectType
,它看起来像:

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
在API调用返回
total
值1时为null


在这里,如何灵活地进行映射,使查询响应看起来相同?

GraphQL希望返回的数据是

{
  "total": "number of some sort"
}
{
  "queryContentContentsWithTotal": {
    "total": 1
  }
}
但实际上,您以

{
  "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;
  }

您正在返回的
数据
BlogPost
的类型不同。你应该退回这个

return{total:data.queryContentContentsWithTotal.total}