简体   繁体   中英

Apollo graphql query with parameters

I am following along with this Graphql intro https://www.apollographql.com/docs/apollo-server/getting-started/ . I've got my files set up (slightly modified), and the base query is working on http://localhost:4000/.

My next question after getting through the basics was, how do I get data based on parameters? I've gotten this far, but the query in playground doesn't return results.

index.js

const typeDefs = gql`
    type Item {
        name: String
        description: String
        full_url: String
        term: String
    }

    type Query {
        items: [Item]
        itemsSearch(term: String!): [Item]
    }
`;

const resolvers = {
    Query: {
        // this works. it is the example from the guide.
        items: () => items,
        // this doesn't work. `term` is always undefined
        itemsSearch: term => {
            console.log('term', term);
            console.log('items', items);
            return items.filter(item => item.title.indexOf(term) > -1 || item.author.indexOf(term) > -1);
        },
    },
};

Then I'm running this query in playground. (mostly working from https://graphql.org/graphql-js/passing-arguments/ )

{
  itemsSearch(term: "Rowling") {
    title
    author
  }
}

I get a successful response but no data. As mentioned, logging term in the itemsSearch resolver prints undefined.

Any idea how I can pass that param term to the resolver and get results? Thanks in advance.

The arguments of a resolver are parent , args , context and info :

args

An object that contains all GraphQL arguments provided for this field.

For example, when executing query{ user(id: "4") } , the args object passed to the user resolver is { "id": "4" } .

Therefore you get term through args with:

itemsSearch: (parent, { term }) => {
   ...
}

Or:

itemsSearch: (parent, args) => {
   const term = args.term;
   ...
}

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