New📚 Introducing our captivating new product - Explore the enchanting world of Novel Search with our latest book collection! 🌟📖 Check it out

Write Sign In
Library BookLibrary Book
Write
Sign In
Member-only story

Quick Start to Using TypeScript and TypeORM on Node.js for CLI and Web

Jese Leos
·17.7k Followers· Follow
Published in Quick Start To Using Typescript And TypeORM On Node Js For CLI And Web Applications
7 min read ·
423 View Claps
33 Respond
Save
Listen
Share

TypeScript and TypeORM are two of the most popular tools for building robust Node.js applications. TypeScript is a superset of JavaScript that adds static typing, while TypeORM is an object-relational mapper (ORM) that makes it easy to work with databases.

Quick Start to using Typescript and TypeORM on Node js for CLI and web applications
Quick Start to using Typescript and TypeORM on Node.js for CLI and web applications
by David Herron

5 out of 5

Language : English
File size : 3258 KB
Text-to-Speech : Enabled
Screen Reader : Supported
Enhanced typesetting : Enabled
Print length : 444 pages
Lending : Enabled

In this comprehensive guide, we'll show you how to use TypeScript and TypeORM to build both CLI and web-based Node.js applications. We'll cover everything from setup and configuration to advanced topics like dependency injection and testing.

Prerequisites

To follow along with this guide, you'll need the following:

  • Node.js installed on your system
  • A code editor or IDE, such as Visual Studio Code
  • A basic understanding of JavaScript

Getting Started

Let's start by creating a new Node.js project. Open your terminal and run the following command:

mkdir my-project cd my-project npm init -y

This will create a new directory called "my-project" and initialize a new npm project.

Next, we need to install TypeScript and TypeORM. Run the following command:

npm install --save-dev typescript typeorm

This will install TypeScript and TypeORM as development dependencies.

Now, we need to configure TypeScript. Create a file called "tsconfig.json" in the root of your project directory. Add the following contents to the file:

{ "compilerOptions": { "target": "es5", "module": "commonjs", "outDir": "./dist", "sourceMap": true, "strict": true, "noImplicitAny": true, }}

This configuration tells TypeScript to compile our code to ES5, use the CommonJS module system, and output the compiled code to the "dist" directory. We've also enabled source maps, strict mode, and implicit any type checking.

Finally, we need to configure TypeORM. Create a file called "ormconfig.json" in the root of your project directory. Add the following contents to the file:

{ "type": "mysql", "host": "localhost", "port": 3306, "username": "root", "password": "", "database": "my_database", }

This configuration tells TypeORM to use MySQL as our database, and specifies the host, port, username, password, and database name.

Building a CLI Application

Now that we have TypeScript and TypeORM configured, let's build a simple CLI application. Create a file called "index.ts" in the root of your project directory. Add the following contents to the file:

import {createConnection}from "typeorm"; import {User}from "./entity/User";

createConnection().then(async connection => { const user = new User(); user.firstName ="John"; user.lastName ="Doe"; await connection.manager.save(user); console.log("User created successfully!"); });

This script imports the "createConnection" function from TypeORM, and the "User" class from a file called "entity/User.ts". We'll create that file in a moment.

The "createConnection" function establishes a connection to our database. Once the connection is established, we create a new "User" instance and set its first name and last name. We then use the "save" method to save the user to the database.

To create the "entity/User.ts" file, run the following command:

touch entity/User.ts

Add the following contents to the file:

import {Entity, PrimaryGeneratedColumn, Column}from "typeorm";

@Entity() export class User {

@PrimaryGeneratedColumn() id: number;

@Column() firstName: string;

@Column() lastName: string;

}

This script defines the "User" entity. The "@Entity()" decorator tells TypeORM that this class represents a database table. The "@PrimaryGeneratedColumn()" decorator tells TypeORM that the "id" property is the primary key of the table, and that it should be auto-generated. The "@Column()" decorator tells TypeORM that the "firstName" and "lastName" properties are columns in the table.

Now, we can run our CLI application. Open your terminal and run the following command:

tsc && node dist/index.js

This will compile our TypeScript code and then run the compiled JavaScript code. You should see the following output:

User created successfully!

This means that our CLI application has successfully created a new user in our database.

Building a Web Application

Now that we've seen how to use TypeScript and TypeORM to build a CLI application, let's see how to use them to build a web application.

Create a new directory called "web" in the root of your project directory. This directory will contain the code for our web application.

In the "web" directory, create a file called "server.ts". Add the following contents to the file:

import express from "express"; import {createConnection}from "typeorm"; import {User}from "../entity/User";

const app = express(); app.use(express.json());

createConnection().then(async connection => { app.get("/users", async (req, res) => { const users = await connection.manager.find(User); res.json(users); });

app.post("/users", async (req, res) => { const user = new User(); user.firstName = req.body.firstName; user.lastName = req.body.lastName; await connection.manager.save(user); res.json(user); });

app.listen(3000, () => { console.log("Server is listening on port 3000"); }); });

This script imports the "express" module, the "createConnection" function from TypeORM, and the "User" class from the "../entity/User.ts" file.

