GraphQL Resolver

Hi in this post we are going to talk about the resolvers in GraphQL, a GraphQL resolver is a function that is responsible for populating the data for a single field in your schema.
In our case to represent the data, we are going to have a dummy data called sessions, that represent our database data:

In our index.js we are going to import that file:

A Resolver Map is a big object that holds all of those Type -> Field -> Resolver functions.
Then we are going to declare the resolver, if you notice you can see how the function is there sessions: () => { } this is going to return us the data (dummy data).
// Resolver
const resolvers = { // I'm the Resolver Map
Query: {
sessions: () => { // GraphQL Resolver function
return sessions;
},
},
};
After that we can declare the Resolver Map, we are need to pass that Resolver Map into the ApolloServer, like this:
// Instanciating Apolloserver
const server = new ApolloServer({ typeDefs, resolvers });
Now run npm start

Final index.js
// Dependencies
const { ApolloServer, gql } = require("apollo-server");
// Dummy data
const sessions = require("./data/sessions");
// Schema
const typeDefs = gql`
type Query {
sessions: [Session]
}
type Session {
id: ID!
title: String!
description: String
startAt: String
endsAt: String
room: String
day: String
format: String
track: String
level: String
}
`;
// Resolver
const resolvers = {
Query: {
sessions: () => {
return sessions;
},
},
};
// Instanciating Apolloserver
const server = new ApolloServer({ typeDefs, resolvers });
// Server configuration
server
.listen({ port: process.env.PORT || 4000 }) // the server port
// this function will be called when server started
.then(({ url }) => {
console.log(`GraQL running at ${url}`);
});
Nice! in the next post we are goin to check the results on the Apollo Playground
By Cristina Rojas.