How to Use One Command to Create RESTful APIs with TypeORM CLI on Node.js

The SOLID Principles of Object-Oriented Programming
8th January 2024
Database Schema Design
Database Schema Design – Complete Guide
10th January 2024
Show all

How to Use One Command to Create RESTful APIs with TypeORM CLI on Node.js

TypeORM connects applications to databases. In this article, I’ll show you how to quickly create a new RESTful API microservice on Express (NodeJS) that integrates with MySQL using TypeORM.

ORM is the bridge between the API and your database

If you’re already familiar with using ORMs, let’s jump to one-liners.

Outline

  1. Definitions
  2. Prerequisites
  3. One Liners
  4. Testing

Definitions

  • TypeORM — According to their website, “TypeORM is an ORM that can run in NodeJS, Browser, Cordova, PhoneGap, Ionic, React Native, NativeScript, Expo, and Electron platforms and can be used with TypeScript and JavaScript (ES5, ES6, ES7, ES8).”
  • Object-relational mapping (ORM) — connects apps to databases. You can think of it as using code at the app level to execute queries.
  • MySQL — a popular open-source relational database.
  • Express — web framework for NodeJS.
  • RESTful API — see “WTF is an API?”

Prerequisites

  • NPM
  • MySQL
  • Docker (if you don’t have MySQL)

One Liners

1. Install TypeORM

npm install typeorm

2. Initialize

typeorm init –name user-microservice –database mysql –express

Explanation: This command creates a new TypeORM project with the name user-microservice and scaffolds the necessary code to use Express and MySQL.

Easy! We just created a Node.js project which includes routes, controller, and entity

Explanation: routes.ts is the entry point for the API. UserController.ts is the orchestrator between routes and entity. User.ts is the entity that defines the table schema for the database.

Pause for a minute to look at the code inside each file and see how each of the pieces connect with each other. Notice any patterns?

3. Install packages

cd user-microservice
npm install

4. Database configurations

If you have MySQL already, run a local instance of it, and update the connection settings in ormconfig.json.

Otherwise, use the following Docker command:

docker run --name songtham-mysql -e MYSQL_ROOT_PASSWORD=test -e MYSQL_USER=test -e MYSQL_PASSWORD=test -e MYSQL_DATABASE=test -p 3306:3306 -d mysql:latest --default-authentication-plugin=mysql_native_password

Explanation: This Docker command grabs the latest MySQL version and runs it locally on your computer. Note: If you run this, you don’t need to make any changes to ormconfig.json, as it’s mapped to the default config file already.

5. Start

npm start

Testing

If you did everything correctly, you should see the following message:

Express server has started on port 3000. Open http://localhost:3000/users to see results

GET

Navigate to http://localhost:3000/users, and you’ll see on the page:

[{"id":1,"firstName":"Timber","lastName":"Saw","age":27},{"id":2,"firstName":"Phantom","lastName":"Assassin","age":24}]

You might be wondering, “How did these users appear in the database?”

If you take a look inside index.ts, you can see starting the server creates the users with the following lines of code:

// 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

}));

POST

To add a new record to the users table, run the following CURL command:

curl -d ‘{“firstName”:”Bob”, “lastName”:”Ross”, “age”:”52"}’ -H “Content-Type: application/json” -X POST http://localhost:3000/users

If done correctly, you should get a new entry in your database, and you’ll see the same entry if you go to http://localhost:3000/users.

[{"id":1,"firstName":"Timber","lastName":"Saw","age":27},{"id":2,"firstName":"Phantom","lastName":"Assassin","age":24},{"id":3,"firstName":"Bob","lastName":"Ross","age":52}]

Closing

TypeORM is an easy-to-use ORM that with one line can scaffold new apps that connect to databases. You can use it to quickly create new projects and/or microservices.

This guide covers the basics of using the CLI to initialize a new app, to connect it to MySQL, and to perform GET and POST API requests. There are more advanced features such as migration, fixtures, and entity relations that I’ll cover in future posts. Stay tuned.

Thanks for reading!

For More Info: XpertLab.com/portfolio