@artenc/nest-orm 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.env.example ADDED
@@ -0,0 +1,5 @@
1
+ DB_HOST=127.0.0.1
2
+ DB_PORT=3306
3
+ DB_USER=
4
+ DB_PASS=
5
+ DB_NAME=
package/.eslintrc.js ADDED
@@ -0,0 +1,25 @@
1
+ module.exports = {
2
+ parser: '@typescript-eslint/parser',
3
+ parserOptions: {
4
+ project: 'tsconfig.json',
5
+ tsconfigRootDir: __dirname,
6
+ sourceType: 'module',
7
+ },
8
+ plugins: ['@typescript-eslint/eslint-plugin'],
9
+ extends: [
10
+ 'plugin:@typescript-eslint/recommended',
11
+ 'plugin:prettier/recommended',
12
+ ],
13
+ root: true,
14
+ env: {
15
+ node: true,
16
+ jest: true,
17
+ },
18
+ ignorePatterns: ['.eslintrc.js'],
19
+ rules: {
20
+ '@typescript-eslint/interface-name-prefix': 'off',
21
+ '@typescript-eslint/explicit-function-return-type': 'off',
22
+ '@typescript-eslint/explicit-module-boundary-types': 'off',
23
+ '@typescript-eslint/no-explicit-any': 'off',
24
+ },
25
+ };
package/.prettierrc ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "singleQuote": true,
3
+ "trailingComma": "all"
4
+ }
package/README.md ADDED
@@ -0,0 +1,3 @@
1
+ NestJS ORM Utility module
2
+
3
+ Works with MySQL
@@ -0,0 +1,12 @@
1
+ import { DataSource } from 'typeorm'
2
+
3
+ export default new DataSource({
4
+ type: 'mysql',
5
+ host: 'localhost',
6
+ port: 3306,
7
+ username: '',
8
+ password: '',
9
+ database: '',
10
+ entities: ['**/*.entity.ts'],
11
+ migrations: ['migrations/*.ts'],
12
+ })
package/nest-cli.json ADDED
@@ -0,0 +1,8 @@
1
+ {
2
+ "$schema": "https://json.schemastore.org/nest-cli",
3
+ "collection": "@nestjs/schematics",
4
+ "sourceRoot": "src",
5
+ "compilerOptions": {
6
+ "deleteOutDir": true
7
+ }
8
+ }
package/package.json ADDED
@@ -0,0 +1,66 @@
1
+ {
2
+ "name": "@artenc/nest-orm",
3
+ "version": "0.0.1",
4
+ "description": "",
5
+ "author": "artenc",
6
+ "license": "UNLICENSED",
7
+ "scripts": {
8
+ "build": "nest build",
9
+ "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
10
+ "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
11
+ "test": "jest",
12
+ "test:watch": "jest --watch",
13
+ "test:cov": "jest --coverage",
14
+ "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
15
+ "test:e2e": "jest --config ./test/jest-e2e.json"
16
+ },
17
+ "dependencies": {
18
+ "@nestjs/common": "^10.0.0",
19
+ "@nestjs/config": "^3.3.0",
20
+ "@nestjs/core": "^10.0.0",
21
+ "@nestjs/typeorm": "^10.0.2",
22
+ "class-transformer": "^0.5.1",
23
+ "reflect-metadata": "^0.2.0",
24
+ "rxjs": "^7.8.1",
25
+ "typeorm": "^0.3.20"
26
+ },
27
+ "devDependencies": {
28
+ "@nestjs/cli": "^10.0.0",
29
+ "@nestjs/schematics": "^10.0.0",
30
+ "@nestjs/testing": "^10.0.0",
31
+ "@types/jest": "^29.5.2",
32
+ "@types/node": "^20.3.1",
33
+ "@types/supertest": "^6.0.0",
34
+ "@typescript-eslint/eslint-plugin": "^8.0.0",
35
+ "@typescript-eslint/parser": "^8.0.0",
36
+ "eslint": "^8.0.0",
37
+ "eslint-config-prettier": "^9.0.0",
38
+ "eslint-plugin-prettier": "^5.0.0",
39
+ "jest": "^29.5.0",
40
+ "prettier": "^3.0.0",
41
+ "source-map-support": "^0.5.21",
42
+ "supertest": "^7.0.0",
43
+ "ts-jest": "^29.1.0",
44
+ "ts-loader": "^9.4.3",
45
+ "ts-node": "^10.9.1",
46
+ "tsconfig-paths": "^4.2.0",
47
+ "typescript": "^5.1.3"
48
+ },
49
+ "jest": {
50
+ "moduleFileExtensions": [
51
+ "js",
52
+ "json",
53
+ "ts"
54
+ ],
55
+ "rootDir": "src",
56
+ "testRegex": ".*\\.spec\\.ts$",
57
+ "transform": {
58
+ "^.+\\.(t|j)s$": "ts-jest"
59
+ },
60
+ "collectCoverageFrom": [
61
+ "**/*.(t|j)s"
62
+ ],
63
+ "coverageDirectory": "../coverage",
64
+ "testEnvironment": "node"
65
+ }
66
+ }
@@ -0,0 +1,46 @@
1
+ import { Exclude } from 'class-transformer'
2
+ import { EntityManager, Repository } from 'typeorm'
3
+
4
+ export abstract class AbstractOrmEntity {
5
+ @Exclude()
6
+ private repository: Repository<this>
7
+ @Exclude()
8
+ private entityManager: EntityManager
9
+
10
+ public setRepository(repository: Repository<this>): void {
11
+ if (this.repository || this.entityManager) {
12
+ throw new Error('Cannot reassign Repository or EntityManager')
13
+ }
14
+ this.repository = repository
15
+ }
16
+
17
+ public setEntityManager(entityManager: EntityManager): void {
18
+ if (this.repository || this.entityManager) {
19
+ throw new Error('Cannot reassign Repository or EntityManager')
20
+ }
21
+ this.entityManager = entityManager
22
+ }
23
+
24
+ public save(): Promise<this> {
25
+ return this.repository ?
26
+ this.repository.save(this) :
27
+ this.entityManager.save(this)
28
+ }
29
+
30
+ protected fillable(): string[] {
31
+ return []
32
+ }
33
+
34
+ public apply(fields: any): void {
35
+ const fillable = this.fillable()
36
+
37
+ Object.getOwnPropertyNames(fields)
38
+ .filter(f => fillable.includes(f))
39
+ .forEach(f => {
40
+ const v = fields[f]
41
+ if (v !== undefined) {
42
+ (this as any)[f] = v
43
+ }
44
+ })
45
+ }
46
+ }
@@ -0,0 +1,99 @@
1
+ import { DeepPartial, DeleteResult, EntityManager, FindManyOptions, FindOneOptions, FindOptionsWhere, Repository, UpdateResult } from 'typeorm'
2
+ import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity'
3
+ import { Type } from '@nestjs/common'
4
+ import { InjectRepository } from '@nestjs/typeorm'
5
+ import { AbstractOrmEntity } from './abstract-orm.entity'
6
+
7
+ export interface IOrmService<T extends AbstractOrmEntity> {
8
+ readonly repository: Repository<T>
9
+
10
+ create(props: DeepPartial<T>, entityManager?: EntityManager): Promise<T>
11
+ exists(condition: FindOneOptions<T>, entityManager?: EntityManager): Promise<boolean>
12
+ find(conditions: FindManyOptions<T>, entityManager?: EntityManager): Promise<T[]>
13
+ findOne(conditions: FindOneOptions<T>, entityManager?: EntityManager): Promise<T | null>
14
+ count(conditions: FindManyOptions<T>, entityManager?: EntityManager): Promise<number>
15
+ update(criteria: FindOptionsWhere<T>, props: QueryDeepPartialEntity<T>, entityManager?: EntityManager): Promise<UpdateResult>
16
+ remove(id: number, entityManager?: EntityManager): Promise<DeleteResult>
17
+ }
18
+
19
+ type Constructor<I> = new (...args: any[]) => I
20
+
21
+ export function AbstractOrmService<T extends AbstractOrmEntity>(entity: Constructor<T>): Type<IOrmService<T>> {
22
+ class AbstractOrmServiceHost implements IOrmService<T> {
23
+ @InjectRepository(entity)
24
+ repository: Repository<T>
25
+
26
+ public create(props: DeepPartial<T>, entityManager?: EntityManager): Promise<T> {
27
+ if (entityManager) {
28
+ const model = entityManager.create(entity, props)
29
+ model.setEntityManager(entityManager)
30
+ return entityManager.save(model)
31
+ }
32
+
33
+ const model = this.repository.create(props)
34
+ model.setRepository(this.repository)
35
+ return this.repository.save(model)
36
+ }
37
+
38
+ public async exists(condition: FindOneOptions<T>, entityManager?: EntityManager): Promise<boolean> {
39
+ if (entityManager) {
40
+ return !!(await entityManager.findOne(entity, condition))
41
+ }
42
+
43
+ return !!(await this.repository.findOne(condition))
44
+ }
45
+
46
+ public async find(conditions: FindManyOptions<T>, entityManager?: EntityManager): Promise<T[]> {
47
+ if (entityManager) {
48
+ const models = await entityManager.find(entity, conditions)
49
+ models.forEach(m => m.setEntityManager(entityManager))
50
+ return models
51
+ }
52
+
53
+ const models = await this.repository.find(conditions)
54
+ models.forEach(m => m.setRepository(this.repository))
55
+ return models
56
+ }
57
+
58
+ public async findOne(conditions: FindOneOptions<T>, entityManager?: EntityManager): Promise<T | null> {
59
+ if (entityManager) {
60
+ const model = await entityManager.findOne(entity, conditions)
61
+ if (model) {
62
+ model.setEntityManager(entityManager)
63
+ }
64
+ return model
65
+ }
66
+
67
+ const model = await this.repository.findOne(conditions)
68
+ if (model) {
69
+ model.setRepository(this.repository)
70
+ }
71
+ return model
72
+ }
73
+
74
+ public count(conditions: FindManyOptions<T>, entityManager?: EntityManager): Promise<number> {
75
+ if (entityManager) {
76
+ return entityManager.count(entity, conditions)
77
+ }
78
+
79
+ return this.repository.count(conditions)
80
+ }
81
+
82
+ public update(criteria: FindOptionsWhere<T>, props: QueryDeepPartialEntity<T>, entityManager?: EntityManager): Promise<UpdateResult> {
83
+ if (entityManager) {
84
+ return entityManager.update(entity, criteria, props)
85
+ }
86
+
87
+ return this.repository.update(criteria, props)
88
+ }
89
+
90
+ public remove(id: number, entityManager?: EntityManager): Promise<DeleteResult> {
91
+ if (entityManager) {
92
+ return entityManager.delete(entity, id)
93
+ }
94
+
95
+ return this.repository.delete(id)
96
+ }
97
+ }
98
+ return AbstractOrmServiceHost
99
+ }
@@ -0,0 +1,9 @@
1
+ import { registerAs } from '@nestjs/config'
2
+
3
+ export default registerAs('db', () => ({
4
+ host: process.env.DB_HOST,
5
+ port: process.env.DB_PORT,
6
+ user: process.env.DB_USER,
7
+ pass: process.env.DB_PASS,
8
+ name: process.env.DB_NAME,
9
+ }))
@@ -0,0 +1,5 @@
1
+ import DbConfig from './db.config'
2
+
3
+ export default [
4
+ DbConfig,
5
+ ]
@@ -0,0 +1,27 @@
1
+ import { Module } from '@nestjs/common'
2
+ import { ConfigModule, ConfigService } from '@nestjs/config'
3
+ import { TypeOrmModule } from '@nestjs/typeorm'
4
+ import config from './config'
5
+
6
+ @Module({
7
+ imports: [
8
+ ConfigModule.forRoot({
9
+ load: config,
10
+ }),
11
+
12
+ TypeOrmModule.forRootAsync({
13
+ useFactory: (configService: ConfigService) => ({
14
+ type: 'mysql',
15
+ host: configService.get('db.host'),
16
+ port: configService.get<number>('db.port'),
17
+ username: configService.get('db.user'),
18
+ password: configService.get('db.pass'),
19
+ database: configService.get('db.name'),
20
+ autoLoadEntities: true,
21
+ }),
22
+ imports: [ConfigModule],
23
+ inject: [ConfigService],
24
+ }),
25
+ ],
26
+ })
27
+ export class OrmModule {}
@@ -0,0 +1,9 @@
1
+ {
2
+ "moduleFileExtensions": ["js", "json", "ts"],
3
+ "rootDir": ".",
4
+ "testEnvironment": "node",
5
+ "testRegex": ".e2e-spec.ts$",
6
+ "transform": {
7
+ "^.+\\.(t|j)s$": "ts-jest"
8
+ }
9
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "extends": "./tsconfig.json",
3
+ "exclude": ["node_modules", "test", "dist", "**/*spec.ts"]
4
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "compilerOptions": {
3
+ "module": "commonjs",
4
+ "declaration": true,
5
+ "removeComments": true,
6
+ "emitDecoratorMetadata": true,
7
+ "experimentalDecorators": true,
8
+ "allowSyntheticDefaultImports": true,
9
+ "target": "ES2021",
10
+ "sourceMap": true,
11
+ "outDir": "./dist",
12
+ "baseUrl": "./",
13
+ "incremental": true,
14
+ "skipLibCheck": true,
15
+ "strictNullChecks": true,
16
+ "noImplicitAny": true,
17
+ "strictBindCallApply": true,
18
+ "forceConsistentCasingInFileNames": true,
19
+ "noFallthroughCasesInSwitch": true
20
+ }
21
+ }