I am new to 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.
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 :
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:
{
"queryContentContentsWithTotal": {
"total": 1
}
}
but the Graphql response for the query is :
{
"data": {
"test": {
"total": null // this needs to be 1
}
}
}
total
is null where the API call returns total
value 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
{
"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. You need to map your data to the proper return like so:
@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;
}