Creating an Express.js App Using Typescript & MongoDb P-1
abdulrahilsheikh
Posted on July 5, 2023
Section 1 - Creating Express App
Step by step Implementation:
Step 1 : First create a empty folder and open terminal in this folder.
Step 2 : Run the following command in your terminal, to create a nodejs application, because our express server will work inside the node application.
Command :
npm init
Step 3 : Installing all the necessary dependencies for our application.
Command :
npm install express cors mongoose
Step 4 : Now we need to install types for express and cors.
npm install @types/express @types/cors --save-dev
Step 5 : Now we have to set up typescript for our app for that run the following command
Command :
tsc --init
This will create a tsconfig.json file which will have all the configuration for the typescript.
Step 6 : Now to run the typescript application we need to install some additional dependencies. Which are ts-node and nodemon.
Command :
npm i nodemon ts-node --save-dev
After following all the steps your folder structure should look like
-|-node_modules
|-package-lock.json
|-package.json
|-tsconfig.json
Step 7 : Creating an entry point for our express app to start.
create an index,ts file in the root of your project. Also create a folder with app name here we will put all of our middleware, routes etc.
The project structure will look like following.
-|-app
|-node_modules
|-index.ts
|-package-lock.json
|-package.json
|-tsconfig.json
Step 8: To run the server we need to add following script to our package.json file. Also change the extension on index.js to index.ts of the main property in package.json.
"run:dev": "nodemon index.ts"
After this our script will look like
Step 9: Now to test our setup is working file put the below code snippet in the index.ts.
console.log("I'm running")
Now in the terminal run the following command
npm run run:dev
The text I'm running should log in the terminal and your terminal should look like following.
Hurray ๐๐๐ we have successfully setup our starting point
Step 10: Now create a app.ts file in app folder. The folder structure will look like following.
-|-app
| |-app.ts
|-node_modules
|-index.ts
|-package-lock.json
|-package.json
|-tsconfig.json
Step 11: Now need to create our express server. For that we need an instance of express. For that we need to import express from express package we installed. for that put the below code at the top of app.ts file.
And now invoke this express function imported and store it into a variable named app
import express from "express";
const app: express.Application = express();
express.Application will give us typescript interface of express
Now create a function named server and export it. We will use this server function in index.ts.
import express from "express";
const app: express.Application = express();
export const server = async () => {
const port: number = 3500;
app.listen(port, () => {
console.log(`Server running on ${port}`);
});
};
Now in index.ts import the server and invoke it as shown below.
import { server } from "./app/app";
server();
Now again run the npm run run:dev to start the server in dev mode.
npm run run:dev
Your terminal will look like following.
Step 12: Now we will create a basic get route which will return hello world. For doing first we will create an organized folder structure . For that we will create a modules folder inside our app folder for holding our routes. In this modules folder create a new folder called users. Inside it create files called users.routes.ts, users.schema.ts and users.services.ts . Now you folder should look like following.
-|-app
| |-modules
| | |-users
| | |-users.routes.ts
| | |-users.schema.ts
| | |-users.services.ts
| |-app.ts
|-node_modules
|-index.ts
|-package-lock.json
|-package.json
|-tsconfig.json
Each file has its own role.
- users.routes.ts will hold all the routes such as get, post, patch etc.
- users.schema.ts will hold the mongoose schema and model which we will use to communicate with mongodb.
- users.services.ts will hold the all function which we need to complete or process the user request.
Step 13: In user.routes.ts import the Router from express and create an instance of it.
Router function is used to create a new router object which is used to create a new router object in your program to handle requests.
Your code should look like below.
import { Router } from "express";
const userRouter = Router();
userRouter.get("/users", (req, res) => {
res.json({ message: "sent succesfully" });
});
export default userRouter;
Now import this user router in your app.ts file and use is as shown below.
import express from "express";
import userRouter from "./modules/users/users.routes";
const app: express.Application = express();
export const server = async () => {
const port: number = 3500;
app.use('/',userRouter);
app.listen(port, () => {
console.log(`Server running on ${port}`);
});
};
Now in your browser go to http:localhost:3500/users or whatever your port is http:localhost:/users.
You will see the following.
Congratulations ๐๐ you've successfully created a route. You can similarly create a post route.
Now we will use the services file.
The services file will have all the business logic like processing data, fetching from db etc.
In users.services.ts paste the following code block.
const users = [
{ name: "Jhon Doe", age: 24 },
{ name: "Man Freed", age: 22 },
{ name: "Mr Beast", age: 21 },
{ name: "Carry Minati", age: 25 },
];
export const getRandomUser = () => {
const index = Math.floor(Math.random() * users.length);
return users[index];
};
Also modify the user.routes.ts like the following.
import { Router } from "express";
import { getRandomUser } from "./users.services";
const userRouter = Router();
userRouter.get("/users", (req, res) => {
const user = getRandomUser();
res.json({ user });
});
export default userRouter;
Now each time you hit "/users" or refresh the page in browser you will get a different user.
We will be using this services a lot when dealing with mongodb.
For connecting to mongodb and using it we will have another blog.
Posted on July 5, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.