Objection.js
Contributors are welcomeThis tutorial show yous how you can useObjection.js package with Ts.ED.
Installation
Before using the@tsed/objection
package, we need to install theObection.js andKnex modules.
Install the dependencies:
npm install --save @tsed/objection objection knex
yarn add @tsed/objection objection knex
pnpm add @tsed/objection objection knex
bun add @tsed/objection objection knex
We also need to install one of the following depending on the database you want to use:
npm install pgnpm install sqlite3npm install mysqlnpm install mysql2
yarn add pgyarn add sqlite3yarn add mysqlyarn add mysql2
pnpm add pgpnpm add sqlite3pnpm add mysqlpnpm add mysql2
bun add pgbun add sqlite3bun add mysqlbun add mysql2
Configuration
Add aknex
configuration to your Ts.ED configuration (see:http://knexjs.org/#Installation-client for options):
import {Server}from "@tsed/platform-http";import "@tsed/objection";// don't forget to add this line!@Configuration({ // ... knex: { client:"sqlite3", connection:":memory:" }})class Server {}
Usage
You can use theEntity decorator to create your models and make them work with Objection.js.Entity
expects the table name as its argument.
import {Required, MinLength, MaxLength}from "@tsed/schema";import {Inject}from "@tsed/di";import {Entity, IdColumn}from "@tsed/objection";import {Model}from "objection";@Entity("users")export class User extends Model { @IdColumn() id: number; @Property() @MaxLength(200) name: string; @Property() age: number; @Decimal({scale:1, precision:12}) score: number; @Property() active: boolean;}
Relationships
Ts.ED enables you to define relationships between models on properties directly, using decorators such asBelongsToOne,HasMany,HasOne,HasOneThroughRelation,ManyToMany orRelatesTo.
You can supply a configuration object via (RelationshipOpts) into the decorator factor to override the default join keys and configure a relationship like you normally would viarelationMappings
. For collection-type relationships, you must also specify the model you wish to use and we will also apply theCollectionOf decorator for you automatically.
This expressive usage ensures that your domain models are correctly typed for usage alongsideObjection.js's Graph API.
/** * All work in a similar manner: * - @HasMany, @HasOne, @HasOneThroughRelation, @ManyToMany,@RelatesTo */import {Entity, BelongsToOne}from "@tsed/objection";@Entity("user")class User extends Model { @IdColumn() id!: string;}@Entity("movie")class Movie extends Model { @IdColumn() id!: string; ownerId!: string; @BelongsToOne() owner?: User;}// Retrieve the related userconst owner = await Movie.relatedQuery("owner").for(1);// Retrieve the movie with their ownerconst movie = await Movie.query().for(1).withGraphFetched("owner");
Default joining keys
When used in conjunction withEntity andIdColumn, Ts.ED attempts to provide you with a sensible default for your join keys out of the box, reducing the amount of boilerplate you need to write.
In the instance ofBelongsToOne, the default join keys will be:
{ "from":"<sourceModelTable>.<foreignModelProperty>Id", "to":"<foreignModelTable>.<foreignModelIdColumn>"}
TIP
An example of the keys outputted above could bemovie.ownerId
anduser.id
respectively.
In the instances ofHasMany andHasOne, the default join keys will be:
{ "from":"<sourceModelTable>.<sourceModelIdColumn>", "to":"<foreignModelTable>.<sourceModelTable>Id"}
TIP
An example of the keys outputted above could beuser.id
andauthentication.userId
respectively.
In the instances ofManyToMany andHasOneThroughRelation, the default join key will be:
{ "from":"<sourceModelTable>.<sourceModelIdColumn>", "through": { "from":"<sourceModelTable>_<foreignModelTable>.<sourceModelTable>Id", "to":"<sourceModelTable>_<foreignModelTable>.<foreignModelTable>Id" }, "to":"<foreignModelTable>.<foreignModelIdColumn>"}
TIP
An example of the keys outputted above could beuser.id
,user_authentication.userId
,user_authentication.authenticationId
andauthentication.id
respectively.
Get connection
import {OBJECTION_CONNECTION}from "@tsed/objection";@Injectable()class MyService { @Inject(OBJECTION_CONNECTION) connection: OBJECTION_CONNECTION; $onInit() { console.log(this.connection); }}
Migration
Ts.ED can create columns based on the declared Model. UsingcreateColumns, you can implement a migration file as following:
import {createColumns}from "@tsed/objection";import {User}from "../domain/User";import Knexfrom "objection";export async function up(knex: Knex): Promise<any> { return knex.schema.createTable(User.tableName,async (table: Knex.TableBuilder)=> { // createColumns for the given model createColumns(table, User); });}export async function down(knex: Knex): Promise<any> { return knex.schema.dropTable("users");}
Decorators
Ts.ED gives some decorators and services to write your code:
You can also use the common decorators to describe model (Seemodels documentation):