I am going to explain the configuration of GraphQL and REST in Node.js. Both can be used alternately. First, I will cover REST.
I assume you know how to install Node.js, Express, and other required packages in VS Code. We need the below packages to complete these tasks.
Step 1:
Please run the below command to install packages.
npm install express express-graphql graphql mongodb mongoose dotenv body-parser -save
Step 2:
Please create your MongoDB account and get the link for using this database (https://www.mongodb.com).
Step 3:
Open (Microsoft Visual Studio Code) VS Code and copy the below code. The complete code can be accessed at https://github.com/waheednazeer/node-server/tree/main/project-graphql.
`const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const {graphqlHTTP} = require('express-graphql');
const schema = require('./schema/graphql-schema');
const dotenv = require('dotenv');
const routes = require('./routes/student-route');
dotenv.config();
const app = express();
mongoose.connect(process.env.MONGOOSE_URI);
mongoose.connection.once('open', () => {
console.log('conneted to database');
});
//This route will be used as an endpoint to interact with Graphql,
//All queries will go through this route.
app
.use(
"/graphql",
graphqlHTTP({
schema: schema,
graphiql: true,
})
)
.use(bodyParser.json())
.use(express.urlencoded({ extended: true }))
.use('/',routes);
app.listen(3000, () => {
console.log('Listening on port 3000');
}); `
Routes
`const router= require('express').Router();
const studentController= require('../controllers/student-controller');
router.get('/students', studentController.getAllStudents);
router.get('/students/:id', studentController.getStudentById);
router.post('/students', studentController.createStudent);
router.put('/students/:id', studentController.updateStudent);
router.delete('/students/:id', studentController.deleteStudent);
module.exports= router;`
Controller
`const Student = require('../models/student');
const createStudent = (req, res) => {
const student = new Student(req.body);
student.save()
.then((data) => {
res.send(data);
})
};
const getAllStudents = (req, res) => {
Student.find({})
.then((data) => {
res.send(data);
})
};
const getStudentById = (req, res) => {
const id = req.params.id;
Student.findById(id)
.then((data) => {
res.send(data);
})
};
const updateStudent = (req, res) => {
const id = req.params.id;
Student.findByIdAndUpdate(id, req.body, { new: true })
.then((data) => {
res.send(data);
})
};
const deleteStudent = (req, res) => {
const id = req.params.id;
Student.findByIdAndDelete(id)
.then((data) => {
res.send(data);
})
};
module.exports= {
createStudent,
getAllStudents,
getStudentById,
updateStudent,
deleteStudent
};`
Top comments (0)