Developing REST Api using sequelize typescript, node, express and mysql

Author
April 06, 2022

In this article i will explain you step by step to setup REST Api with node, express , sequelize, mysql and typescript

Step 1: Install typescript globally

We need to install typescript globally in our computer so that we can use typescript command easily you can use npm or yarn i will use npm here, use the command below to install typescript

npm install -g typescript

typescript-install

Step 2: Initialize typescript compiler

We need to intialize typescript compiler in order to compile our code to typescript, go to project folder and use below command to initialize typescript compiler this will create tsconfig.json file at the root path of your project

tsc --init

typescript-compiler

Step 3: Initialize npm

Initialize npm to create package.json file so that you can install necessary package required by the project or start the project or for other purposes where you need to run npm command, run below command to initialize npm

npm init

npm-init

Step 4: Change the required configuration in tsconfig.json file for your project and create a src folder in your project root path

Change the outDir, rootDir in your tsconfig.json file outDir is the path where typescript compiled file will be stored and rootDir is the path where you main project code exists, I’m defining the path folder path as outDir: ‘./dist’ and rootDir:‘./src’

Also create a folder name src at root path of project where we will be storing our project files

tsconfig-file

Step 5: Install required package express.js and body parser,nodemon, node types using npm

We will use npm command to install express.js and body parser, use below command to install the package express.js and body-parser and mongoose which helps in connecting to mongodb database

npm install --save express body-parser sequelize sequelize-typescript mysql2

Use below command to install nodemon as development dependency

npm install --save-dev nodemon

Use below command to install node types so that typescript understands the node js code and doesn’t throw error

npm install --save-dev @types/node
npm install --save-dev @types/express

Step 6: Creating Node, express server and starting the server

Create app.ts file under src folder in your project which we have created previously and copy paste code below in your app.ts file

import express from "express";

const app = express();

app.listen(3000);

Update your package.json file and add start command under script tag to compile typescript code and start the express server

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "tsc && nodemon dist/app.js"
  },

After updating package.json file you can use below command to start the express server

npm start

npm-start

Step 7: Creating routes, controller , model folder, connecting to mysql using sequelize and testing REST api

Create a folder name controller inside src folder and create a file name todos.ts which is controller file and copy paste below code

import { RequestHandler } from "express";

import { Todos } from "../models/todos";

export const createToDo: RequestHandler = async (req, res, next) => {
  var todos = await Todos.create({ ...req.body });
  return res
    .status(200)
    .json({ message: "Todo created successfully", data: todos });
};

export const deleteToDo: RequestHandler = async (req, res, next) => {
  const { id } = req.params;
  const deletedTodo: Todos | null = await Todos.findByPk(id);
  await Todos.destroy({ where: { id } });
  return res
    .status(200)
    .json({ message: "Todo deleted successfully", data: deletedTodo });
};

export const getAllToDo: RequestHandler = async (req, res, next) => {
  const allTodos: Todos[] = await Todos.findAll();
  return res
    .status(200)
    .json({ message: "Todo fetched successfully", data: allTodos });
};

export const getTodoById: RequestHandler = async (req, res, next) => {
  const { id } = req.params;
  const todos: Todos | null = await Todos.findByPk(id);
  return res
    .status(200)
    .json({ message: "Todo fetched successfully", data: todos });
};

export const updateTodo: RequestHandler = async (req, res, next) => {
  const { id } = req.params;
  await Todos.update({ ...req.body }, { where: { id } });
  const updatedTodos: Todos | null = await Todos.findByPk(id);
  return res
    .status(200)
    .json({ message: "Todo updated successfully", data: updatedTodos });
};

Create a folder name routes inside src folder and create a file name todos.ts which is route file and copy paste below code

import { Router } from "express";

import {
  createToDo,
  deleteToDo,
  getAllToDo,
  updateTodo,
  getTodoById,
} from "../controllers/todos";

const router = Router();

router.post("/", createToDo);

router.get("/", getAllToDo);

router.get("/:id", getTodoById);

router.put("/:id", updateTodo);

router.delete("/:id", deleteToDo);

export default router;

Create a folder name models inside src folder and create a file name todos.ts which is model file and copy paste below code

import { Table, Model, Column, DataType } from "sequelize-typescript";

@Table({
  timestamps: false,
  tableName: "todos",
})
export class Todos extends Model {
  @Column({
    type: DataType.STRING,
    allowNull: false,
  })
  name!: string;

  @Column({
    type: DataType.STRING,
    allowNull: false,
  })
  description!: string;
}

Create sequelize database connection file config.ts inside db folder under root path and copy paste below code

import { Sequelize } from "sequelize-typescript";
import { Todos } from "../models/todos";

const connection = new Sequelize({
  dialect: "mysql",
  host: "localhost",
  username: "root",
  password: "anku@1234",
  database: "todos",
  logging: false,
  models: [Todos],
});

export default connection;

Update your app.ts file with below code this includes connection code with mongodb and routes code

import express from "express";
import todoRoutes from "./routes/todos";
import connection from "./db/config";
import { json, urlencoded } from "body-parser";

const app = express();

app.use(json());

app.use(urlencoded({ extended: true }));

app.use("/todos", todoRoutes);

app.use(
  (
    err: Error,
    req: express.Request,
    res: express.Response,
    next: express.NextFunction
  ) => {
    res.status(500).json({ message: err.message });
  }
);

connection
  .sync()
  .then(() => {
    console.log("Database successfully connected");
  })
  .catch((err) => {
    console.log("Error", err);
  });
app.listen(3000, () => {
  console.log("Server started on port 3000");
});

folderstructure

Test your REST API with postman

Open postman and also make sure that your mysql server on your local computer is running

postman

mysqlworkbench