Creating an Express.js App Using Typescript & MongoDb P-1

abdulrahilsheikh

abdulrahilsheikh

Posted on July 5, 2023

Creating an Express.js App Using Typescript & MongoDb P-1

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
Enter fullscreen mode Exit fullscreen mode

Step 3 : Installing all the necessary dependencies for our application.

Command :

npm install express cors mongoose
Enter fullscreen mode Exit fullscreen mode

Step 4 : Now we need to install types for express and cors.

npm install @types/express @types/cors --save-dev
Enter fullscreen mode Exit fullscreen mode

Step 5 : Now we have to set up typescript for our app for that run the following command
Command :

tsc --init
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

After following all the steps your folder structure should look like

Folder structure

-|-node_modules
 |-package-lock.json
 |-package.json
 |-tsconfig.json
Enter fullscreen mode Exit fullscreen mode

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.

Image showing folder structure 2

-|-app
 |-node_modules
 |-index.ts
 |-package-lock.json
 |-package.json
 |-tsconfig.json
Enter fullscreen mode Exit fullscreen mode

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"
Enter fullscreen mode Exit fullscreen mode

After this our script will look like

Package Json after editing

Step 9: Now to test our setup is working file put the below code snippet in the index.ts.

console.log("I'm running")
Enter fullscreen mode Exit fullscreen mode

Now in the terminal run the following command

npm run run:dev
Enter fullscreen mode Exit fullscreen mode

The text I'm running should log in the terminal and your terminal should look like following.

Server run 1

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.

folder structure 3

-|-app
 |   |-app.ts
 |-node_modules
 |-index.ts
 |-package-lock.json
 |-package.json
 |-tsconfig.json
Enter fullscreen mode Exit fullscreen mode

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();

Enter fullscreen mode Exit fullscreen mode

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}`);
    });
};

Enter fullscreen mode Exit fullscreen mode

Now in index.ts import the server and invoke it as shown below.

import { server } from "./app/app";

server();
Enter fullscreen mode Exit fullscreen mode

Now again run the npm run run:dev to start the server in dev mode.

npm run run:dev
Enter fullscreen mode Exit fullscreen mode

Your terminal will look like following.

Server run 2

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.
folder structure 3

-|-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
Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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}`);
    });
};

Enter fullscreen mode Exit fullscreen mode

Now in your browser go to http:localhost:3500/users or whatever your port is http:localhost:/users.
You will see the following.

Browser view 1

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];
};

Enter fullscreen mode Exit fullscreen mode

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;
Enter fullscreen mode Exit fullscreen mode

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.

Browser view 2

Browser view 3

For connecting to mongodb and using it we will have another blog.

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
abdulrahilsheikh
abdulrahilsheikh

Posted on July 5, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About