简体   繁体   中英

GraphQL : Reuse arguments from root_query in a type

I'm trying to wrap a REST API in GraphQL and I came across this. Imagine I have the following type:

const CbookType = new GraphQLObjectType({
name: 'CbookType',
fields: () => ({
    id: { type: GraphQLID },
    title: { type: GraphQLString },
    user: {
        type: UserType,
        args: {
            userToken: { type: new GraphQLNonNull(GraphQLString) },
            userId: { type: new GraphQLNonNull(GraphQLString) }
        },
        resolve(parentValue, { userToken, userId }) {
            return UserController.user({ targetUserId: parentValue.user_id, userToken, userId });
        }
    }
});

The user field is located on another REST endpoint so I have to pass my token and user_id again which creates ugly queries where I permanently have to add args for my token and user_id.

Is there a way for me to keep the args passed in my RootQuery and reuse them in my type? I've looked into parentValue but they are not there.

The first argument passed to the resolver (parentValue) is simply what the "parent" of the field resolved to -- it will not contain any information about the request itself or how the value was resolved.

Because GraphQL resolves each "level" of the request before moving on, you can modify the context passed to each resolver (the third argument) at a higher level, and the changes will be visible to all resolvers at a lower level.

For example, the resolver for a query that gets a Foo type:

function (obj, { userToken, userId }, ctx = {}) => {
  Object.assign(ctx, { userToken, userId })
  return getFoo()
}

And then a field on type Foo might look like this:

function (obj, { userToken, userId }, ctx = {}) => {
  return getBars(ctx.userToken, ctx.userId)
}

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