TypeORM and Knex
Built-in models
@meghjs/core also has its own type-safe models and migrations, built on Kysely, with no extra Megh package. See MeghORM.
The @meghjs/data package adds two database integrations: TypeORM for an entity/repository model, and Knex for a query builder. Install it with the library you use and its driver. It needs @meghjs/core 0.4 or later.
npm i @meghjs/data typeorm pgnpm i @meghjs/data knex pg@meghjs/data is a plugin: once it is installed, app.useTypeORM() and app.useKnex() are available, with no import needed. Projects created with megh new load its types through the generated megh-env.d.ts. In other projects, add that file yourself and include it in tsconfig.json:
/// <reference types="@meghjs/data" />{
"include": ["megh-env.d.ts", "src/**/*"]
}Both methods connect before they resolve, so await them before app.run(). The connection is closed when the app shuts down.
TypeORM
Register the datasource on the app with useTypeORM. It is asynchronous, so await it before the app runs.
import { Megh } from '@meghjs/core';
import { User } from './models/user';
import { UsersController } from './controllers/users.controller';
const app = Megh.createApplication();
export async function setup() {
await app.useTypeORM({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'postgres',
database: 'myapi',
entities: [User],
synchronize: true, // development only
});
app.useControllers([UsersController]);
return app;
}
export default app;import { Environment, inject } from '@meghjs/core';
import app, { setup } from './app';
async function serve() {
await setup();
const env = inject(Environment);
await app.run(Number(env.get('PORT')) || 4000);
}
serve();INFO
The project generated by megh new compiles to CommonJS, where top-level await is not available. Wrap async setup in a function and await it from your entry point, as above.
Defining an entity
import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn } from 'typeorm';
@Entity({ name: 'user' })
export class User {
@PrimaryGeneratedColumn()
id: number;
@Column()
name: string;
@CreateDateColumn()
createdAt: Date;
}Generate one with the CLI:
npx megh make:model user --typeormInjecting a repository
Use @InjectRepository to receive a TypeORM Repository in any service or controller. It also has a paginate() method, so type it as PaginatedRepository:
import { AppService } from '@meghjs/core';
import { InjectRepository, PaginatedRepository } from '@meghjs/data';
import { User } from '../models/user';
@AppService
export class UserService {
constructor(
@InjectRepository(User)
private readonly userRepository: PaginatedRepository<User>,
) {}
findAll() {
return this.userRepository.find();
}
page(page: number) {
return this.userRepository.paginate({ page, perPage: 20 });
}
findByPk(id: number) {
return this.userRepository.findOneBy({ id });
}
create(body: Partial<User>) {
const user = this.userRepository.create(body);
return this.userRepository.save(user);
}
}Using a config class
Instead of an inline object, useTypeORM also accepts an @AppConfig class. This keeps credentials in one place and gives access to the environment:
import { AppConfig, MeghConfig, Environment } from '@meghjs/core';
import { DataSourceOptions } from 'typeorm';
import { User } from '../models/user';
@AppConfig
export class DatabaseConfig extends MeghConfig<DataSourceOptions> {
config(env: Environment): DataSourceOptions {
return {
type: 'postgres',
url: env.get<string>('DATABASE_URL'),
entities: [User],
};
}
}import { Megh } from '@meghjs/core';
import { DatabaseConfig } from './config/database.config';
const app = Megh.createApplication();
export async function setup() {
await app.useTypeORM(DatabaseConfig);
return app;
}
export default app;Custom repositories
Extend MeghRepository to keep queries in one class, with pagination and transactions built in. Query operators (Like, ILike, In, Not, Between, LessThan, MoreThan, IsNull, Any, Raw, Equal, ArrayContains) are exported from @meghjs/data.
import { MeghRepository, Repository, Like } from '@meghjs/data';
import { User } from '../models/user';
import { AuditService } from '../services/audit.service';
@Repository(User)
export class UserRepository extends MeghRepository<User> {
constructor(private readonly audit: AuditService) {
super();
}
search(term: string, page = 1) {
return this.paginate(
{ where: { name: Like(`%${term}%`) } }, // TypeORM find options
{ page, perPage: 20 },
);
}
rename(id: number, name: string) {
return this.transaction(async (tx) => {
await tx.update({ id }, { name });
await this.audit.log('rename', id);
});
}
}WARNING
In 0.3.0, a @Repository class must declare a constructor that calls super(), even with no dependencies. Without one, resolving it through dependency injection fails on the first query.
transaction(work)joins a transaction that is already active instead of opening a nested one. Thetxrepository keeps your injected dependencies.withManager(manager)returns a copy bound to anotherEntityManager.
Knex
Register the connection with useKnex, which takes a Knex config or an @AppConfig class just like useTypeORM:
import { Megh } from '@meghjs/core';
const app = Megh.createApplication();
export async function setup() {
await app.useKnex({
client: 'pg',
connection: process.env.DATABASE_URL,
});
return app;
}
export default app;Call setup() from serve.ts before app.run(), as in the TypeORM example.
Inject KnexDB to reach the query builder through its client property:
import { AppService } from '@meghjs/core';
import { KnexDB } from '@meghjs/data';
@AppService
export class ReportService {
constructor(private readonly db: KnexDB) {}
activeUsers() {
return this.db.client('user').where({ active: true }).select('*');
}
page(page: number) {
return this.db.paginate(this.db.client('user').orderBy('id'), { page, perPage: 20 });
}
}KnexDB throws if it is resolved before useKnex has run, so always register the connection during app setup. paginateKnex(query, { page, perPage }) does the same as db.paginate without injecting KnexDB.
Pagination
Every paginator takes { page, perPage } and returns the same shape:
| Source | Call |
|---|---|
@InjectRepository | repo.paginate({ page, perPage }) |
MeghRepository | this.paginate(findOptions, { page, perPage }) |
KnexDB | db.paginate(query, { page, perPage }) |
Collection | collection.paginate({ page, perPage }) |
{
"data": [ ... ],
"meta": { "total": 57, "page": 2, "perPage": 20, "lastPage": 3, "next": 3, "prev": 1 }
}page defaults to 1 and perPage to 10. next and prev are page numbers. They are null at either end. The Paginated<T> and PageRequest types are exported.
Without a database
For prototypes and tests, Collection gives the same shape of API over an in-memory array — see Controller for an example.
Troubleshooting
| Symptom | Fix |
|---|---|
TypeScript: Property 'useKnex' does not exist (or useTypeORM) | Add megh-env.d.ts and include it in tsconfig.json, as shown above. Importing anything from @meghjs/data in your code has the same effect. |
Runtime: app.useKnex is not a function | List @meghjs/data in package.json dependencies, use @meghjs/core 0.4 or later, and start the app from the project root: plugins are found from the package.json in the current directory. A bundled app has no package.json at runtime; pass the plugin explicitly (below). |
pg is required but not installed | Install the driver named in client (or type for TypeORM). |
Knex is not initialized. Call useKnex first. | A service using KnexDB was created before useKnex finished. Await setup() before app.run(). |
To register the plugin yourself, for a bundled app or to turn off discovery:
import { Megh } from '@meghjs/core';
import { dataPlugin } from '@meghjs/data';
const app = Megh.createApplication({ plugins: [dataPlugin] });