What is TypeORM and why is it needed?
TypeORM is a powerful Object-Relational Mapping (ORM) library for TypeScript and JavaScript that works with various databases: PostgreSQL, MySQL, MariaDB, SQLite, MS SQL Server, Oracle, and MongoDB (partially). It provides a convenient way to interact with relational databases through an object-oriented approach, allowing developers to work with tables as classes and records as objects.
Main reasons to use TypeORM:
- Typing: Full integration with TypeScript provides strict typing and autocompletion in the IDE.
- Declarative approach: Defining the database schema through decorators or schemas.
- Auto-migrations: Automatic creation and synchronization of the database schema.
- Active Record and Data Mapper: Support for both popular patterns.
- Relation support: One-to-One, One-to-Many, Many-to-Many.
- Query Builder: Flexible query builder for complex SQL queries.
- Cross-platform: Works with Node.js, browsers, React Native, and Ionic.
Installing TypeORM
To install TypeORM and the necessary database drivers, use npm (or yarn):
// Install TypeORMnpm install typeorm --save
// Install reflect-metadata (required for decorators)npm install reflect-metadata --save
// Install driver for PostgreSQLnpm install pg --save
// Install driver for MySQL/MariaDBnpm install mysql2 --save
// Install driver for SQLitenpm install sqlite3 --save
// Install driver for SQL Servernpm install mssql --save
// Install driver for MongoDB (experimental)npm install mongodb --saveAfter installation, add to tsconfig.json:
{ "compilerOptions": { "emitDecoratorMetadata": true, "experimentalDecorators": true }}Quick start with code example
Let's create a simple application for managing users using SQLite (requires no server installation).
1. Create a file data-source.ts for connection configuration:
import { DataSource } from "typeorm";import { User } from "./entity/User";
export const AppDataSource = new DataSource({ type: "sqlite", database: "database.sqlite", synchronize: true, logging: true, entities: [User], subscribers: [], migrations: [],});
// Initialize connectionAppDataSource.initialize() .then(() => { console.log("Data Source has been initialized!"); }) .catch((err) => { console.error("Error during Data Source initialization:", err); });2. Create the User entity in the file entity/User.ts:
import { Entity, PrimaryGeneratedColumn, Column } from "typeorm";
@Entity()export class User { @PrimaryGeneratedColumn() id: number;
@Column() firstName: string;
@Column() lastName: string;
@Column({ unique: true }) email: string;
@Column({ default: true }) isActive: boolean;}3. Create a file index.ts to demonstrate the functionality:
import "reflect-metadata";import { AppDataSource } from "./data-source";import { User } from "./entity/User";
async function main() { await AppDataSource.initialize();
// Create a new user const user = new User(); user.firstName = "Ivan"; user.lastName = "Petrov"; user.email = "ivan@example.com"; user.isActive = true;
// Save to the database await AppDataSource.manager Also in library
Authorization and Authentication in C# (.NET) — Complete Guide
GraphQL in PHP: webonyx/graphql-php library for creating APIs
Working with CSV in Kotlin: Libraries, Parsing, and Data Writing
Geolocation and Maps in C# (.NET): Overview of Libraries and Tools