In this article i will explain you step by step to setup REST Api with node, express , mongodb 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
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
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
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
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 mongoose
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
Step 7: Creating routes, controller , model folder, connecting to mongodb 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 Todo, { TodoModel } from "../models/todos";
export const createToDo: RequestHandler = async (req, res, next) => {
try {
const data: TodoModel = req.body;
console.log("Data", data);
var todos = await Todo.create(data);
return res
.status(200)
.json({ message: "Todo created successfully", data: todos });
} catch (error: any) {
return res.status(500).json({ message: error.message });
}
};
export const getToDo: RequestHandler = async (req, res, next) => {
try {
var todos = await Todo.find({});
return res.status(200).json({ message: "All todos!", data: todos });
} catch (error: any) {
return res.status(500).json({ message: error.message });
}
};
export const updateToDo: RequestHandler = async (req, res, next) => {
try {
const { id } = req.params;
var todos = await Todo.findByIdAndUpdate(id, req.body, { new: true });
return res
.status(200)
.json({ message: "Todo updated successfully!", data: todos });
} catch (error: any) {
return res.status(500).json({ message: error.message });
}
};
export const deleteToDo: RequestHandler = async (req, res, next) => {
try {
const { id } = req.params;
var isDeleted = await Todo.findByIdAndDelete(id);
if (!isDeleted) throw new Error("Failed to delete todo");
return res.status(200).json({ message: "Todo deleted successfully!" });
} catch (error: any) {
return res.status(500).json({ message: error.message });
}
};
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,
getToDo,
updateToDo,
deleteToDo,
} from "../controllers/todos";
const router = Router();
router.post("/", createToDo);
router.get("/", getToDo);
router.patch("/: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 * as mongoose from "mongoose";
import { Model } from "mongoose";
type TodoType = TodoModel & mongoose.Document;
export interface TodoModel {
title: {
type: String,
required: true,
};
description: {
type: String,
required: true,
};
}
const TodosSchema = new mongoose.Schema({
title: {
type: String,
required: true,
},
description: {
type: String,
required: true,
},
});
const Todo: Model<TodoType> = mongoose.model < TodoType > ("Todo", TodosSchema);
export default Todo;
Update your app.ts file with below code this includes connection code with mongodb and routes code
import express from "express";
import db from "mongoose";
import todoRoutes from "./routes/todos";
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 });
}
);
db.connect("mongodb://localhost:27017/todos", () => {
console.log("Database connected");
});
app.listen(3000);
Test your REST API with postman
Open postman and also make sure that your mongodb on your local computer is running