Example using TypeORM with Express

Initial setup

Let’s create a simple application called “user” which stores users in the databaseand allows us to create, update, remove, and get a list of all users, as well as a single user by idwithin web api.

First, create a directory called “user”:

  1. mkdir user

Then switch to the directory and create a new project:

  1. cd user
  2. npm init

Finish the init process by filling in all required application information.

Now we need to install and setup a TypeScript compiler. Lets install it first:

  1. npm i typescript --save-dev

Then let’s create a tsconfig.json file which contains the configuration required for the application tocompile and run. Create it using your favorite editor and put the following configuration:

  1. {
  2. "compilerOptions": {
  3. "lib": ["es5", "es6", "dom"],
  4. "target": "es5",
  5. "module": "commonjs",
  6. "moduleResolution": "node",
  7. "emitDecoratorMetadata": true,
  8. "experimentalDecorators": true
  9. }
  10. }

Now let’s create a main application endpoint - app.ts inside the src directory:

  1. mkdir src
  2. cd src
  3. touch app.ts

Let’s add a simple console.log inside it:

  1. console.log("Application is up and running");

Now it’s time to run our application.To run it, you need to compile your typescript project first:

  1. tsc

Once you compile it, you should have a src/app.js file generated.You can run it using:

  1. node src/app.js

You should see the, “Application is up and running” message in your console right after you run the application.

You must compile your files each time you make a change.Alternatively, you can setup watcher or install ts-node to avoid manual compilation each time.

Adding Express to the application

Let’s add Express to our application. First, let’s install the packages we need:

  1. npm i express body-parser @types/express @types/body-parser --save
  • express is the express engine itself. It allows us to create a web api
  • body-parser is used to setup how express would handle body sent by a client
  • @types/express is used to have a type information when using express
  • @types/body-parser is used to have a type information when using body parser

Let’s edit the src/app.ts file and add express-related logic:

  1. import * as express from "express";
  2. import {Request, Response} from "express";
  3. import * as bodyParser from "body-parser";
  4. // create and setup express app
  5. const app = express();
  6. app.use(bodyParser.json());
  7. // register routes
  8. app.get("/users", function(req: Request, res: Response) {
  9. // here we will have logic to return all users
  10. });
  11. app.get("/users/:id", function(req: Request, res: Response) {
  12. // here we will have logic to return user by id
  13. });
  14. app.post("/users", function(req: Request, res: Response) {
  15. // here we will have logic to save a user
  16. });
  17. app.put("/users/:id", function(req: Request, res: Response) {
  18. // here we will have logic to update a user by a given user id
  19. });
  20. app.delete("/users/:id", function(req: Request, res: Response) {
  21. // here we will have logic to delete a user by a given user id
  22. });
  23. // start express server
  24. app.listen(3000);

Now you can compile and run your project.You should have an express server running now with working routes.However, those routes do not return any content yet.

Adding TypeORM to the application

Finally, let’s add TypeORM to the application.In this example, we will use mysql driver.Setup process for other drivers is similar.

Let’s install the required packages first:

  1. npm i typeorm mysql reflect-metadata --save
  • typeorm is the typeorm package itself
  • mysql is the underlying database driver.If you are using a different database system, you must install the appropriate package
  • reflect-metadata is required to make decorators to work properly

Now let’s create ormconfig.json with the database connection configuration we will use.

  1. {
  2. "type": "mysql",
  3. "host": "localhost",
  4. "port": 3306,
  5. "username": "test",
  6. "password": "test",
  7. "database": "test",
  8. "entities": ["src/entity/*.js"],
  9. "logging": true,
  10. "synchronize": true
  11. }

Configure each option as you need.Learn more about connection options.

Let’s create a User entity inside src/entity:

  1. import {Entity, Column, PrimaryGeneratedColumn} from "typeorm";
  2. @Entity()
  3. export class User {
  4. @PrimaryGeneratedColumn()
  5. id: number;
  6. @Column()
  7. firstName: string;
  8. @Column()
  9. lastName: string;
  10. }

Let’s change src/app.ts:

  1. import * as express from "express";
  2. import {Request, Response} from "express";
  3. import * as bodyParser from "body-parser";
  4. import {createConnection} from "typeorm";
  5. import {User} from "./entity/User";
  6. // create typeorm connection
  7. createConnection().then(connection => {
  8. const userRepository = connection.getRepository(User);
  9. // create and setup express app
  10. const app = express();
  11. app.use(bodyParser.json());
  12. // register routes
  13. app.get("/users", async function(req: Request, res: Response) {
  14. const users = await userRepository.find();
  15. res.json(users);
  16. });
  17. app.get("/users/:id", async function(req: Request, res: Response) {
  18. const results = await userRepository.findOne(req.params.id);
  19. return res.send(results);
  20. });
  21. app.post("/users", async function(req: Request, res: Response) {
  22. const user = await userRepository.create(req.body);
  23. const results = await userRepository.save(user);
  24. return res.send(results);
  25. });
  26. app.put("/users/:id", async function(req: Request, res: Response) {
  27. const user = await userRepository.findOne(req.params.id);
  28. userRepository.merge(user, req.body);
  29. const results = await userRepository.save(user);
  30. return res.send(results);
  31. });
  32. app.delete("/users/:id", async function(req: Request, res: Response) {
  33. const results = await userRepository.delete(req.params.id);
  34. return res.send(results);
  35. });
  36. // start express server
  37. app.listen(3000);
  38. });

If you want to extract action callbacks into separate files and you need the connection instance,you can simply use getConnection:

  1. import {getConnection} from "typeorm";
  2. import {User} from "./entity/User";
  3. export function UsersListAction(req: Request, res: Response) {
  4. return getConnection().getRepository(User).find();
  5. }

You don’t even need getConnection in this example - you can directly use the getRepository function:

  1. import {getRepository} from "typeorm";
  2. import {User} from "./entity/User";
  3. export function UsersListAction(req: Request, res: Response) {
  4. return getRepository(User).find();
  5. }