Reputation: 23
I'm trying to get familiar with Graphql by building a server with the following schema:
type Game
{
id: ID!
players: [Player!]!
winner: Player
...
}
type Player {
id: ID!
game: Game!
...
}
type Query {
getGame(id: ID!): Game
getPlayer(id: ID!): Player
}
And map to the following data:
const games = {
1: {
id: 1,
players: [2, 3],
winner: undefined
}
};
const players = {
2: {
id: 2,
game: 1
},
3: {
id: 3,
game: 1
},
};
While writing the resolvers, I noticed a lot of boilerplate code - I had to write conceptually the same field resolver for every object member which holds a foreign key.
const typedefs = {
Query: {
getGame: (_, {id}) => games[id],
getPlayer: (_, {id}) => players[id]
},
Game: {
winner: (game) => players[game.winner],
players: (game) => game.players.map(id => players[id])
},
Player: {
game: (player) => games[player.id]
}
}
Is there a way to create a type resolver by ID?
for example, a Player
field or query would always be resolved by (id) => players[id]
,
and a game field or query would always be resolved by (id) => games[id]
.
I saw that this is achievable using AWS-Amplify's @model
directive, but I'm wondering if there is a more standard way I'm missing rather than implementing my own directive.
Is this a feature of any current Graphql implementation? I couldn't find anything that resembles it in apollo-graphql's documentation (or in graphql-js's).
Thanks.
Upvotes: 2
Views: 879
Reputation: 7666
There is no way of changing the default resolver. Apollo-GraphQL just passes the resolver map to graphql-tools
and graphql-tools
uses graphql-js
. graphql-js
implements the default resolver here and uses it here.
Maybe you could try using ES2015 Proxy
to provide a default implementation for resolvers in the object instead. But even if you override your default resolver, you break all the places where you used the actual default resolver.
Upvotes: 0