graphql-directive-resolve-as
v1.0.2
Published
Graphql directive to resolve fields as different prop names of the belonging object
Downloads
66
Maintainers
Readme
graphql-directive-resolve-as
Introduction
Graphql directive to resolve fields as different prop names of the belonging object.
This directive helps you not to declare resolvers over and over just because the name you want to expose is different to the prop name.
It allows resolution for nested objects, converting a string in dot notation into an object reference.
Table of Contents
Installation
yarn add graphql-directive-resolve-asor
npm i graphql-directive-resolve-asUsage
const { resolveAs } = require('graphql-directive-resolve-as');
const schema = makeExecutableSchema({
typeDefs,
resolvers,
schemaDirectives: {
resolveAs,
...
},
});then you can use it in your fields like this:
const typeDefs = `
type User {
name: String @resolve_as(name: "firstName")
lastName: String,
city: String @resolveAs(name: "country.city.name")
firstFriend: String @resolveAs(name: "friends.0.name")
}
type Query {
me: User
}
`;me query resolver could be something like this:
const resolvers = {
Query: {
me: () => ({
firstName: 'John',
lastName: 'Doe',
friends: [
{
name: 'Edu'
},
{
name: 'Natalia'
}
],
country: {
name:'Germany',
city: {
name:'Berlin',
neighborhood: {
name: "Kreuzberg"
}
}
}
}),
},
};if you use
graphql-importthen you need to add this definition on top of the schema:
directive @resolveAs(name: String) on FIELD_DEFINITIONDirective Parameters
name = Path as string in dot notation to the object property to be resolved.
