@tsed/typeorm
TypeScript icon, indicating that this package has built-in type declarations

7.68.0 • Public • Published

Ts.ED logo

TypeORM

Build & Release PR Welcome npm version semantic-release code style: prettier github opencollective

Website   •   Getting started   •   Slack   •   Twitter

A package of Ts.ED framework. See website: https://tsed.io/tutorials/typeorm

Feature

Currently, @tsed/typeorm allows you:

  • Configure one or more TypeORM connections via the @Configuration decorator. All databases will be initialized when the server starts during the server's OnInit phase.
  • Use the Entity TypeORM as Model for Controllers, AJV Validation and Swagger.

Installation

To begin, install the TypeORM module for TS.ED:

npm install --save @tsed/typeorm
npm install --save typeorm

Then import @tsed/typeorm in your Server:

import {Configuration} from "@tsed/common";
import "@tsed/typeorm"; // import typeorm ts.ed module

@Configuration({
   typeorm: [
    {
      name: 'default',
      type: 'postgres',
      ...,

       entities: [
         `./entity/*{.ts,.js}`
       ],
       migrations: [
        `./migrations/*{.ts,.js}`
       ],
       subscribers: [
        `./subscriber/*{.ts,.js}`
       ]
    },
    {
       name: 'mongo',
       type: 'mongodb',
       ...
    }
  ]
})
export class Server {

}

TypeORMService

TypeORMService let you to retrieve an instance of TypeORM Connection.

import {Service, AfterRoutesInit} from "@tsed/common";
import {TypeORMService} from "@tsed/typeorm";
import {Connection} from "typeorm";

@Service()
export class UsersService implements AfterRoutesInit {
    private connection: Connection;
    constructor(private typeORMService: TypeORMService) {

    }

    $afterRoutesInit() {
        this.connection = this.typeORMService.get("db1");
    }

    async create(user: User): Promise<User> {

        // do something
        ...
        // Then save
        await this.connection.manager.save(user);
        console.log("Saved a new user with id: " + user.id);

        return user;
    }

    async find(): Promise<User[]> {
        const users = await this.connection.manager.find(User);
        console.log("Loaded users: ", users);

        return users;
    }

}

For more information about TypeORM look his documentation here;

Use Entity TypeORM with Controller

To begin, we need to define an Entity TypeORM like this and use Ts.ED Decorator to define the JSON Schema.

import {Property, MaxLength, Required} from "@tsed/common";
import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";

@Entity()
export class User {
  @PrimaryGeneratedColumn()
  @Property()
  id: number;

  @Column()
  @MaxLength(100)
  @Required()
  firstName: string;

  @Column()
  @MaxLength(100)
  @Required()
  lastName: string;

  @Column()
  @Mininum(0)
  @Maximum(100)
  age: number;
}

Now, the model is correctly defined and can be used with a Controller, AJV validation, Swagger and TypeORM.

We can use this model with a Controller like that:

import {Controller, Post, BodyParams} from "@tsed/common";

@Controller("/users")
export class UsersCtrl {
  constructor(private usersService: UsersService) {}

  @Post("/")
  create(@BodyParams() user: User): Promise<User> {
    return this.usersService.create(user);
  }

  @Get("/")
  getList(): Promise<User[]> {
    return this.usersService.find();
  }
}

Contributors

Please read contributing guidelines here

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

The MIT License (MIT)

Copyright (c) 2016 - 2022 Romain Lenzotti

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Readme

Keywords

none

Package Sidebar

Install

npm i @tsed/typeorm

Weekly Downloads

4,214

Version

7.68.0

License

MIT

Unpacked Size

30.4 kB

Total Files

36

Last publish

Collaborators

  • romakita