TypeORM
FoalTS components using TypeORM officially support the following databases: PostgreSQL, MySQL, MariaDB and SQLite.
A simple model:
import { Column, Entity, PrimaryGeneratedColumn } from 'typeorm';
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
firstName: string;
@Column()
lastName: string;
}
The ORM
FoalTS uses TypeORM as default Object-Relational Mapping. This allows you to create classes to interact with your database tables (or collections). TypeORM is written in TypeScript and supports both Active Record and Data Mapper patterns.
Here is a non-exhaustive list of its features:
- migrations and automatic migrations generation
- uni-directional, bi-directional and self-referenced relations
- eager and lazy relations
- TypeScript support
- connection configuration in json / xml / yml / env formats
- transactions
- etc
TypeORM supports many SQL databases (MySQL / MariaDB / Postgres / SQLite / Microsoft SQL Server / Oracle / sql.js) as well as the MongoDB NoSQL database.
Although this documentation presents the basic features of TypeORM, you may be interested in reading the official documentation to learn more advanced features.
Use with FoalTS
TypeORM is integrated by default in each new FoalTS project. This allows you to quickly create models, run migrations and use the authentication system without wasting time on configuration. However, if you do not wish to use it, you can refer to the page Using another ORM.
Initial Configuration
When creating a new project, an SQLite
database is used by default as it does not require any additional installation (the data is saved in a file). The connection configuration is stored in ormconfig.js
and default.json
located respectively at the root of your project and in the config/
directory.
ormconfig.js
const { Config } = require('@foal/core');
module.exports = {
type: 'sqlite',
database: Config.get('database.database'),
dropSchema: Config.get('database.dropSchema', false),
entities: ['build/app/**/*.entity.js'],
migrations: ['build/migrations/*.js'],
cli: {
migrationsDir: 'src/migrations'
},
synchronize: Config.get('database.synchronize', false)
}
default.json (example)
{
"port": 3001,
"settings": {
...
},
"database": {
"database": "./db.sqlite3"
}
}
Packages
npm install typeorm @foal/typeorm
Two packages are required to use TypeORM with FoalTS:
- The package typeorm which is the official one of the ORM. It includes everything you need to create models and make database requests.
- The package @foal/typeorm (maintained by FoalTS) which contains additional components. These are particularly useful when using FoalTS authentication and authorization system.