{"id":23469099,"url":"https://github.com/etienne-bechara/nestjs-orm","last_synced_at":"2025-09-03T17:35:06.559Z","repository":{"id":132666946,"uuid":"352093088","full_name":"etienne-bechara/nestjs-orm","owner":"etienne-bechara","description":"ORM Module Component for NestJS Projects","archived":false,"fork":false,"pushed_at":"2022-11-12T03:49:51.000Z","size":1274,"stargazers_count":4,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-03-28T04:28:37.312Z","etag":null,"topics":["mikro-orm","nestjs","orm"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/etienne-bechara.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-03-27T14:26:30.000Z","updated_at":"2024-02-07T19:55:41.000Z","dependencies_parsed_at":"2023-06-01T16:31:08.262Z","dependency_job_id":null,"html_url":"https://github.com/etienne-bechara/nestjs-orm","commit_stats":null,"previous_names":[],"tags_count":111,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/etienne-bechara%2Fnestjs-orm","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/etienne-bechara%2Fnestjs-orm/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/etienne-bechara%2Fnestjs-orm/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/etienne-bechara%2Fnestjs-orm/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/etienne-bechara","download_url":"https://codeload.github.com/etienne-bechara/nestjs-orm/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248906841,"owners_count":21181225,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["mikro-orm","nestjs","orm"],"created_at":"2024-12-24T14:59:31.883Z","updated_at":"2025-04-14T15:35:17.563Z","avatar_url":"https://github.com/etienne-bechara.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"⚠️ **Disclaimer**: This project is opinionated and intended for personal use.\n\n---\n\n# NestJS ORM Component\n\nThis package acts as a plugin for [NestJS Core Components](https://github.com/etienne-bechara/nestjs-core) and adds ORM capabilities including service functionalities and controllers.\n\nSupports MongoDB, MySQL, MariaDB, PostgreSQL and SQLite.\n\n## Installation\n\nThe following instructions considers you already have a project set up with [@bechara/nestjs-core](https://www.npmjs.com/package/@bechara/nestjs-core).\n\nIf not, please refer to documentation above before proceeding.\n\n\n1\\. Install the new necessary dependencies:\n\n```\nnpm i @bechara/nestjs-orm\n```\n\n2\\. Add these example variables to your `.env` (adjust accordingly):\n\n```bash\n# Standard connection\nORM_TYPE='mysql'\nORM_HOST='localhost'\nORM_PORT=3306\nORM_USERNAME='root'\nORM_PASSWORD=''\nORM_DATABASE='test'\n\n# SSL options\nORM_SERVER_CA=''\nORM_CLIENT_CERTIFICATE=''\nORM_CLIENT_KEY=''\n```\n\nIt is recommended that you have a local database in order to test connectivity.\n\n3\\. Import `OrmModule` and `OrmConfig` into you boot script and configure asynchronously:\n\n```ts\nimport { AppEnvironment, AppModule } from '@bechara/nestjs-core';\nimport { OrmConfig. OrmModule } from '@bechara/nestjs-orm';\n\nvoid AppModule.bootServer({\n  configs: [ OrmConfig ],\n  imports: [\n    OrmModule.registerAsync({\n      inject: [ OrmConfig ],\n      useFactory: (ormConfig: OrmConfig) =\u003e ({\n        type: ormConfig.ORM_TYPE,\n        host: ormConfig.ORM_HOST,\n        port: ormConfig.ORM_PORT,\n        dbName: ormConfig.ORM_DATABASE,\n        user: ormConfig.ORM_USERNAME,\n        password: ormConfig.ORM_PASSWORD,\n        pool: { min: 1, max: 25 },\n        sync: {\n          auto: true,\n          controller: true,\n          safe: ormConfig.NODE_ENV === AppEnvironment.PRODUCTION,\n        },\n        // SSL configuration (optional)\n        driverOptions: {\n          connection: {\n            ssl: {\n              ca: Buffer.from(ormConfig.ORM_SERVER_CA, 'base64'),\n              cert: Buffer.from(ormConfig.ORM_CLIENT_CERTIFICATE, 'base64'),\n              key: Buffer.from(ormConfig.ORM_CLIENT_KEY, 'base64'),\n            },\n          },\n        }\n      }),\n    }),\n  ],\n  providers: [ OrmConfig ],\n  exports: [ OrmConfig, OrmModule ],\n});\n```\n\nIf you wish to change how environment variables are injected you may provide your own configuration instead of using the built-in `OrmConfig`.\n\n4\\. Before booting the application, create at least one entity inside your project source. Refer to **Usage** section below for further details.\n\n\n## Usage\n\nWe may simplify the process of adding data storage functionality as:\n- Create the entity definition (table, columns and relationships)\n- Create its service (repository abstraction extending provided one)\n- Create its controller (extending provided one)\n\n### Creating an Entity Definition\n\nPlease refer to the official [Defining Entities](https://mikro-orm.io/docs/defining-entities) documentation from MikroORM.\n\n### Creating an Entity Repository\n\nIn order to create a new entity repository, extend the provided abstract repository from this package.\n\nThen, you should call its super method passing this instance as well as an optional object with further customizations.\n\nExample:\n\n```ts\nimport { EntityManager, EntityName, OrmRepository, Repository } from '@bechara/nestjs-orm';\n\nimport { User } from './user.entity';\n\n@Repository(User)\nexport class UserRepository extends OrmRepository\u003cUser\u003e {\n\n  public constructor(\n    protected readonly entityManager: EntityManager,\n    protected readonly entityName: EntityName\u003cUser\u003e,\n  ) {\n    super(entityManager, entityName, {\n      defaultUniqueKey: [ 'name', 'surname' ],\n    });\n  }\n\n}\n```\n\nAt this point, an injectable `UserRepository` will be available throughout the application, exposing extra ORM functionalities.\n\n```ts\n// Read operations\npopulate(): Promise\u003cvoid\u003e;\nreadBy(): Promise\u003cEntity[]\u003e;\nreadById(): Promise\u003cEntity\u003e;\nreadByIdOrFail(): Promise\u003cEntity\u003e;\nreadUnique(): Promise\u003cEntity\u003e;\nreadUniqueOrFail(): Promise\u003cEntity\u003e;\ncountBy(): Promise\u003cnumber\u003e;\nreadPaginatedBy(): Promise\u003cOrmPaginatedResponse\u003cEntity\u003e\u003e;\n\n// Create operations\nbuild(): Entity[];\nbuildOne(): Entity;\ncreate(): Promise\u003cEntity[]\u003e;\ncreateOne(): Promise\u003cEntity\u003e;\n\n// Update operations\nupdate(): Promise\u003cEntity[]\u003e;\nupdateBy(): Promise\u003cEntity[]\u003e;\nupdateById(): Promise\u003cEntity\u003e;\nupdateOne(): Promise\u003cEntity\u003e;\nupsert(): Promise\u003cEntity[]\u003e;\nupsertOne(): Promise\u003cEntity\u003e;\n\n// Async manipulation (optional)\ncommit(): Promise\u003cvoid\u003e;\n```\n\n### Creating an Subscriber\n\nIf you would like to create hooks when triggering certain operations, it is possible by defining an injectable subscriber:\n\n```ts\nimport { Injectable, LoggerService } from '@bechara/nestjs-core';\nimport { EntityManager, OrmSubscriber, OrmSubscriberParams } from '@bechara/nestjs-orm';\n\nimport { User } from './user.entity';\n\n@Injectable()\nexport class UserSubscriber implements OrmSubscriber\u003cUser\u003e {\n\n  public constructor(\n    private readonly entityManager: EntityManager,\n    private readonly loggerService: LoggerService,\n  ) {\n    entityManager.getEventManager().registerSubscriber(this);\n  }\n\n  /**\n   * Before update hook example.\n   * @param params\n   */\n  public beforeUpdate(params: OrmSubscriberParams\u003cUser\u003e): Promise\u003cvoid\u003e {\n    const { changeSet } = params;\n    this.loggerService.warning('beforeUpdate: changeSet', changeSet);\n    return;\n  }\n\n}\n```\n\n\n### Creating an Entity Controller\n\nFinally, expose a controller injecting your repository as dependency to allow manipulation through HTTP requests.\n\nIf you are looking for CRUD functionality you may copy exactly as the template below.\n\nExample:\n\n```ts\nimport { Body, Controller, Delete, Get, Param, Patch, Post, Put, Query } from '@bechara/nestjs-core';\nimport { OrmController, OrmPagination } from '@bechara/nestjs-orm';\n\n// These DTOs are validations customized with class-validator and class-transformer\nimport { UserCreateDto, UserReadDto, UserUpdateDto } from './user.dto';\nimport { User } from './user.entity';\nimport { UserService } from './user.service';\n\n@Controller('user')\nexport class UserController {\n\n  public constructor(\n    private readonly userRepository: UserRepository,\n  ) { }\n\n  @Get()\n  public async get(@Query() query: UserReadDto): Promise\u003cOrmPagination\u003cUser\u003e\u003e {\n    return this.userRepository.readPaginatedBy(query);\n  }\n\n  @Get(':id')\n  public async getById(@Param('id') id: string): Promise\u003cUser\u003e {\n    return this.userRepository.readByIdOrFail(id);\n  }\n\n  @Post()\n  public async post(@Body() body: UserCreateDto): Promise\u003cUser\u003e {\n    return this.userRepository.createOne(body);\n  }\n\n  @Put()\n  public async put(@Body() body: UserCreateDto): Promise\u003cUser\u003e {\n    return this.userRepository.upsertOne(body);\n  }\n\n  @Put(':id')\n  public async putById(@Param('id') id: string, @Body() body: UserCreateDto): Promise\u003cUser\u003e {\n    return this.userRepository.updateById(id, body);\n  }\n\n  @Patch(':id')\n  public async patchById(@Param('id') id: string, @Body() body: UserUpdateDto): Promise\u003cUser\u003e {\n    return this.userRepository.updateById(id, body);\n  }\n\n  @Delete(':id')\n  public async deleteById(@Param('id') id: string): Promise\u003cUser\u003e {\n    return this.userRepository.deleteById(id);\n  }\n\n}\n```\n\n\n## Full Examples\n\nRefer to `test` folder of this project for a full working example including:\n- Entities with several different column types\n- Entity relationships including ManyToOne and ManyToMany\n- Service repository extension\n- Controller extension with CRUD functionality\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fetienne-bechara%2Fnestjs-orm","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fetienne-bechara%2Fnestjs-orm","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fetienne-bechara%2Fnestjs-orm/lists"}