Node Js GraphQL Basis

Install necessary packages like apollo-server-express and graphql using npm or yarn.

Create a schema using the GraphQL Schema Definition Language (SDL). Define types, queries, mutations, and subscriptions.

Write resolver functions to handle GraphQL queries, mutations, and subscriptions. Resolvers resolve the data for each field in the schema.

Configure and start the Apollo Server with Express. Use the schema and resolvers you’ve defined.

Access the GraphQL Playground to interact with your GraphQL API, run queries, and test mutations.

Tried out an example for GraphQL API for displaying students, their subjects, and feedback

Schema.js File

const { gql } = require('apollo-server-express');

const typeDefs = gql`
  type Student {
    id: ID!
    name: String!
    subjects: [Subject]!
    feedback: String
  }

  type Subject {
    id: ID!
    name: String!
    teacher: String!
  }

  type Query {
    students: [Student]!
  }
`;

module.exports = typeDefs;

resolvers.js is used for getting the values or connecting witht the Db for mutations

const students = [
  {
    id: '1',
    name: 'Test',
    subjects: [
      { id: '101', name: 'Math', teacher: 'Test' },
      { id: '102', name: 'Science', teacher: 'Student' }
    ],
    feedback: 'Test student'
  },
  {
    id: '2',
    name: 'Test 1 ',
    subjects: [
      { id: '103', name: 'History', teacher: 'Test 1' },
      { id: '104', name: 'English', teacher: 'Student 1' }
    ],
    feedback: 'Test 1 student'
  }
];

const resolvers = {
  Query: {
    students: () => students
  }
};

module.exports = resolvers;

app.js file

const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const typeDefs = require('./schema');
const resolvers = require('./resolvers');

const app = express();

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

server.applyMiddleware({ app });

const PORT = process.env.PORT || 4000;
app.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}${server.graphqlPath}`);
});

Check the following document for the using apollo server graphql

https://www.apollographql.com/docs/apollo-server/v2/schema/schema

Leave a comment

Your email address will not be published. Required fields are marked *