Skip to content

Instantly share code, notes, and snippets.

// src/controller/graphqlController.js
const graphqlHTTP = require('express-graphql');
const { buildSchema } = require('graphql');
// Construct a schema, using GraphQL schema language
const schema = buildSchema(`
type Query {
employee(id: Int!): Employee
employees: [Employee],
// src/controller/graphqlController.js
const graphqlHTTP = require('express-graphql');
const { buildSchema } = require('graphql');
// Construct a schema, using GraphQL schema language
const schema = buildSchema(`
type Query {
employee(id: Int!): Employee # `!` signifies this is mandatory
employees: [Employee],
const graphqlController = require('./controller/graphqlController');
app.use('/graphql', graphqlController);
const express = require('express');
const router = express.Router();
const employeeService = require('../service/employeeService');
router.get('/api/employees', (req, res) => res.json(employeeService.getAll()));
router.get('/api/employees/:id', (req, res) => {
const employeeId = req.params.id;
return res.json(employeeService.getById(employeeId));
REST APIs GraphQL
one URL serves only one request which leads to 100s of URL to maintan One URL to serves every request
Multiple roundtrip to get various kinds of data Single trip to get various combinations of data
Unwanted data travel from server to client (Wastage of bandwidth) Only required data is travelled which make response light and minimum number
No flexibility Much more flexible
Keeps Backend and frontend team tightly coupled Backend and frontend team are loosely coupled
Change in structure of APIs needs the client to change as well Change in structure of API is not needed in client side
type mutation {
addNewMovie($name: String!, $releaseYear: Int!, $actors: [ActorInput]): Movie
}
type Query {
movie(category: String, year: Int): Movie # takes category and year as param and return Movie
movies: [Movie], # equivalent to GET /api/movies
actors: [Actor], # equivalent to GET /api/actors
actor(id: String): Actor # equivalent to GET /api/actors/{id}
}
type Actor {
id: String!, # `!` represents required
name: String!,
age: Int!
}
type Movie {
id: String!,
name: String!,
releaseYear: Int!,
actors: [Actor] # Actor is another type and [] represents array of
type Starship {
id: ID!
name: String!
length(unit: LengthUnit = METER): Float
}
module.exports = {
entry: [
path.join(process.cwd(), 'app/app.tsx'), // or whatever the path of your root file is
]
module: {
rules:[{ test: /\.tsx?$/, loader: 'awesome-typescript-loader' }], // other loader configuration goes in the array
resolve: {extensions: ['.js', '.jsx', '.react.js', '.ts', '.tsx']}
}
}