Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

javascript - Apollo Server: pass arguments to nested resolvers

My GraphQL query looks like this:

{
    p1: property(someArgs: "some_value") {
        id
        nestedField {
            id
            moreNestedField {
                id
            }
        }
    }
}

On the server side, I'm using Apollo Server. I have a resolver for the property and other resolvers for nestedField and moreNestedField. I need to retrieve the value of someArgs on my nested resolvers. I tried to do this using the context available on the resolver:

property: (_, {someArgs}, ctx) => {
    ctx.someArgs = someArgs;

    // Do something
}

But this won't work as the context is shared among all resolvers, thus if I have multiple propertyon my query, the context value won't be good.

I also tried to use the path available on info on my nested resolvers. I'm able to go up to the property field but I don't have the arguments here...

I also tried to add some data on info but it's not shared on nested resolvers.

Adding arguments on all resolvers is not an option as it would make query very bloated and cumbersome to write, I don't want that.

Any thoughts?

Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Params can be passed down to child resolvers using currently returned value. Additional data will be removed from response later.

I'll 'borow' Daniel's code, but without specific params - pass args down as reference (suitable/cleaner/more readable for more args):

function propertyResolver (parent, args) {
  const property = await getProperty()
  property.propertyArgs = args
  return property
}

// if this level args required in deeper resolvers
function nestedPropertyResolver (parent, args) {
  const nestedProperty = await getNestedProperty()
  nestedProperty.propertyArgs = parent.propertyArgs
  nestedProperty.nestedPropertyArgs = args
  return nestedProperty
}

function moreNestedPropertyResolver (parent) {
  // do something with parent.propertyArgs.someArgs
}

As Daniels stated this method has limited functionality. You can chain results and make something conditionally in child resolver. You'll have parent and filtered children ... not filtered parent using child condition (like in SQL ... WHERE ... AND ... AND ... on joined tables), this can be done in parent resolver.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...