简体   繁体   中英

Graphql type resolver by id

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM