TypeORM with Express

Express is one of the popular JavaScript framework to create web application. Let us learn how to use TypeORM along with express framework in this chapter.
TypeORM CLI provides an easy option to create a complete working express web application (Restful API application) integrated with TypeORM. The CLI command to create the application is as follows −
cd /path/to/workspace typeorm init --express --name typeorm-express-sample --database mysql

Above command will create a new web application under typeorm-express-sample folder. The structure of the application is as follows −
│ .gitignore 
│ ormconfig.json 
│ package.json 
│ README.md 
│ tsconfig.json 
│ └───src 
      │ index.ts 
      │ routes.ts 
      │ 
      ├───controller 
      │      UserController.ts 
      │ 
      ├───entity 
      │      User.ts 
      │ 
      └───migration
Here,
As we know, ormconfig.json is the TypeORM configuration file. The code is as follows,
{ 
   "type": "mysql", 
   "host": "localhost", 
   "port": 3306, 
   "username": "test", 
   "password": "test", 
   "database": "test", 
   "synchronize": true, 
   "logging": false, 
   "entities": [
      "src/entity/**/*.ts" 
   ], 
   "migrations": [ "src/migration/**/*.ts" 
   ], 
   "subscribers": [ "src/subscriber/**/*.ts" 
   ], 
   "cli": { 
      "entitiesDir": "src/entity", "migrationsDir": "src/migration", "subscribersDir": "src/subscriber" 
   } 
}
Here, change the database setting to match your local database setting.
package.json file is the main configuration of the application.
tsconfig.json file contains the configuration related to TypeScript.
entity folder contains the TypeORM models. A default User model will be created by CLI and it is as follows −
import {Entity, PrimaryGeneratedColumn, Column} from "typeorm"; 

@Entity() 
export class User { 
   
   @PrimaryGeneratedColumn() 
   id: number; 
   
   @Column() 
   firstName: string; 
   
   @Column() 
   lastName: string; 
   
   @Column() 
   age: number; 
}
controller folder contains the express controllers. CLI create a default user API controller with add / list / delete user details. The code is as follows −
import {getRepository} from "typeorm"; import {NextFunction, Request, Response} from "express"; import {User} from "../entity/User"; 

export class UserController {

   private userRepository = getRepository(User); 
   
   async all(request: Request, response: Response, next: NextFunction) { 
      return this.userRepository.find(); 
   } 
   
   async one(request: Request, response: Response, next: NextFunction) { 
      return this.userRepository.findOne(request.params.id); 
   } 
   
   async save(request: Request, response: Response, next: NextFunction) { 
      return this.userRepository.save(request.body); 
   } 
   
   async remove(request: Request, response: Response, next: NextFunction) { 
      let userToRemove = await this.userRepository.findOne(request.params.id); 
      await this.userRepository.remove(userToRemove); 
   } 
}
Here,
all method is used to fetch all users from the database.
one method is used to fetch a single user from the database using user id
save method is used to save the user information into the database.
delete method is used to delete the user from the database using user id
routes.ts file maps the user controller methods to proper URL and the code is as follows −
import {UserController} from "./controller/UserController"; 

export const Routes = [{ 
      method: "get", 
      route: "/users", 
      controller: UserController, action: "all" 
   }, { 
      method: "get", 
      route: "/users/:id", controller: UserController, action: "one" 
   }, { 
      method: "post", 
      route: "/users", 
      controller: UserController, action: "save" 
   }, { 
      method: "delete", route: "/users/:id", controller: UserController,
      action: "remove" 
}];
Here,
/users url is mapped to user controller. Each verb post, get and delete are mapped to different methods.
Finally, index.ts is our main web application entry point. The source code is as follows −
import "reflect-metadata"; 
import {createConnection} from "typeorm"; 
import * as express from "express"; import * as bodyParser from "body-parser"; 
import {Request, Response} from "express"; 
import {Routes} from "./routes"; import {User} from "./entity/User"; 

createConnection().then(async connection => { 

   // create express app const app = express(); app.use(bodyParser.json()); 

   // register express routes from defined application routes Routes.forEach(route => { 
      (app as any)[route.method](route.route, (req:   Request, res: Response, next: Function) => { 
         const result = (new (route.controller as any))[route.action](req, res, next); 
         if (result instanceof Promise) { 
            result.then(result => result !== null && result !== undefined ? res.send(result) : undefined); 
         } else if (result !== null && result !== undefined) { 
            .json(result); 
         } 
      }); 
   }); 
      
   // setup express app here 
   // ... 
      
   // start express server app.listen(3000); 
      
   // insert new users for test await connection.manager.save(connection.manager.create(User, { 
      firstName: "Timber",
      lastName: "Saw", 
      age: 27 
   }));
   await connection.manager.save(connection.manager.create(User, { 
      firstName: "Phantom", 
      lastName: "Assassin", 
      age: 24 
   })); 
      
   console.log("Express server has started on port 3000. Open http://localhost:3000/users to see results"); 
}).catch(error => console.log(error));
Here, the application configures the routes, insert two users and then start the web application at port 3000. We can access the application at http://localhost:3000
To run the application, follow below steps −
Let us install the necessary packages using below command −
npm install

npm notice created a lockfile as package-lock.json. You should commit this file. 
npm WARN typeorm-express-sample@0.0.1 No repository field. 
npm WARN typeorm-express-sample@0.0.1 No license field. 

added 176 packages from 472 contributors and audited 351 packages in 11.965s 

3 packages are looking for funding  run `npm fund` for details 

found 0 vulnerabilities
Run the below command to start the application.
npm start

> typeorm-express-sample@0.0.1 start /path/to/workspace/typeorm-express-sample 
> ts-node src/index.ts 

Express server has started on port 3000. Open http://localhost:3000/users to see results
Let us access our web application API using curl command as below −
curl http://localhost:3000/users

Here,
curl is a command line application to access web application from command prompt. It supports all the HTTP verbs such as get, post, delete, etc.,
[{"id":1,"firstName":"Timber","lastName":"Saw","age":27},{"id":2,"firstName":"Phantom","lastName":"Assassin","age":24}]

To fetch the first record, we can use below command −
curl http://localhost:3000/users/1

{"id":1,"firstName":"Timber","lastName":"Saw","age":27}

To delete a user record, we can use below command −
curl -X DELETE http://localhost:3000/users/1

As we seen in this chapter, TypeORM can be easily integrated into express application.

    19 Lectures 
     50 mins

 James Coonce
 Print
 Add Notes
 Bookmark this page