4.4.3 • Published 1 year ago

@bechara/nestjs-orm v4.4.3

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

⚠️ Disclaimer: This project is opinionated and intended for personal use.


NestJS ORM Component

This package acts as a plugin for NestJS Core Components and adds ORM capabilities including service functionalities and controllers.

Supports MongoDB, MySQL, MariaDB, PostgreSQL and SQLite.

Installation

The following instructions considers you already have a project set up with @bechara/nestjs-core.

If not, please refer to documentation above before proceeding.

1. Install the new necessary dependencies:

npm i @bechara/nestjs-orm

2. Add these example variables to your .env (adjust accordingly):

# Standard connection
ORM_TYPE='mysql'
ORM_HOST='localhost'
ORM_PORT=3306
ORM_USERNAME='root'
ORM_PASSWORD=''
ORM_DATABASE='test'

# SSL options
ORM_SERVER_CA=''
ORM_CLIENT_CERTIFICATE=''
ORM_CLIENT_KEY=''

It is recommended that you have a local database in order to test connectivity.

3. Import OrmModule and OrmConfig into you boot script and configure asynchronously:

import { AppEnvironment, AppModule } from '@bechara/nestjs-core';
import { OrmConfig. OrmModule } from '@bechara/nestjs-orm';

void AppModule.bootServer({
  configs: [ OrmConfig ],
  imports: [
    OrmModule.registerAsync({
      inject: [ OrmConfig ],
      useFactory: (ormConfig: OrmConfig) => ({
        type: ormConfig.ORM_TYPE,
        host: ormConfig.ORM_HOST,
        port: ormConfig.ORM_PORT,
        dbName: ormConfig.ORM_DATABASE,
        user: ormConfig.ORM_USERNAME,
        password: ormConfig.ORM_PASSWORD,
        pool: { min: 1, max: 25 },
        sync: {
          auto: true,
          controller: true,
          safe: ormConfig.NODE_ENV === AppEnvironment.PRODUCTION,
        },
        // SSL configuration (optional)
        driverOptions: {
          connection: {
            ssl: {
              ca: Buffer.from(ormConfig.ORM_SERVER_CA, 'base64'),
              cert: Buffer.from(ormConfig.ORM_CLIENT_CERTIFICATE, 'base64'),
              key: Buffer.from(ormConfig.ORM_CLIENT_KEY, 'base64'),
            },
          },
        }
      }),
    }),
  ],
  providers: [ OrmConfig ],
  exports: [ OrmConfig, OrmModule ],
});

If you wish to change how environment variables are injected you may provide your own configuration instead of using the built-in OrmConfig.

4. Before booting the application, create at least one entity inside your project source. Refer to Usage section below for further details.

Usage

We may simplify the process of adding data storage functionality as:

  • Create the entity definition (table, columns and relationships)
  • Create its service (repository abstraction extending provided one)
  • Create its controller (extending provided one)

Creating an Entity Definition

Please refer to the official Defining Entities documentation from MikroORM.

Creating an Entity Repository

In order to create a new entity repository, extend the provided abstract repository from this package.

Then, you should call its super method passing this instance as well as an optional object with further customizations.

Example:

import { EntityManager, EntityName, OrmRepository, Repository } from '@bechara/nestjs-orm';

import { User } from './user.entity';

@Repository(User)
export class UserRepository extends OrmRepository<User> {

  public constructor(
    protected readonly entityManager: EntityManager,
    protected readonly entityName: EntityName<User>,
  ) {
    super(entityManager, entityName, {
      defaultUniqueKey: [ 'name', 'surname' ],
    });
  }

}

At this point, an injectable UserRepository will be available throughout the application, exposing extra ORM functionalities.

// Read operations
populate(): Promise<void>;
readBy(): Promise<Entity[]>;
readById(): Promise<Entity>;
readByIdOrFail(): Promise<Entity>;
readUnique(): Promise<Entity>;
readUniqueOrFail(): Promise<Entity>;
countBy(): Promise<number>;
readPaginatedBy(): Promise<OrmPaginatedResponse<Entity>>;

// Create operations
build(): Entity[];
buildOne(): Entity;
create(): Promise<Entity[]>;
createOne(): Promise<Entity>;

// Update operations
update(): Promise<Entity[]>;
updateBy(): Promise<Entity[]>;
updateById(): Promise<Entity>;
updateOne(): Promise<Entity>;
upsert(): Promise<Entity[]>;
upsertOne(): Promise<Entity>;

// Async manipulation (optional)
commit(): Promise<void>;

Creating an Subscriber

If you would like to create hooks when triggering certain operations, it is possible by defining an injectable subscriber:

import { Injectable, LoggerService } from '@bechara/nestjs-core';
import { EntityManager, OrmSubscriber, OrmSubscriberParams } from '@bechara/nestjs-orm';

import { User } from './user.entity';

@Injectable()
export class UserSubscriber implements OrmSubscriber<User> {

  public constructor(
    private readonly entityManager: EntityManager,
    private readonly loggerService: LoggerService,
  ) {
    entityManager.getEventManager().registerSubscriber(this);
  }

  /**
   * Before update hook example.
   * @param params
   */
  public beforeUpdate(params: OrmSubscriberParams<User>): Promise<void> {
    const { changeSet } = params;
    this.loggerService.warning('beforeUpdate: changeSet', changeSet);
    return;
  }

}