The "createConnection" function establishes a connection to our database. Once the connection is established, we define two routes: a GET route for fetching all users, and a POST route for creating a new user.

To start our web application, open your terminal and run the following command:

tsc --watch

This will watch for changes to our TypeScript code and compile it automatically.

In another terminal window, run the following command:

cd web node server.js

This will start our web application. Open your browser and go to http://localhost:3000. You should see a list of all users in your database.

Click the "Create User" button to create a new user. Enter a first name and last name, and then click the "Create" button. You should see the new user appear in the list.

Advanced Topics

In this section, we'll cover some advanced topics related to using TypeScript and TypeORM.

Dependency Injection

Dependency injection is a design pattern that allows us to decouple our code from конкретные реализации. This makes our code more flexible and easier to test.

TypeORM supports dependency injection through its "injectable" decorator. To use dependency injection, we can add the "@Injectable()" decorator to our constructor functions. For example, the following script shows how we can inject the "connection" object into our "UserRepository":

import {Injectable}from "typeorm"; import {Connection}from "typeorm";

@Injectable() export class UserRepository {

private connection: Connection;

constructor(connection: Connection){this.connection = connection; }

// ...

}

We can then inject the "UserRepository" into our other classes, such as our controllers:

import {Injectable}from "typeorm"; import {UserRepository}from "./UserRepository";

@Injectable() export class UserController {

private userRepository: UserRepository;

constructor(userRepository: UserRepository){this.userRepository = userRepository

Quick Start to using Typescript and TypeORM on Node js for CLI and web applications
Quick Start to using Typescript and TypeORM on Node.js for CLI and web applications
by David Herron

5 out of 5

Language : English
File size : 3258 KB
Text-to-Speech : Enabled
Screen Reader : Supported
Enhanced typesetting : Enabled
Print length : 444 pages
Lending : Enabled
Create an account to read the full story.
The author made this story available to Library Book members only.
If you’re new to Library Book, create a new account to read this story on us.
Already have an account? Sign in
423 View Claps
33 Respond
Save
Listen
Share

Light bulbAdvertise smarter! Our strategic ad space ensures maximum exposure. Reserve your spot today!

Good Author
  • Herman Mitchell profile picture
    Herman Mitchell
    Follow ·18.2k
  • Jon Reed profile picture
    Jon Reed
    Follow ·9.5k
  • Owen Simmons profile picture
    Owen Simmons
    Follow ·19.1k
  • Edwin Blair profile picture
    Edwin Blair
    Follow ·18.8k
  • Daniel Knight profile picture
    Daniel Knight
    Follow ·17k
  • Jacques Bell profile picture
    Jacques Bell
    Follow ·6.8k
  • Elliott Carter profile picture
    Elliott Carter
    Follow ·13.7k
  • Caleb Long profile picture
    Caleb Long
    Follow ·3.4k
Recommended from Library Book
Celebrating Winter Solstice: Customs And Crafts Recipes And Rituals For Festivals Of Light Hanukkah Yule And Other Midwinter Holidays (Celebrating The Seasonal Holidays 4)
Isaac Bell profile pictureIsaac Bell

Unveiling the Enchanting World of Customs and Crafts:...

Embark on a captivating journey through the...

·6 min read
150 View Claps
22 Respond
How To Write Nonfiction Memoir (A BookCraft Guide)
Allen Parker profile pictureAllen Parker
·5 min read
148 View Claps
27 Respond
Celebrating Spring Equinox: Customs Crafts Recipes Rituals For Celebrating Easter Passover Nowruz Lady Day Other Spring Holidays (Celebrating The Seasonal Holidays 1)
Nathaniel Powell profile pictureNathaniel Powell

Celebrate Spring's Arrival with Traditions from Around...

Immerse Yourself in the Vibrant Cultures of...

·8 min read
694 View Claps
87 Respond
Faces We Love Shanghai Derek Muhs
Steve Carter profile pictureSteve Carter
·5 min read
465 View Claps
62 Respond
The Muscular System Manual: The Skeletal Muscles Of The Human Body
Hunter Mitchell profile pictureHunter Mitchell

The Skeletal Muscles of the Human Body: An In-Depth Guide

The skeletal muscles of the human body are...

·5 min read
918 View Claps
61 Respond
First Aid Q A For The NBDE Part I (First Aid Series)
Justin Bell profile pictureJustin Bell
·4 min read
106 View Claps
15 Respond
The book was found!
Quick Start to using Typescript and TypeORM on Node js for CLI and web applications
Quick Start to using Typescript and TypeORM on Node.js for CLI and web applications
by David Herron

5 out of 5

Language : English
File size : 3258 KB
Text-to-Speech : Enabled
Screen Reader : Supported
Enhanced typesetting : Enabled
Print length : 444 pages
Lending : Enabled
Sign up for our newsletter and stay up to date!

By subscribing to our newsletter, you'll receive valuable content straight to your inbox, including informative articles, helpful tips, product launches, and exciting promotions.

By subscribing, you agree with our Privacy Policy.


© 2024 Library Book™ is a registered trademark. All Rights Reserved.