Author -  Sai gowtham

How to create resolvers and query fields in GraphQL (Basics)

In this tutorial, we are going to learn about resolver functions and query fields in GraphQL.

First, let’s design a GraphQL Schema.

type User{
    id: ID!
    name: String!
}


type Query{
    user(id:ID!):User
}

Our GraphQL schema has User type with two fields id, name and Query type with one field user but so far graphql didn’t know how to respond to those queries.

Resolvers

  • Resolvers help us to tell the GraphQL, how to respond to the query fields by using a resolver function.

  • In graphql, every query field should be backed by there own resolver function.

This is a resolver function for the user query field in schema.

const resolvers ={

    Query:{
        user(parent,args,ctx,info){           console.log('hello')             return Users.find((user)=> user.id === args.id)        }    }
}

Note: Resolver function names should be match with the Query field names in the schema.

Every resolver function in GraphQL has four arguments.

parent or root: This helps us to get the parent data if we use nested queries in graphql.

args: Arguments are the objects passed at the time of running the query.

context: The context data is passed to every resolver function, like authentication or change theme.

info: It contains more depth information about the current query. (like Ast’s mostly used in advanced use cases.)

What happens when we run a query?

GraphQL first matches the query with the type system if this query is valid then only GraphQL invokes the resolver functions otherwise GraphQL returns the error without invoking a resolver function.

Invalid query

error graphql resolver

valid query

valid graphql query

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY