Create Graphql mock API

How to create a Mock API with custom data


Mock API help UI developers to load fake data for testing. There are plenty of JSON placeholder available for mocking.

Sometimes the data want to test is different than the place holder offering, we have to create our own.

So how do we , create our own mock data with out a server?

Using the Github repository we can create REST API and Graphql end point. Here is how ?

Create a docker image of Node-Express API – Part II

How to build Node-Express project Docker Image using Node base image


In this post which is the continuation of Node-API Docker Image ( the Links are at the end of the post), create and run container using the image we build.

Lets check the existence of the image in docker using

docker image

Create the container

To build a container to run the API we need only the Image , all the depending Image will be automatically download by Docker.

docker run --name customer -d -p 3000:3000 user-api:latest

The above command will run, customer API in detached mode on port 3000.

Stop and Resume the container

We can stop running a container at any time using docker stop <id/name> and resume with docker start <id/name>

Following Docker Post may deserve a good read

How to auto create tables based on sequelize models

Auto create table based on sequelize models


We had discussed how to auto create API using sequelize, on thing I missed is auto creation of tables.

Sequelize

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.

Auto create tables

Sequelize module has provided a function called sync in order to create tables based on the Sequelize models we created.

Place the call in the authenticate method of the Sequelize configuration as follows

const Sequelize=require('sequelize')
module.exports=new Sequelize('todo_collections','root','123',{
    host:'127.0.0.1',
    port:3306,
    dialect:'mysql',
    pool:{
        max:5,
        min:0,
        acquire:30000,
        idle:10000
    }
})

.......
.......

const db = require("./config/database");
db.authenticate()
  .then(() => {
      console.log("Database connected")
    db.sync()
    })
  .catch((e) => console.log("Error:" + e));
app.get("/", (req, res) => {
  res.send("Hello world");
});

We can use sync({force:true}) for drop the tables already created

You may like to read these sequelize posts too

How to resolve sequelize-JSON.parse error in Node

How to resolve JSON.Parse error in sequelize


When I start with Sequelize ORM end up with the body-parser error. Usually we define body parser using app.use(bodyparser.json()), which globally declare parser functionality for all routes.

SyntaxError: Unexpected token in JSON at position 0
at JSON.parse ()
at createStrictSyntaxError (E:\NodeProjects\sequelize-api -mysql\node_modules\body-parser\lib\types\json.js:158:10)
at parse (E:\NodeProjects\sequelize-api -mysql\node_modules\body-parser\lib\types\json.js:83:15)
at E:\NodeProjects\sequelize-api -mysql\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (E:\NodeProjects\sequelize-api -mysql\node_modules\raw-body\index.js:224:16)
at done (E:\NodeProjects\sequelize-api -mysql\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (E:\NodeProjects\sequelize-api -mysql\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (node:events:388:22)
at endReadableNT (node:internal/streams/readable:1305:12)
at processTicksAndRejections (node:internal/process/task_queues:80:21)

Here is where sequelize findAll() like functionality collides and the above error log will be populated

Solution

We can apply route specific parser to fix this mess. Let’s see how

Before the fix

For simplicity I have omitted some of the lines in index.js (Node project file). Before the fix our routes look like this

...
app.use(bodyParser.urlencoded({extended:false})) 
app.use(bodyParser.json())

app.post("/todo",  (req, res, next) => {
    const {item,description}=req.body
    Todo.create({item:item,description:description})
    .then((model) => {
      res.status(200).send(model);
      })
      .catch((e) => {
        res.status(400).send("Error:" + e);
      });
  });

app.get("/todo", (req, res, next) => {
  Todo.findAll()
    .then((model) => {
        res.json({
            error: false,
            data: model
        })
    })
    .catch(error => res.json({
        error: true,
        data: [],
        error: error
    }))
});


After the fix

After the removal of the global json parser it will look like this

...
app.use(bodyParser.urlencoded({extended:false})) 
 

app.post("/todo", bodyParser.json(), (req, res, next) => {
    const {item,description}=req.body
    Todo.create({item:item,description:description})
    .then((model) => {
      res.status(200).send(model);
      })
      .catch((e) => {
        res.status(400).send("Error:" + e);
      });
  });

app.get("/todo", (req, res, next) => {
  Todo.findAll()
    .then((model) => {
        res.json({
            error: false,
            data: model
        })
    })
    .catch(error => res.json({
        error: true,
        data: [],
        error: error
    }))
});


we have added the parser function of the bodyParser to Post routes only and the problem solved

Create REST-API using sequelize -MariaDB ORM in Nodejs

How to create REST-API using sequelize ORM for MariaDB in Node-Expressjs


We had many posts on API and I am moving on sequelize ORM which allows us to perform CURD operation in REST manner or using Modals, just like we done with mongoose.

Sequelize

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.

MariaDB

MariaDB is a community-developed, commercially supported fork of the MySQL relational database management system, intended to remain free and open-source software under the GNU General Public License. The standard installation come with Heidi SQL GUI which help us create and manage database and schemas.

You can download and install it from the official website

Todo API

todos table in Heidi SQL

Our API is used to create the todos ,store in MariaDB , and perform all CURD operations using sequelize modal.

First we need to create the above table in your Maria. Now lets create a basic Nodejs project.

Continue reading “Create REST-API using sequelize -MariaDB ORM in Nodejs”

Create REST-API using sequelize-Mysql in Nodejs

How to create REST-API using sequelize-MySQL ORM in Node-Expressjs


We had many posts on API and I am moving on sequelize ORM which allows us to perform CURD operation in REST manner or using Modals, just like we done with mongoose.

Sequelize

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.

MySQL

MySQL is an open-source relational database management system. Its name is a combination of “My”, the name of co-founder Michael Widenius’s daughter, and “SQL”, the abbreviation for Structured Query Language. A workbench , which GUI tool to manage database object is available at MySQL website along with MySQL Downloads

Todo API

todos table in Workbench

Our API is used to create the todos ,store in MySQL DB , and perform all CURD operations using sequelize modal.

First we need to create the above table in your MySQL. Now lets create a basic Nodejs project.

Continue reading “Create REST-API using sequelize-Mysql in Nodejs”

Create REST-API using sequelize-Postgres in Nodejs

How to create REST-API using sequelize ORM in Node-Expressjs


We had many posts on API and I am moving on sequelize ORM which allows us to perform CURD operation in REST manner or using Modals, just like we done with mongoose.

Sequelize

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.

PostgreSQL

Postgres is an opensource DBMS, it is free and perform faster results. It come with pg-admin web interface which allows navigate through database. You can download and install it from the official website

Todo API

todos table in pg admin

Our API is used to create the todos ,store in pg (PostgreSQL) , and perform all CURD operations using sequelize modal.

First we need to create the above table in your pg. Now lets create a basic Nodejs project.

Continue reading “Create REST-API using sequelize-Postgres in Nodejs”