# Objection.js

alpha Contributors are welcome

This tutorial show yous how you can use Objection.js (opens new window) package with Ts.ED.

# Installation

Before using the @tsed/objection package, we need to install the Obection.js (opens new window) and Knex (opens new window) modules.

Install the dependencies:

npm install --save @tsed/objection objection knex
1

We also need to install one of the following depending on the database you want to use:

npm install pg
npm install sqlite3
npm install mysql
npm install mysql2
1
2
3
4

# Configuration

Add a knex configuration to your Ts.ED configuration (see: http://knexjs.org/#Installation-client for options):

import {Server} from "@tsed/common";
import "@tsed/objection"; // don't forget to add this line!

@Configuration({
  // ...
  knex: {
    client: 'sqlite3',
    connection: ':memory:'
  }
})
class Server {}
1
2
3
4
5
6
7
8
9
10
11

# Usage

You can use the EntityOptions decorator to create your models and make them work with Objection.js. Entity expects the table name as its argument.

import {Required, MinLength, MaxLength, Inject} from "@tsed/common";
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;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# Get connection

import {OBJECTION_CONNECTION} from "@tsed/objection"; 

@Injectable()
class MyService {
  @Inject(OBJECTION_CONNECTION)
  connection: OBJECTION_CONNECTION;
  
  $onInit() {
    console.log(this.connection)
  }
}
1
2
3
4
5
6
7
8
9
10
11

# Migration

Ts.ED can create columns based on the declared Model. Using createColumns , you can implement a migration file as following:

import {createColumns} from "@tsed/objection";
import {User} from "../domain/User";
import Knex from "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");
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# Decorators

Ts.ED gives some decorators and services to write your code:

    You can also use the common decorators to describe model (See models documentation):

    # Author

      # Maintainers

        Last Updated: 11/27/2020, 5:55:17 PM

        Other topics