DEV Community

Princewhyte Dabotubo
Princewhyte Dabotubo

Posted on

A practical approach to creating graphql APIs in node.js - part two(How to setup Apollo Server)

In our previous post here we looked at the foundational concept of graphql (schemas and queries).

Let's take it a step further and implement a node.js graphql server.

We'll be implementing our server by using the leading library Apollo server.

To begin use the command npm init to create a new node.js project and install dependencies.

npm install apollo-server graphql

let's create an index.js file with initial content as follows:

const { ApolloServer, gql } = require("apollo-server")

let contacts = [
  {
    name: "Della charles",
    phoneNo: "234-4567-890",
    address: "Eleme street 34",
    id: "3d594650-3436-8b80ba54c431",
  },
  {
    name: "Awurum mikel",
    phoneNo: "234-4567-560",
    street: "Tombia town 7",
    id: "3d599470-3436-8b80ba54c431",
  },
]

const typeDefs = gql`
  type Contact {
    name: String!
    phoneNo: String
    address: String!
    id: ID!
  }

  type Query {
    countContact: Int!
    allContacts: [Contact!]!
    findContact(name: String!): Contact
  }
`

const resolvers = {
  Query: {
    countContact: () => contacts.length,
    allContacts: () => contacts,
    findContact: (root, args) => contacts.find((p) => p.name === args.name),
  },
}

const server = new ApolloServer({
  typeDefs,
  resolvers,
})

server.listen().then(({ url }) => {
  console.log(`Server running at ${url}`)
})

Enter fullscreen mode Exit fullscreen mode

For our server to be running here the most important weapon is this block of code :

const server = new ApolloServer({
typeDefs,
resolvers,
})

The ApolloServer takes in an object with two properties as an argument. The first is the typeDefs (our schemas and queries definition), and the second is resolvers.

Resolvers are the code, which defines how GraphQL queries are responded to.

const resolvers = {
Query: {
countContact: () => contacts.length,
allContacts: () => contacts,
findContact: (root, args) => contacts.find((p) => p.name === args.name),
},
}

the resolver above responds to the query definition below

type Query {
countContact: Int!
allContacts: [Contact!]!
findContact(name: String!): Contact
}

As you can see each query has an equivalent resolver.

we can now start our server by running the command
node index.js

Our server can now listen for queries and the apollo server comes with a default explorer to try out the queries.

see you in the next post.
you can connect with me on linkedin
github

Top comments (0)