Graphql Installation on Nodejs Server

By ukmodak | April 29th 2021 06:09:08 AM | viewed 675 times

Install the package on any drive from Download the windows version link Download Nodejs and NPM

node –v // to  check nodejs is install
npm –v  // to  check npm is install 
mkdir graphqlMagentoServer
cd graphqlMagentoServer
graphqlMagentoServer>npm add graphql
graphqlMagentoServer>npm add express express-graphql nodemon
graphqlMagentoServer>npm install mysql
graphqlMagentoServer>npm install cors

create a server file graphqlMagentoServer/index.js and the following code:

const express = require('express');
const { graphqlHTTP }  = require('express-graphql');
const { buildSchema } = require('graphql');
const mysql = require('mysql');
const cors = require('cors')

const app = express();
app.use(cors())

const schema = buildSchema(`
  type Query {
    getUsers: [User],
    getUser(user_id: Int) : User
  }
  type User {
    user_id: String
    first_name: String
    full_name: String
    email: String
  }
  type Mutation {
    updateUser(user_id: Int, first_name: String, email: String, full_name: String) : Boolean
    createUser(first_name: String, email: String, full_name: String) : Boolean
    deleteUser(user_id: Int) : Boolean
  }
`);

const queryDB = (req, sql, args) => new Promise((resolve, reject) => {
    req.mysqlDb.query(sql, args, (err, rows) => {
        if (err)
            return reject(err);
        rows.changedRows || rows.affectedRows || rows.insertId ? resolve(true) : resolve(rows);
    });
});

const root = {
  getUsers: (args, req) => queryDB(req, "select * from admin_user").then(data => data),
  getUser: (args, req) => queryDB(req, "select * from admin_user where user_id = ?", [args.user_id]).then(data => data[0]),
  updateUser: (args, req) => queryDB(req, "update admin_user SET ? where user_id = ?", [args, args.user_id]).then(data => data),
  createUser: (args, req) => queryDB(req, "insert into admin_user SET ?", args).then(data => data),
  deleteUser: (args, req) => queryDB(req, "delete from admin_user where user_id = ?", [args.user_id]).then(data => data)
};

app.use((req, res, next) => {
  req.mysqlDb = mysql.createConnection({
    host     : 'localhost',
    user     : 'root',
    password : '',
    database : 'db_qrius_magento'
  });
  req.mysqlDb.connect();
  next();
});

app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));

app.listen(4000);

console.log('Running a GraphQL API server at localhost:4000/graphql');
graphqlMagentoServer>node index.js
bONEandALL
Visitor

Total : 18980

Today :9

Today Visit Country :

  • Germany
  • Singapore
  • United States
  • Russia