How Apollo Server processes GraphQL operations?
A resolver is a function that's responsible for populating the data for a single field in your schema.
Example
our server defines this schema:
type User {
id: ID!
name: String
}
type Query {
user(id: ID!): User
}
We want to be able to query the user field to fetch a user by its id.
const resolvers = {
Query: {
user(parent, args, context, info) {
return users.find(user => user.id === args.id);
}
}
}
parent
The return value of the resolver for this field's parent (i.e., the previous resolver in the resolver chain).
args
https://www.apollographql.com/docs/apollo-server/data/resolvers/#resolver-arguments
Example
Let's say our server defines the following schema:
# A library has a branch and books
type Library {
branch: String!
books: [Book!]
}
# A book has a title and author
type Book {
title: String!
author: Author!
}
# An author has a name
type Author {
name: String!
}
type Query {
libraries: [Library]
}
Here's a valid query against that schema:
query GetBooksByLibrary {
libraries {
books {
author {
name
}
}
}
}
the resolver chain looks like this:
These resolvers execute in the order shown above, and they each pass their return value to the next resolver in the chain via the parent argument.
https://www.apollographql.com/docs/apollo-server/data/resolvers/#resolver-chains
more practice
let tweets = [
{
id: "1",
text: "first one!",
userId: "2",
},
{
id: "2",
text: "second one",
userId: "1",
},
];
let users = [
{
id: "1",
firstName: "nico",
lastName: "las",
},
{
id: "2",
firstName: "Elon",
lastName: "Mask",
},
];
const typeDefs = gql`
type User {
id: ID!
firstName: String!
lastName: String!
fullName: String!
}
type Tweet {
id: ID!
text: String!
author: User
}
type Query {
tweet(id: ID!): Tweet
}
`
const resolvers = {
Query: {
tweet(_, { id }) {
return tweets.find((tweet) => tweet.id === id);
},
},
User: {
fullName({firstName, lastName}) {
return `${firstName} ${lastName}`;
},
},
Tweet: {
author(parent) {
const {id, text, userId} = parent
return users.find((user) => user.id === userId);
},
},
위 코드에 대한 하나의 유효한 쿼리를 표현하면 다음과 같다.
이 쿼리에서 resolver chaindms 다음과 같다.