I would like to create a GraphQL layer for my NestJs API. So based on this interface holding a key/value pairs
export interface Mapping {
id: string;
value: object;
}
I created a DTO acting as a return type for the GraphQL queries
@ObjectType()
export class MappingDTO {
@Field(() => ID)
id: string;
@Field()
value: object;
}
So when I want to find all mappings I would come up with this
@Query(() => [MappingDTO])
public async mappings(): Promise<Mapping[]> {
return this.mappingsService.getMappings();
}
Unfortunately I can't use object
for the value field. I'm getting this error
NoExplicitTypeError: You need to provide explicit type for MappingDTO#value !
When chaning the type e.g. to string
no error gets thrown on startup. The thing is that I can't specify an explicit type because my MongoDB stores objects holding "anything".
How can I fix my resolver or DTO to deal with an object type?
Edit:
Same for the resolver decorator. When I have this
@Query(() => Object)
public async getValueByKey(@Args('id') id: string): Promise<object> {
return this.mappingsService.getValueByKey(id);
}
I get this error
Error: Cannot determine GraphQL output type for getValueByKey
Sounds like you should be using a custom JSON scalar. Like this one.
import { GraphQLJSONObject } from 'graphql-type-json'
This can then either be used directly in the field decorator:
@Field(() => GraphQLJSONObject)
value: object
or you can leave the decorator as @Field()
and add the appropriate scalarsMap
to the options you pass to buildSchema
. See the docs for additional details.