@triproject/nestjs-core 1.0.6 → 1.0.13
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/.swcrc +24 -0
- package/dist/bootstrap.js +1 -43
- package/dist/config.js +1 -50
- package/dist/controllers/controller.js +1 -56
- package/dist/drivers/cache/cache.d.ts +1 -1
- package/dist/drivers/cache/cache.driver.js +1 -22
- package/dist/drivers/cache/cache.js +1 -92
- package/dist/drivers/cache/index.js +1 -19
- package/dist/drivers/cache/redis.js +1 -52
- package/dist/drivers/db/db.helper.js +1 -217
- package/dist/drivers/db/db.module.js +1 -44
- package/dist/drivers/db/db.service.js +1 -49
- package/dist/drivers/db/index.js +1 -21
- package/dist/drivers/db/migration.d.ts +133 -5
- package/dist/drivers/db/migration.js +1 -81
- package/dist/drivers/db/repository.js +1 -255
- package/dist/drivers/encryptions/encryption.js +1 -50
- package/dist/drivers/encryptions/encryption.module.js +1 -24
- package/dist/drivers/encryptions/index.js +1 -19
- package/dist/drivers/encryptions/jwt.js +1 -46
- package/dist/drivers/encryptions/password-hash.js +1 -38
- package/dist/drivers/encryptions/snap.signature.js +1 -110
- package/dist/drivers/logger/app.logger.js +2 -183
- package/dist/drivers/logger/cloudwatch.d.ts +18 -0
- package/dist/drivers/logger/cloudwatch.js +1 -0
- package/dist/drivers/logger/cloudwatch.logger.d.ts +1 -0
- package/dist/drivers/logger/cloudwatch.logger.js +1 -0
- package/dist/drivers/logger/index.js +1 -18
- package/dist/drivers/logger/slack.logger.js +1 -24
- package/dist/drivers/mail/index.js +1 -22
- package/dist/drivers/mail/mail-template.js +8 -41
- package/dist/drivers/mail/mail.config.js +1 -4
- package/dist/drivers/mail/mail.js +13 -73
- package/dist/drivers/mail/mail.module.js +1 -26
- package/dist/drivers/mail/mail.queue.js +1 -37
- package/dist/drivers/mail/mailer.js +1 -62
- package/dist/drivers/notifications/index.js +1 -21
- package/dist/drivers/notifications/notification.config.js +1 -4
- package/dist/drivers/notifications/notification.module.js +1 -25
- package/dist/drivers/notifications/notification.queue.js +1 -37
- package/dist/drivers/notifications/push-notification.js +1 -75
- package/dist/drivers/notifications/slack.js +1 -95
- package/dist/drivers/queues/app.queue.js +1 -66
- package/dist/drivers/queues/index.js +1 -18
- package/dist/drivers/queues/queue.module.js +1 -41
- package/dist/helpers/exception.helper.js +1 -71
- package/dist/helpers/http.helper.js +1 -134
- package/dist/helpers/swagger.helper.js +1 -287
- package/dist/helpers/totp.helper.js +1 -30
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -24
- package/dist/middlewares/log.middleware.js +1 -59
- package/dist/types.d.js +1 -0
- package/package.json +27 -14
|
@@ -1,44 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
-
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
-
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
-
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
-
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
-
};
|
|
8
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
9
|
-
exports.DBModule = void 0;
|
|
10
|
-
const common_1 = require("@nestjs/common");
|
|
11
|
-
const sequelize_1 = require("@nestjs/sequelize");
|
|
12
|
-
const path_1 = require("path");
|
|
13
|
-
const config_1 = require("../../config");
|
|
14
|
-
const db_service_1 = require("./db.service");
|
|
15
|
-
let DBModule = class DBModule {
|
|
16
|
-
};
|
|
17
|
-
exports.DBModule = DBModule;
|
|
18
|
-
exports.DBModule = DBModule = __decorate([
|
|
19
|
-
(0, common_1.Global)(),
|
|
20
|
-
(0, common_1.Module)({
|
|
21
|
-
imports: [
|
|
22
|
-
sequelize_1.SequelizeModule.forRootAsync({
|
|
23
|
-
useFactory: async () => {
|
|
24
|
-
return {
|
|
25
|
-
host: config_1.DB_HOST,
|
|
26
|
-
port: config_1.DB_PORT,
|
|
27
|
-
username: config_1.DB_USER,
|
|
28
|
-
password: config_1.DB_PASSWORD,
|
|
29
|
-
database: config_1.DB_NAME,
|
|
30
|
-
dialect: config_1.DB_DIALECT,
|
|
31
|
-
pool: { min: 2, max: config_1.DB_MAX_POOL_SIZE },
|
|
32
|
-
models: [(0, path_1.resolve)(config_1.DB_ENTITIES_PATH)],
|
|
33
|
-
define: { charset: 'utf8', underscored: false },
|
|
34
|
-
synchronize: false,
|
|
35
|
-
logging: false,
|
|
36
|
-
dialectOptions: config_1.DB_SSL ? { ssl: { require: true, rejectUnauthorized: false } } : {},
|
|
37
|
-
};
|
|
38
|
-
},
|
|
39
|
-
}),
|
|
40
|
-
],
|
|
41
|
-
providers: [sequelize_1.SequelizeModule, db_service_1.DbService],
|
|
42
|
-
exports: [sequelize_1.SequelizeModule, db_service_1.DbService],
|
|
43
|
-
})
|
|
44
|
-
], DBModule);
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"DBModule",{enumerable:!0,get:function(){return DBModule}});let _common=require("@nestjs/common"),_sequelize=require("@nestjs/sequelize"),_path=require("path"),_config=require("../../config"),_dbservice=require("./db.service");let DBModule=class DBModule{};DBModule=function(decorators,target,key,desc){var d,c=arguments.length,r=c<3?target:null===desc?desc=Object.getOwnPropertyDescriptor(target,key):desc;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r}([(0,_common.Global)(),(0,_common.Module)({imports:[_sequelize.SequelizeModule.forRootAsync({useFactory:async()=>({host:_config.DB_HOST,port:_config.DB_PORT,username:_config.DB_USER,password:_config.DB_PASSWORD,database:_config.DB_NAME,dialect:_config.DB_DIALECT,pool:{min:2,max:_config.DB_MAX_POOL_SIZE},models:[(0,_path.resolve)(_config.DB_ENTITIES_PATH)],define:{charset:"utf8",underscored:!1},synchronize:!1,logging:!1,dialectOptions:_config.DB_SSL?{ssl:{require:!0,rejectUnauthorized:!1}}:{}})})],providers:[_sequelize.SequelizeModule,_dbservice.DbService],exports:[_sequelize.SequelizeModule,_dbservice.DbService]})],DBModule);
|
|
@@ -1,49 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
-
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
-
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
-
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
-
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
-
};
|
|
8
|
-
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
-
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
-
};
|
|
11
|
-
var DbService_1;
|
|
12
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
-
exports.DbService = void 0;
|
|
14
|
-
const common_1 = require("@nestjs/common");
|
|
15
|
-
const sequelize_typescript_1 = require("sequelize-typescript");
|
|
16
|
-
const app_logger_1 = require("../../drivers/logger/app.logger");
|
|
17
|
-
let DbService = DbService_1 = class DbService {
|
|
18
|
-
db;
|
|
19
|
-
logger = new app_logger_1.AppLogger(DbService_1.name);
|
|
20
|
-
constructor(db) {
|
|
21
|
-
this.db = db;
|
|
22
|
-
}
|
|
23
|
-
async onModuleInit() {
|
|
24
|
-
await this.authenticate();
|
|
25
|
-
}
|
|
26
|
-
async authenticate() {
|
|
27
|
-
await this.db
|
|
28
|
-
.authenticate({ retry: { max: 1 } })
|
|
29
|
-
.then(() => this.logger.log('Database connection has been established successfully.'))
|
|
30
|
-
.catch((err) => {
|
|
31
|
-
this.logger.error('Unable to connect to the database:', err);
|
|
32
|
-
throw err;
|
|
33
|
-
});
|
|
34
|
-
}
|
|
35
|
-
async checkConnection() {
|
|
36
|
-
return await this.db
|
|
37
|
-
.authenticate({ retry: { max: 1 } })
|
|
38
|
-
.then(() => true)
|
|
39
|
-
.catch((err) => {
|
|
40
|
-
this.logger.error('Database connection failed', err);
|
|
41
|
-
return false;
|
|
42
|
-
});
|
|
43
|
-
}
|
|
44
|
-
};
|
|
45
|
-
exports.DbService = DbService;
|
|
46
|
-
exports.DbService = DbService = DbService_1 = __decorate([
|
|
47
|
-
(0, common_1.Injectable)(),
|
|
48
|
-
__metadata("design:paramtypes", [sequelize_typescript_1.Sequelize])
|
|
49
|
-
], DbService);
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"DbService",{enumerable:!0,get:function(){return DbService}});let _common=require("@nestjs/common"),_sequelizetypescript=require("sequelize-typescript"),_config=require("../../config"),_applogger=require("../../drivers/logger/app.logger");function _ts_metadata(k,v){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(k,v)}let DbService=class DbService{db;logger=new _applogger.AppLogger(DbService.name);constructor(db){this.db=db}async onModuleInit(){await this.authenticate()}async authenticate(){await this.db.authenticate({retry:{max:1}}).then(()=>this.logger.log(`Database connected successfully to ${_config.DB_NAME}:${_config.DB_DIALECT}`)).catch(err=>{throw this.logger.error("Unable to connect to the database:",err),err})}async checkConnection(){return await this.db.authenticate({retry:{max:1}}).then(()=>!0).catch(err=>(this.logger.error("Database connection failed",err),!1))}};DbService=function(decorators,target,key,desc){var d,c=arguments.length,r=c<3?target:null===desc?desc=Object.getOwnPropertyDescriptor(target,key):desc;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);return c>3&&r&&Object.defineProperty(target,key,r),r}([(0,_common.Injectable)(),_ts_metadata("design:type",Function),_ts_metadata("design:paramtypes",[void 0===_sequelizetypescript.Sequelize?Object:_sequelizetypescript.Sequelize])],DbService);
|
package/dist/drivers/db/index.js
CHANGED
|
@@ -1,21 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
-
if (k2 === undefined) k2 = k;
|
|
4
|
-
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
-
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
-
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
-
}
|
|
8
|
-
Object.defineProperty(o, k2, desc);
|
|
9
|
-
}) : (function(o, m, k, k2) {
|
|
10
|
-
if (k2 === undefined) k2 = k;
|
|
11
|
-
o[k2] = m[k];
|
|
12
|
-
}));
|
|
13
|
-
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
-
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
-
};
|
|
16
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
-
__exportStar(require("./db.helper"), exports);
|
|
18
|
-
__exportStar(require("./db.module"), exports);
|
|
19
|
-
__exportStar(require("./db.service"), exports);
|
|
20
|
-
__exportStar(require("./migration"), exports);
|
|
21
|
-
__exportStar(require("./repository"), exports);
|
|
1
|
+
"use strict";function _export_star(from,to){return Object.keys(from).forEach(function(k){"default"===k||Object.prototype.hasOwnProperty.call(to,k)||Object.defineProperty(to,k,{enumerable:!0,get:function(){return from[k]}})}),from}Object.defineProperty(exports,"__esModule",{value:!0}),_export_star(require("./db.helper"),exports),_export_star(require("./db.module"),exports),_export_star(require("./db.service"),exports),_export_star(require("./migration"),exports),_export_star(require("./repository"),exports);
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { QueryInterface, QueryInterfaceIndexOptions, StringDataType } from 'sequelize';
|
|
2
|
-
import { SequelizeOptions } from 'sequelize-typescript';
|
|
3
2
|
type Index = {
|
|
4
3
|
queryInterface: QueryInterface;
|
|
5
4
|
tableName: string;
|
|
@@ -33,10 +32,139 @@ export declare const addIndexes: (params: Index) => Promise<void>;
|
|
|
33
32
|
export declare const deleteIndexes: (params: Index) => Promise<void>;
|
|
34
33
|
export declare const addUniqueIndexes: (params: Index) => Promise<void>;
|
|
35
34
|
export declare const deleteUniqueIndexes: (params: Index) => Promise<void>;
|
|
36
|
-
export declare const migrationConfig: {
|
|
37
|
-
development:
|
|
38
|
-
|
|
35
|
+
export declare const migrationConfig: (migrationTableName: string) => {
|
|
36
|
+
development: {
|
|
37
|
+
migrationStorageTableName: string;
|
|
38
|
+
models?: string[] | import("sequelize-typescript").ModelCtor[];
|
|
39
|
+
modelPaths?: string[];
|
|
40
|
+
modelMatch?: import("sequelize-typescript").ModelMatch;
|
|
41
|
+
repositoryMode?: boolean;
|
|
42
|
+
validateOnly?: boolean;
|
|
43
|
+
dialect?: import("sequelize").Dialect;
|
|
44
|
+
dialectModule?: object;
|
|
45
|
+
dialectModulePath?: string;
|
|
46
|
+
dialectOptions?: object;
|
|
47
|
+
storage?: string;
|
|
48
|
+
database?: string;
|
|
49
|
+
username?: string;
|
|
50
|
+
password?: string;
|
|
51
|
+
host?: string;
|
|
52
|
+
port?: number;
|
|
53
|
+
ssl?: boolean;
|
|
54
|
+
protocol?: string;
|
|
55
|
+
define?: import("sequelize").ModelOptions;
|
|
56
|
+
query?: import("sequelize").QueryOptions;
|
|
57
|
+
set?: import("sequelize").DefaultSetOptions;
|
|
58
|
+
sync?: import("sequelize").SyncOptions;
|
|
59
|
+
timezone?: string;
|
|
60
|
+
omitNull?: boolean;
|
|
61
|
+
native?: boolean;
|
|
62
|
+
replication?: import("sequelize").ReplicationOptions | false;
|
|
63
|
+
pool?: import("sequelize").PoolOptions;
|
|
64
|
+
quoteIdentifiers?: boolean;
|
|
65
|
+
isolationLevel?: string;
|
|
66
|
+
transactionType?: import("sequelize").Transaction.TYPES;
|
|
67
|
+
typeValidation?: boolean;
|
|
68
|
+
operatorsAliases?: import("sequelize").OperatorsAliases;
|
|
69
|
+
standardConformingStrings?: boolean;
|
|
70
|
+
clientMinMessages?: string | boolean;
|
|
71
|
+
hooks?: Partial<import("sequelize/types/hooks").SequelizeHooks<import("sequelize").Model, any, any>>;
|
|
72
|
+
minifyAliases?: boolean;
|
|
73
|
+
logQueryParameters?: boolean;
|
|
74
|
+
retry?: import("sequelize").RetryOptions;
|
|
75
|
+
schema?: string;
|
|
76
|
+
attributeBehavior?: "escape" | "throw" | "unsafe-legacy";
|
|
77
|
+
logging?: boolean | ((sql: string, timing?: number) => void);
|
|
78
|
+
benchmark?: boolean;
|
|
79
|
+
};
|
|
80
|
+
staging: {
|
|
81
|
+
migrationStorageTableName: string;
|
|
82
|
+
models?: string[] | import("sequelize-typescript").ModelCtor[];
|
|
83
|
+
modelPaths?: string[];
|
|
84
|
+
modelMatch?: import("sequelize-typescript").ModelMatch;
|
|
85
|
+
repositoryMode?: boolean;
|
|
86
|
+
validateOnly?: boolean;
|
|
87
|
+
dialect?: import("sequelize").Dialect;
|
|
88
|
+
dialectModule?: object;
|
|
89
|
+
dialectModulePath?: string;
|
|
90
|
+
dialectOptions?: object;
|
|
91
|
+
storage?: string;
|
|
92
|
+
database?: string;
|
|
93
|
+
username?: string;
|
|
94
|
+
password?: string;
|
|
95
|
+
host?: string;
|
|
96
|
+
port?: number;
|
|
97
|
+
ssl?: boolean;
|
|
98
|
+
protocol?: string;
|
|
99
|
+
define?: import("sequelize").ModelOptions;
|
|
100
|
+
query?: import("sequelize").QueryOptions;
|
|
101
|
+
set?: import("sequelize").DefaultSetOptions;
|
|
102
|
+
sync?: import("sequelize").SyncOptions;
|
|
103
|
+
timezone?: string;
|
|
104
|
+
omitNull?: boolean;
|
|
105
|
+
native?: boolean;
|
|
106
|
+
replication?: import("sequelize").ReplicationOptions | false;
|
|
107
|
+
pool?: import("sequelize").PoolOptions;
|
|
108
|
+
quoteIdentifiers?: boolean;
|
|
109
|
+
isolationLevel?: string;
|
|
110
|
+
transactionType?: import("sequelize").Transaction.TYPES;
|
|
111
|
+
typeValidation?: boolean;
|
|
112
|
+
operatorsAliases?: import("sequelize").OperatorsAliases;
|
|
113
|
+
standardConformingStrings?: boolean;
|
|
114
|
+
clientMinMessages?: string | boolean;
|
|
115
|
+
hooks?: Partial<import("sequelize/types/hooks").SequelizeHooks<import("sequelize").Model, any, any>>;
|
|
116
|
+
minifyAliases?: boolean;
|
|
117
|
+
logQueryParameters?: boolean;
|
|
118
|
+
retry?: import("sequelize").RetryOptions;
|
|
119
|
+
schema?: string;
|
|
120
|
+
attributeBehavior?: "escape" | "throw" | "unsafe-legacy";
|
|
121
|
+
logging?: boolean | ((sql: string, timing?: number) => void);
|
|
122
|
+
benchmark?: boolean;
|
|
123
|
+
};
|
|
39
124
|
test: {};
|
|
40
|
-
production:
|
|
125
|
+
production: {
|
|
126
|
+
migrationStorageTableName: string;
|
|
127
|
+
models?: string[] | import("sequelize-typescript").ModelCtor[];
|
|
128
|
+
modelPaths?: string[];
|
|
129
|
+
modelMatch?: import("sequelize-typescript").ModelMatch;
|
|
130
|
+
repositoryMode?: boolean;
|
|
131
|
+
validateOnly?: boolean;
|
|
132
|
+
dialect?: import("sequelize").Dialect;
|
|
133
|
+
dialectModule?: object;
|
|
134
|
+
dialectModulePath?: string;
|
|
135
|
+
dialectOptions?: object;
|
|
136
|
+
storage?: string;
|
|
137
|
+
database?: string;
|
|
138
|
+
username?: string;
|
|
139
|
+
password?: string;
|
|
140
|
+
host?: string;
|
|
141
|
+
port?: number;
|
|
142
|
+
ssl?: boolean;
|
|
143
|
+
protocol?: string;
|
|
144
|
+
define?: import("sequelize").ModelOptions;
|
|
145
|
+
query?: import("sequelize").QueryOptions;
|
|
146
|
+
set?: import("sequelize").DefaultSetOptions;
|
|
147
|
+
sync?: import("sequelize").SyncOptions;
|
|
148
|
+
timezone?: string;
|
|
149
|
+
omitNull?: boolean;
|
|
150
|
+
native?: boolean;
|
|
151
|
+
replication?: import("sequelize").ReplicationOptions | false;
|
|
152
|
+
pool?: import("sequelize").PoolOptions;
|
|
153
|
+
quoteIdentifiers?: boolean;
|
|
154
|
+
isolationLevel?: string;
|
|
155
|
+
transactionType?: import("sequelize").Transaction.TYPES;
|
|
156
|
+
typeValidation?: boolean;
|
|
157
|
+
operatorsAliases?: import("sequelize").OperatorsAliases;
|
|
158
|
+
standardConformingStrings?: boolean;
|
|
159
|
+
clientMinMessages?: string | boolean;
|
|
160
|
+
hooks?: Partial<import("sequelize/types/hooks").SequelizeHooks<import("sequelize").Model, any, any>>;
|
|
161
|
+
minifyAliases?: boolean;
|
|
162
|
+
logQueryParameters?: boolean;
|
|
163
|
+
retry?: import("sequelize").RetryOptions;
|
|
164
|
+
schema?: string;
|
|
165
|
+
attributeBehavior?: "escape" | "throw" | "unsafe-legacy";
|
|
166
|
+
logging?: boolean | ((sql: string, timing?: number) => void);
|
|
167
|
+
benchmark?: boolean;
|
|
168
|
+
};
|
|
41
169
|
};
|
|
42
170
|
export {};
|
|
@@ -1,81 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.migrationConfig = exports.deleteUniqueIndexes = exports.addUniqueIndexes = exports.deleteIndexes = exports.addIndexes = exports.relationCols = exports.defaultCols = void 0;
|
|
4
|
-
const helpers_1 = require("@triproject/helpers");
|
|
5
|
-
const sequelize_1 = require("sequelize");
|
|
6
|
-
const config_1 = require("../../config");
|
|
7
|
-
const defaultCols = () => ({
|
|
8
|
-
id: { type: (0, sequelize_1.STRING)(32), primaryKey: true, autoIncrement: false, defaultValue: () => (0, helpers_1.generateId)() },
|
|
9
|
-
createdAt: { type: sequelize_1.DATE, defaultValue: (0, sequelize_1.fn)('now') },
|
|
10
|
-
updatedAt: { type: sequelize_1.DATE, defaultValue: (0, sequelize_1.fn)('now') },
|
|
11
|
-
});
|
|
12
|
-
exports.defaultCols = defaultCols;
|
|
13
|
-
const relationCols = (...args) => ({
|
|
14
|
-
id: { type: sequelize_1.BIGINT, primaryKey: true, autoIncrement: true },
|
|
15
|
-
...args.reduce((acc, curr) => {
|
|
16
|
-
acc[curr] = { type: (0, sequelize_1.STRING)(32), allowNull: false };
|
|
17
|
-
return acc;
|
|
18
|
-
}, {}),
|
|
19
|
-
});
|
|
20
|
-
exports.relationCols = relationCols;
|
|
21
|
-
const index = (tableName, column) => {
|
|
22
|
-
return [tableName, (0, helpers_1.md5)(Array.isArray(column) ? column.sort().join('_') : column).substring(0, 8), 'idx'].join('_');
|
|
23
|
-
};
|
|
24
|
-
const addIndexes = async (params) => {
|
|
25
|
-
const { tableName, columns, options = {}, queryInterface } = params;
|
|
26
|
-
for (const col of columns) {
|
|
27
|
-
await queryInterface.addIndex(tableName, [col], { name: index(tableName, col), ...options });
|
|
28
|
-
}
|
|
29
|
-
};
|
|
30
|
-
exports.addIndexes = addIndexes;
|
|
31
|
-
const deleteIndexes = async (params) => {
|
|
32
|
-
const { tableName, columns, queryInterface } = params;
|
|
33
|
-
for (const col of columns) {
|
|
34
|
-
await queryInterface.removeIndex(tableName, index(tableName, col));
|
|
35
|
-
}
|
|
36
|
-
};
|
|
37
|
-
exports.deleteIndexes = deleteIndexes;
|
|
38
|
-
const addUniqueIndexes = async (params) => {
|
|
39
|
-
const { tableName, columns, options = {}, queryInterface } = params;
|
|
40
|
-
queryInterface.addIndex(tableName, columns, {
|
|
41
|
-
unique: true,
|
|
42
|
-
name: index(tableName, columns),
|
|
43
|
-
...options,
|
|
44
|
-
});
|
|
45
|
-
};
|
|
46
|
-
exports.addUniqueIndexes = addUniqueIndexes;
|
|
47
|
-
const deleteUniqueIndexes = async (params) => {
|
|
48
|
-
const { tableName, columns, queryInterface } = params;
|
|
49
|
-
await queryInterface.removeIndex(tableName, index(tableName, columns));
|
|
50
|
-
};
|
|
51
|
-
exports.deleteUniqueIndexes = deleteUniqueIndexes;
|
|
52
|
-
const dialect = config_1.DB_DIALECT ?? 'postgres';
|
|
53
|
-
const common = {
|
|
54
|
-
host: config_1.DB_HOST ?? '127.0.0.1',
|
|
55
|
-
port: +(config_1.DB_PORT ?? 5432),
|
|
56
|
-
username: config_1.DB_USER ?? 'postgres',
|
|
57
|
-
database: config_1.DB_NAME ?? 'app_db',
|
|
58
|
-
password: config_1.DB_PASSWORD ?? '',
|
|
59
|
-
dialect,
|
|
60
|
-
logging: false,
|
|
61
|
-
pool: {
|
|
62
|
-
max: config_1.DB_MAX_POOL_SIZE ?? 10,
|
|
63
|
-
min: config_1.DB_POOL_MIN ?? 0,
|
|
64
|
-
acquire: config_1.DB_POOL_ACQUIRE ?? 30000,
|
|
65
|
-
idle: config_1.DB_POOL_IDLE ?? 10000,
|
|
66
|
-
},
|
|
67
|
-
dialectOptions: config_1.DB_SSL
|
|
68
|
-
? {
|
|
69
|
-
ssl: {
|
|
70
|
-
require: true,
|
|
71
|
-
rejectUnauthorized: true,
|
|
72
|
-
},
|
|
73
|
-
}
|
|
74
|
-
: {},
|
|
75
|
-
};
|
|
76
|
-
exports.migrationConfig = {
|
|
77
|
-
development: common,
|
|
78
|
-
staging: common,
|
|
79
|
-
test: {},
|
|
80
|
-
production: common,
|
|
81
|
-
};
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var target=exports,all={get addIndexes(){return addIndexes},get addUniqueIndexes(){return addUniqueIndexes},get defaultCols(){return defaultCols},get deleteIndexes(){return deleteIndexes},get deleteUniqueIndexes(){return deleteUniqueIndexes},get migrationConfig(){return migrationConfig},get relationCols(){return relationCols}};for(var name in all)Object.defineProperty(target,name,{enumerable:!0,get:Object.getOwnPropertyDescriptor(all,name).get});let _helpers=require("@triproject/helpers"),_sequelize=require("sequelize"),_config=require("../../config"),defaultCols=()=>({id:{type:(0,_sequelize.STRING)(36),primaryKey:!0,autoIncrement:!1,defaultValue:()=>(0,_helpers.generateId)()},createdAt:{type:_sequelize.DATE,defaultValue:(0,_sequelize.fn)("now")},updatedAt:{type:_sequelize.DATE,defaultValue:(0,_sequelize.fn)("now")}}),relationCols=(...args)=>({id:{type:_sequelize.BIGINT,primaryKey:!0,autoIncrement:!0},...args.reduce((acc,curr)=>(acc[curr]={type:(0,_sequelize.STRING)(36),allowNull:!1},acc),{})}),index=(tableName,column)=>[tableName,(0,_helpers.md5)(Array.isArray(column)?column.sort().join("_"):column).substring(0,8),"idx"].join("_"),addIndexes=async params=>{let{tableName,columns,options={},queryInterface}=params;for(let col of columns)await queryInterface.addIndex(tableName,[col],{name:index(tableName,col),...options})},deleteIndexes=async params=>{let{tableName,columns,queryInterface}=params;for(let col of columns)await queryInterface.removeIndex(tableName,index(tableName,col))},addUniqueIndexes=async params=>{let{tableName,columns,options={},queryInterface}=params;queryInterface.addIndex(tableName,columns,{unique:!0,name:index(tableName,columns),...options})},deleteUniqueIndexes=async params=>{let{tableName,columns,queryInterface}=params;await queryInterface.removeIndex(tableName,index(tableName,columns))},dialect=_config.DB_DIALECT??"postgres",common={host:_config.DB_HOST??"127.0.0.1",port:+(_config.DB_PORT??5432),username:_config.DB_USER??"postgres",database:_config.DB_NAME??"app_db",password:_config.DB_PASSWORD??"",dialect,logging:!1,pool:{max:_config.DB_MAX_POOL_SIZE??10,min:_config.DB_POOL_MIN??0,acquire:_config.DB_POOL_ACQUIRE??3e4,idle:_config.DB_POOL_IDLE??1e4},dialectOptions:_config.DB_SSL?{ssl:{require:!0,rejectUnauthorized:!0}}:{}},migrationConfig=migrationTableName=>({development:{...common,migrationStorageTableName:migrationTableName},staging:{...common,migrationStorageTableName:migrationTableName},test:{},production:{...common,migrationStorageTableName:migrationTableName}});
|
|
@@ -1,255 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
-
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
-
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
-
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
-
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
-
};
|
|
8
|
-
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
-
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
-
};
|
|
11
|
-
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
12
|
-
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
13
|
-
};
|
|
14
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
-
exports.Repository = void 0;
|
|
16
|
-
const common_1 = require("@nestjs/common");
|
|
17
|
-
const helpers_1 = require("@triproject/helpers");
|
|
18
|
-
const moment_1 = __importDefault(require("moment"));
|
|
19
|
-
const sequelize_1 = require("sequelize");
|
|
20
|
-
const sequelize_typescript_1 = require("sequelize-typescript");
|
|
21
|
-
const logger_1 = require("../logger");
|
|
22
|
-
class Repository {
|
|
23
|
-
logger = new logger_1.AppLogger(this.constructor.name);
|
|
24
|
-
Model;
|
|
25
|
-
db;
|
|
26
|
-
excludeParamsFromFilter = [
|
|
27
|
-
'attributes',
|
|
28
|
-
'include',
|
|
29
|
-
'where',
|
|
30
|
-
'orWhere',
|
|
31
|
-
'andWhere',
|
|
32
|
-
'q',
|
|
33
|
-
'searchKey',
|
|
34
|
-
'page',
|
|
35
|
-
'perPage',
|
|
36
|
-
'orderBy',
|
|
37
|
-
'sort',
|
|
38
|
-
'groupBy',
|
|
39
|
-
'order',
|
|
40
|
-
];
|
|
41
|
-
get attributes() {
|
|
42
|
-
return Object.keys(this.Model.getAttributes());
|
|
43
|
-
}
|
|
44
|
-
get attributesTypes() {
|
|
45
|
-
const attributes = this.Model.getAttributes();
|
|
46
|
-
return Object.keys(attributes).map((attr) => ({
|
|
47
|
-
name: attr,
|
|
48
|
-
type: attributes[attr].type,
|
|
49
|
-
}));
|
|
50
|
-
}
|
|
51
|
-
getTrueKey(key) {
|
|
52
|
-
return key.replace('min_', '').replace('max_', '').replace('start_', '').replace('end_', '');
|
|
53
|
-
}
|
|
54
|
-
parsedBetweenData(where, key, value) {
|
|
55
|
-
const col = this.getTrueKey(key);
|
|
56
|
-
const operation = key.startsWith('start_') || key.startsWith('min_') ? 'gte' : 'lte';
|
|
57
|
-
value =
|
|
58
|
-
key.startsWith('_start') || key.startsWith('end_') ? (0, moment_1.default)(value).utc().format('YYYY-MM-DD HH:mm:ss') : value;
|
|
59
|
-
// @ts-ignore
|
|
60
|
-
if (typeof where[col] === 'undefined')
|
|
61
|
-
return { [sequelize_1.Op[operation]]: value };
|
|
62
|
-
// @ts-ignore
|
|
63
|
-
let beforeValue = where[col][sequelize_1.Op[operation == 'gte' ? 'lte' : 'gte']];
|
|
64
|
-
beforeValue =
|
|
65
|
-
key.startsWith('_start') || key.startsWith('end_')
|
|
66
|
-
? (0, moment_1.default)(beforeValue).utc().format('YYYY-MM-DD HH:mm:ss')
|
|
67
|
-
: beforeValue;
|
|
68
|
-
return {
|
|
69
|
-
[sequelize_1.Op.between]: operation === 'gte' ? [value, beforeValue] : [beforeValue, value],
|
|
70
|
-
};
|
|
71
|
-
}
|
|
72
|
-
mapFilter(filter, cols) {
|
|
73
|
-
const where = {};
|
|
74
|
-
for (const key of Object.keys(filter)) {
|
|
75
|
-
const isSpecialKey = key.includes('$') || key.includes('.');
|
|
76
|
-
if (!cols.includes(this.getTrueKey(key)) && !isSpecialKey)
|
|
77
|
-
continue;
|
|
78
|
-
const value = filter[key];
|
|
79
|
-
const col = this.getTrueKey(key);
|
|
80
|
-
if (value === undefined || value === '')
|
|
81
|
-
continue;
|
|
82
|
-
if (key.startsWith('min_') || key.startsWith('start_') || key.startsWith('max_') || key.startsWith('end_')) {
|
|
83
|
-
// @ts-ignore
|
|
84
|
-
where[col] = this.parsedBetweenData(where, key, value);
|
|
85
|
-
continue;
|
|
86
|
-
}
|
|
87
|
-
if (typeof value === 'string' && value.includes(',')) {
|
|
88
|
-
// @ts-ignore
|
|
89
|
-
where[col] = value.split(',');
|
|
90
|
-
continue;
|
|
91
|
-
}
|
|
92
|
-
if (typeof value === 'object' && !Array.isArray(value)) {
|
|
93
|
-
// @ts-ignore
|
|
94
|
-
where[col] = { ...value };
|
|
95
|
-
continue;
|
|
96
|
-
}
|
|
97
|
-
// @ts-ignore
|
|
98
|
-
where[col] = value;
|
|
99
|
-
}
|
|
100
|
-
return where;
|
|
101
|
-
}
|
|
102
|
-
_getOptions(params) {
|
|
103
|
-
const fields = this.attributes;
|
|
104
|
-
let where = this.mapFilter({ ...params.where, ...(0, helpers_1.omit)(params, this.excludeParamsFromFilter) }, fields);
|
|
105
|
-
if (params.q && params.searchKey) {
|
|
106
|
-
const searchConditions = Array.isArray(params.searchKey)
|
|
107
|
-
? params.searchKey.map((key) => ({
|
|
108
|
-
[key]: { [sequelize_1.Op.like]: `%${params.q}%` },
|
|
109
|
-
}))
|
|
110
|
-
: [{ [params.searchKey]: { [sequelize_1.Op.like]: `%${params.q}%` } }];
|
|
111
|
-
where = {
|
|
112
|
-
...where,
|
|
113
|
-
[sequelize_1.Op.and]: [...(params.andWhere || []), { [sequelize_1.Op.or]: [...searchConditions, ...(params.orWhere || [])] }],
|
|
114
|
-
};
|
|
115
|
-
}
|
|
116
|
-
if (params.orWhere || params.andWhere) {
|
|
117
|
-
where = {
|
|
118
|
-
...where,
|
|
119
|
-
[sequelize_1.Op.and]: [...(params.andWhere || []), { [sequelize_1.Op.or]: params.orWhere || [] }],
|
|
120
|
-
};
|
|
121
|
-
}
|
|
122
|
-
const order = [];
|
|
123
|
-
if (params?.orderBy && fields.includes(params?.orderBy)) {
|
|
124
|
-
order.push([params?.orderBy, params?.sort ?? 'DESC']);
|
|
125
|
-
}
|
|
126
|
-
if (params?.order)
|
|
127
|
-
order.push(...params.order, ['id', 'ASC']);
|
|
128
|
-
const attributes = params.attributes
|
|
129
|
-
? params.attributes.filter((d) => (typeof d === 'string' ? fields.includes(d) : true))
|
|
130
|
-
: undefined;
|
|
131
|
-
return {
|
|
132
|
-
where,
|
|
133
|
-
order,
|
|
134
|
-
group: params?.groupBy,
|
|
135
|
-
...(attributes && { attributes }),
|
|
136
|
-
include: params.include,
|
|
137
|
-
};
|
|
138
|
-
}
|
|
139
|
-
async findForPublic(params, mapInto) {
|
|
140
|
-
const options = this._getOptions(params);
|
|
141
|
-
const limit = +(params?.perPage ?? 20);
|
|
142
|
-
const data = await this.findAll({ ...options, limit });
|
|
143
|
-
return data.map((d) => mapInto(d));
|
|
144
|
-
}
|
|
145
|
-
async paginate(params, mapInto) {
|
|
146
|
-
const options = this._getOptions(params);
|
|
147
|
-
const limit = +(params?.perPage ?? 20);
|
|
148
|
-
const page = +(params?.page ?? 1);
|
|
149
|
-
const offset = page > 1 ? limit * (page - 1) : 0;
|
|
150
|
-
const data = await this.findAndCountAll({
|
|
151
|
-
limit,
|
|
152
|
-
offset,
|
|
153
|
-
...options,
|
|
154
|
-
distinct: true,
|
|
155
|
-
});
|
|
156
|
-
data.count = Array.isArray(data.count) ? data.count.length : data.count;
|
|
157
|
-
const totalPage = Math.ceil(data.count / limit);
|
|
158
|
-
return {
|
|
159
|
-
data: mapInto ? data.rows.map((d) => mapInto(d)) : data.rows,
|
|
160
|
-
timestamp: (0, moment_1.default)().utc().toISOString(true),
|
|
161
|
-
meta: {
|
|
162
|
-
perPage: limit,
|
|
163
|
-
page: page,
|
|
164
|
-
totalPage: totalPage,
|
|
165
|
-
total: data.count,
|
|
166
|
-
prevPage: page > 1 ? page - 1 : null,
|
|
167
|
-
nextPage: page < totalPage ? page + 1 : null,
|
|
168
|
-
},
|
|
169
|
-
};
|
|
170
|
-
}
|
|
171
|
-
async export(params, mapInto) {
|
|
172
|
-
const options = this._getOptions(params);
|
|
173
|
-
const data = await this.findAll(options);
|
|
174
|
-
if (!mapInto)
|
|
175
|
-
return data;
|
|
176
|
-
return data.map((d) => mapInto(d));
|
|
177
|
-
}
|
|
178
|
-
async updateOrCreate(values, whereOptions, options) {
|
|
179
|
-
const data = await this.findOne({ where: whereOptions });
|
|
180
|
-
if (!data) {
|
|
181
|
-
return await this.create(values, options);
|
|
182
|
-
}
|
|
183
|
-
await this.update(data, values, options);
|
|
184
|
-
return data;
|
|
185
|
-
}
|
|
186
|
-
async findAll(options) {
|
|
187
|
-
return await this.Model.findAll(options);
|
|
188
|
-
}
|
|
189
|
-
async findAndCountAll(options) {
|
|
190
|
-
return await this.Model.findAndCountAll(options);
|
|
191
|
-
}
|
|
192
|
-
async findOne(options) {
|
|
193
|
-
return await this.Model.findOne(options);
|
|
194
|
-
}
|
|
195
|
-
async create(values, options) {
|
|
196
|
-
return await this.Model.create(values, options);
|
|
197
|
-
}
|
|
198
|
-
async update(entity, values, options) {
|
|
199
|
-
// @ts-ignore
|
|
200
|
-
if (typeof entity === 'string')
|
|
201
|
-
entity = (await this.findOne({ where: { id: entity }, attributes: ['id'] }));
|
|
202
|
-
if (!entity)
|
|
203
|
-
throw new common_1.NotFoundException();
|
|
204
|
-
return await entity.update(values, { ...options });
|
|
205
|
-
}
|
|
206
|
-
async upsert(values, options) {
|
|
207
|
-
return await this.Model.upsert(values, { ...options });
|
|
208
|
-
}
|
|
209
|
-
async bulkUpdate(values, options) {
|
|
210
|
-
return await this.Model.update(values, { ...options });
|
|
211
|
-
}
|
|
212
|
-
async bulkCreate(values, options) {
|
|
213
|
-
const idAttribute = this.attributesTypes.find((attr) => attr.name === 'id');
|
|
214
|
-
if (idAttribute && idAttribute.type !== 'BIGINT') {
|
|
215
|
-
values = values.map((val) => {
|
|
216
|
-
// @ts-ignore
|
|
217
|
-
if (!val['id'])
|
|
218
|
-
val['id'] = generateId();
|
|
219
|
-
return val;
|
|
220
|
-
});
|
|
221
|
-
}
|
|
222
|
-
return await this.Model.bulkCreate(values, options);
|
|
223
|
-
}
|
|
224
|
-
async destroy(options) {
|
|
225
|
-
return await this.Model.destroy(options);
|
|
226
|
-
}
|
|
227
|
-
async sum(field, options) {
|
|
228
|
-
return await this.Model.sum(field, options);
|
|
229
|
-
}
|
|
230
|
-
async sumField(params, field) {
|
|
231
|
-
const options = this._getOptions(params);
|
|
232
|
-
return await this.sum(field, options);
|
|
233
|
-
}
|
|
234
|
-
async sumCol(params, fieldToSum, expectedField) {
|
|
235
|
-
const options = this._getOptions(params);
|
|
236
|
-
options.attributes = [[(0, sequelize_1.fn)('sum', (0, sequelize_1.col)(fieldToSum)), expectedField]];
|
|
237
|
-
const result = await this.Model.findAll(options);
|
|
238
|
-
return result.reduce((total, row) => {
|
|
239
|
-
const value = row.get(expectedField);
|
|
240
|
-
return total + parseFloat(String(value) || '0');
|
|
241
|
-
}, 0);
|
|
242
|
-
}
|
|
243
|
-
async count(options) {
|
|
244
|
-
return await this.Model.count(options);
|
|
245
|
-
}
|
|
246
|
-
async filteredFindAll(params) {
|
|
247
|
-
const options = this._getOptions(params);
|
|
248
|
-
return await this.Model.findAll(options);
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
exports.Repository = Repository;
|
|
252
|
-
__decorate([
|
|
253
|
-
(0, common_1.Inject)(sequelize_typescript_1.Sequelize),
|
|
254
|
-
__metadata("design:type", sequelize_typescript_1.Sequelize)
|
|
255
|
-
], Repository.prototype, "db", void 0);
|
|
1
|
+
"use strict";var obj;Object.defineProperty(exports,"__esModule",{value:!0}),Object.defineProperty(exports,"Repository",{enumerable:!0,get:function(){return Repository}});let _common=require("@nestjs/common"),_helpers=require("@triproject/helpers"),_moment=(obj=require("moment"))&&obj.__esModule?obj:{default:obj},_sequelize=require("sequelize"),_sequelizetypescript=require("sequelize-typescript"),_logger=require("../logger");let Repository=class Repository{logger=new _logger.AppLogger(this.constructor.name);Model;db;excludeParamsFromFilter=["attributes","include","where","orWhere","andWhere","q","searchKey","page","perPage","orderBy","sort","groupBy","order"];get attributes(){return Object.keys(this.Model.getAttributes())}get attributesTypes(){let attributes=this.Model.getAttributes();return Object.keys(attributes).map(attr=>({name:attr,type:attributes[attr].type}))}getTrueKey(key){return key.replace("min_","").replace("max_","").replace("start_","").replace("end_","")}parsedBetweenData(where,key,value){let col=this.getTrueKey(key),operation=key.startsWith("start_")||key.startsWith("min_")?"gte":"lte";if(value=key.startsWith("_start")||key.startsWith("end_")?(0,_moment.default)(value).utc().format("YYYY-MM-DD HH:mm:ss"):value,void 0===where[col])return{[_sequelize.Op[operation]]:value};let beforeValue=where[col][_sequelize.Op["gte"==operation?"lte":"gte"]];return beforeValue=key.startsWith("_start")||key.startsWith("end_")?(0,_moment.default)(beforeValue).utc().format("YYYY-MM-DD HH:mm:ss"):beforeValue,{[_sequelize.Op.between]:"gte"===operation?[value,beforeValue]:[beforeValue,value]}}mapFilter(filter,cols){let where={};for(let key of Object.keys(filter)){let isSpecialKey=key.includes("$")||key.includes(".");if(!cols.includes(this.getTrueKey(key))&&!isSpecialKey)continue;let value=filter[key],col=this.getTrueKey(key);if(void 0!==value&&""!==value){if(key.startsWith("min_")||key.startsWith("start_")||key.startsWith("max_")||key.startsWith("end_")){where[col]=this.parsedBetweenData(where,key,value);continue}if("string"==typeof value&&value.includes(",")){where[col]=value.split(",");continue}if("object"==typeof value&&!Array.isArray(value)){where[col]={...value};continue}where[col]=value}}return where}_getOptions(params){let fields=this.attributes,where=this.mapFilter({...params.where,...(0,_helpers.omit)(params,this.excludeParamsFromFilter)},fields);if(params.q&¶ms.searchKey){let searchConditions=Array.isArray(params.searchKey)?params.searchKey.map(key=>({[key]:{[_sequelize.Op.like]:`%${params.q}%`}})):[{[params.searchKey]:{[_sequelize.Op.like]:`%${params.q}%`}}];where={...where,[_sequelize.Op.and]:[...params.andWhere||[],{[_sequelize.Op.or]:[...searchConditions,...params.orWhere||[]]}]}}(params.orWhere||params.andWhere)&&(where={...where,[_sequelize.Op.and]:[...params.andWhere||[],{[_sequelize.Op.or]:params.orWhere||[]}]});let order=[];params?.orderBy&&fields.includes(params?.orderBy)&&order.push([params?.orderBy,params?.sort??"DESC"]),params?.order&&order.push(...params.order,["id","ASC"]);let attributes=params.attributes?params.attributes.filter(d=>"string"!=typeof d||fields.includes(d)):void 0;return{where,order,group:params?.groupBy,...attributes&&{attributes},include:params.include}}async findForPublic(params,mapInto){let options=this._getOptions(params),limit=+(params?.perPage??20);return(await this.findAll({...options,limit})).map(d=>mapInto(d))}async paginate(params,mapInto){let options=this._getOptions(params),limit=+(params?.perPage??20),page=+(params?.page??1),data=await this.findAndCountAll({limit,offset:page>1?limit*(page-1):0,...options,distinct:!0});data.count=Array.isArray(data.count)?data.count.length:data.count;let totalPage=Math.ceil(data.count/limit);return{data:mapInto?data.rows.map(d=>mapInto(d)):data.rows,timestamp:(0,_moment.default)().utc().toISOString(!0),meta:{perPage:limit,page:page,totalPage:totalPage,total:data.count,prevPage:page>1?page-1:null,nextPage:page<totalPage?page+1:null}}}async export(params,mapInto){let options=this._getOptions(params),data=await this.findAll(options);return mapInto?data.map(d=>mapInto(d)):data}async updateOrCreate(values,whereOptions,options){let data=await this.findOne({where:whereOptions});return data?(await this.update(data,values,options),data):await this.create(values,options)}async findAll(options){return await this.Model.findAll(options)}async findAndCountAll(options){return await this.Model.findAndCountAll(options)}async findOne(options){return await this.Model.findOne(options)}async create(values,options){return await this.Model.create(values,options)}async update(entity,values,options){if("string"==typeof entity&&(entity=await this.findOne({where:{id:entity},attributes:["id"]})),!entity)throw new _common.NotFoundException;return await entity.update(values,{...options})}async upsert(values,options){return await this.Model.upsert(values,{...options})}async bulkUpdate(values,options){return await this.Model.update(values,{...options})}async bulkCreate(values,options){let idAttribute=this.attributesTypes.find(attr=>"id"===attr.name);return idAttribute&&"BIGINT"!==idAttribute.type&&(values=values.map(val=>(val.id||(val.id=generateId()),val))),await this.Model.bulkCreate(values,options)}async destroy(options){return await this.Model.destroy(options)}async sum(field,options){return await this.Model.sum(field,options)}async sumField(params,field){let options=this._getOptions(params);return await this.sum(field,options)}async sumCol(params,fieldToSum,expectedField){let options=this._getOptions(params);return options.attributes=[[(0,_sequelize.fn)("sum",(0,_sequelize.col)(fieldToSum)),expectedField]],(await this.Model.findAll(options)).reduce((total,row)=>total+parseFloat(String(row.get(expectedField))||"0"),0)}async count(options){return await this.Model.count(options)}async filteredFindAll(params){let options=this._getOptions(params);return await this.Model.findAll(options)}};!function(decorators,target,key,desc){var d,c=arguments.length,r=c<3?target:null===desc?desc=Object.getOwnPropertyDescriptor(target,key):desc;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)r=Reflect.decorate(decorators,target,key,desc);else for(var i=decorators.length-1;i>=0;i--)(d=decorators[i])&&(r=(c<3?d(r):c>3?d(target,key,r):d(target,key))||r);c>3&&r&&Object.defineProperty(target,key,r)}([(0,_common.Inject)(_sequelizetypescript.Sequelize),function(k,v){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(k,v)}("design:type",void 0===_sequelizetypescript.Sequelize?Object:_sequelizetypescript.Sequelize)],Repository.prototype,"db",void 0);
|