How to use graphql-type-json with NestJS

Viewed 15

i Have following response that needs to go under GraphQL Query:

{
  '0xF7446f0...9a496aE94Cf9d42': { balances: [ [Object], [Object] ] },
  '0xc01679F6496...95c86f9DEc63a': { balances: [ [Object], [Object] ] }
}

Using nestjs together with graphql-type-json and my code looks like this

@ObjectType()
export class BalancesResponse {
  @Field({ nullable: true })
  error?: string;

  @Field((type) => JSON)
  balances: any;
}

but when i try to execute the requests i got this error:

"message": "Cannot return null for non-nullable field BalancesResponse.balances."

Any idea how to return it, i want to return all of the key-value pairs in the object and my key to be dynamic

1 Answers

GraphQL does not support dictionary types. You can only query defined (i.e. known in advance) fields.

You could, however, refactor the response object to be an array:

[
  { key: '0xF7446f0...9a496aE94Cf9d42', balances: [ ... ] },
  { key: '0xc01679F6496...95c86f9DEc63a', balances: [ ... ] }
]

The corresponding type definition would be:

@ObjectType()
export class BalanceResponse {
  @Field()
  key: string;

  @Field({ nullable: true })
  error?: string;

  @Field((type) => JSON)
  balances: any;
}

...
@Query(() => [BalanceResponse])
async getBalance(): Promise<BalanceResponse[]>

Alternatively, you are free to lose the typing by declaring the whole response object as a GraphQL JSON. Then you can return your original response from the endpoint:

// not a GraphQL class anymore
export class BalancesResponse {
  error?: string;
  balances: Balance;
}

...
@Query(() => JSON)
async getBalance(): Promise<Record<string, BalancesResponse>>
Related