Creating an Entity Controller

Finally, expose a controller injecting your repository as dependency to allow manipulation through HTTP requests.

If you are looking for CRUD functionality you may copy exactly as the template below.

Example:

import { Body, Controller, Delete, Get, Param, Patch, Post, Put, Query } from '@bechara/nestjs-core';
import { OrmController, OrmPagination } from '@bechara/nestjs-orm';

// These DTOs are validations customized with class-validator and class-transformer
import { UserCreateDto, UserReadDto, UserUpdateDto } from './user.dto';
import { User } from './user.entity';
import { UserService } from './user.service';

@Controller('user')
export class UserController {

  public constructor(
    private readonly userRepository: UserRepository,
  ) { }

  @Get()
  public async get(@Query() query: UserReadDto): Promise<OrmPagination<User>> {
    return this.userRepository.readPaginatedBy(query);
  }

  @Get(':id')
  public async getById(@Param('id') id: string): Promise<User> {
    return this.userRepository.readByIdOrFail(id);
  }

  @Post()
  public async post(@Body() body: UserCreateDto): Promise<User> {
    return this.userRepository.createOne(body);
  }

  @Put()
  public async put(@Body() body: UserCreateDto): Promise<User> {
    return this.userRepository.upsertOne(body);
  }

  @Put(':id')
  public async putById(@Param('id') id: string, @Body() body: UserCreateDto): Promise<User> {
    return this.userRepository.updateById(id, body);
  }

  @Patch(':id')
  public async patchById(@Param('id') id: string, @Body() body: UserUpdateDto): Promise<User> {
    return this.userRepository.updateById(id, body);
  }

  @Delete(':id')
  public async deleteById(@Param('id') id: string): Promise<User> {
    return this.userRepository.deleteById(id);
  }

}

Full Examples

Refer to test folder of this project for a full working example including:

  • Entities with several different column types
  • Entity relationships including ManyToOne and ManyToMany
  • Service repository extension
  • Controller extension with CRUD functionality
4.4.3

1 year ago

4.4.1

2 years ago

4.4.0

2 years ago

4.4.2

2 years ago

4.3.2

2 years ago

4.3.1

2 years ago

4.3.4

2 years ago

4.3.3

2 years ago

4.3.0

2 years ago

4.4.0-beta.3

2 years ago

4.4.0-beta.4

2 years ago

4.3.5

2 years ago

4.4.0-beta.1

2 years ago

4.4.0-beta.2

2 years ago

4.2.0

2 years ago

4.1.0

2 years ago

4.1.0-beta.1

2 years ago

4.1.0-beta.2

2 years ago

4.0.1

2 years ago

4.0.2

2 years ago

4.0.0

2 years ago

3.7.5

2 years ago

3.7.4

2 years ago

3.7.3

2 years ago

3.7.2

2 years ago

3.7.6

2 years ago

3.7.0

3 years ago

3.6.0

3 years ago

3.4.6

3 years ago

3.5.1

3 years ago

3.5.0

3 years ago

3.4.5

3 years ago

3.4.4

3 years ago

3.4.3

3 years ago

3.4.2

3 years ago

3.4.0

3 years ago

3.4.1

3 years ago

3.3.1

3 years ago

3.2.2

3 years ago

3.2.3

3 years ago

3.3.0

3 years ago

3.2.1

3 years ago

3.2.0

3 years ago

3.1.3

3 years ago

3.0.1

3 years ago

3.0.0

3 years ago

3.1.2

3 years ago

3.1.1

3 years ago

3.1.0

3 years ago

2.11.0

3 years ago

2.10.1

3 years ago

2.10.0

3 years ago

2.9.10

3 years ago

2.9.9

3 years ago

2.9.8

3 years ago

2.9.7

3 years ago

2.9.6

3 years ago

2.9.5

3 years ago

2.9.2

3 years ago

2.9.1

3 years ago

2.9.4

3 years ago

2.9.3

3 years ago

2.9.0

3 years ago

2.8.12

3 years ago

2.8.11

3 years ago

2.8.14

3 years ago

2.8.13

3 years ago

2.8.10

3 years ago

2.3.0

3 years ago

2.2.1

3 years ago

2.2.0

3 years ago

2.5.0

3 years ago

2.2.3

3 years ago

2.4.0

3 years ago

2.2.2

3 years ago

2.7.0

3 years ago

2.6.1

3 years ago

2.5.2

3 years ago

2.2.5

3 years ago

2.6.0

3 years ago

2.5.1

3 years ago

2.2.4

3 years ago

2.8.1

3 years ago

2.5.4

3 years ago

2.2.7

3 years ago

2.8.0

3 years ago

2.6.2

3 years ago

2.5.3

3 years ago

2.2.6

3 years ago

2.8.3

3 years ago

2.8.2

3 years ago

2.8.5

3 years ago

2.8.4

3 years ago

2.8.7

3 years ago

2.8.6

3 years ago

2.8.9

3 years ago

2.8.8

3 years ago

2.1.0

3 years ago

2.0.3

3 years ago

2.0.4

3 years ago

2.0.2

3 years ago

2.0.1

3 years ago

2.0.0

3 years ago

1.1.1

3 years ago

1.1.0

3 years ago

1.1.2

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago