-
Notifications
You must be signed in to change notification settings - Fork 731
Expand file tree
/
Copy pathsequelizeRepository.ts
More file actions
224 lines (192 loc) · 6.13 KB
/
Copy pathsequelizeRepository.ts
File metadata and controls
224 lines (192 loc) · 6.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
import lodash from 'lodash'
import { Sequelize, Transaction, UniqueConstraintError } from 'sequelize'
import { Error400 } from '@crowd/common'
import { DbConnection, getDbConnection } from '@crowd/data-access-layer/src/database'
import { QueryExecutor } from '@crowd/data-access-layer/src/queryExecutor'
import { getServiceLogger } from '@crowd/logging'
import { getOpensearchClient } from '@crowd/opensearch'
import { getRedisClient } from '@crowd/redis'
import { Client as TemporalClient, getTemporalClient } from '@crowd/temporal'
import { SegmentData } from '@crowd/types'
import {
IS_TEST_ENV,
OPENSEARCH_CONFIG,
PRODUCT_DB_CONFIG,
REDIS_CONFIG,
TEMPORAL_CONFIG,
} from '../../conf'
import { IServiceOptions } from '../../services/IServiceOptions'
import { databaseInit } from '../databaseConnection'
import {
SequelizeQueryExecutor,
TransactionalSequelizeQueryExecutor,
} from '../sequelizeQueryExecutor'
import { IRepositoryOptions } from './IRepositoryOptions'
/**
* Abstracts some basic Sequelize operations.
* See https://sequelize.org/v5/index.html to learn how to customize it.
*/
export default class SequelizeRepository {
/**
* Cleans the database.
*/
static async cleanDatabase(database) {
if (!IS_TEST_ENV) {
throw new Error('Clean database only allowed for test!')
}
await database.sequelize.sync({ force: true })
}
static async getDefaultIRepositoryOptions(
user?,
tenant?,
segments?,
): Promise<IRepositoryOptions> {
let temporal: TemporalClient | undefined
if (TEMPORAL_CONFIG.serverUrl) {
temporal = await getTemporalClient(TEMPORAL_CONFIG)
}
let productDb: DbConnection | undefined
if (PRODUCT_DB_CONFIG) {
productDb = await getDbConnection(PRODUCT_DB_CONFIG)
}
const opensearch = await getOpensearchClient(OPENSEARCH_CONFIG)
return {
log: getServiceLogger(),
database: await databaseInit(),
currentTenant: tenant,
currentUser: user,
currentSegments: segments,
bypassPermissionValidation: true,
language: 'en',
redis: await getRedisClient(REDIS_CONFIG, true),
temporal,
productDb,
opensearch,
}
}
/**
* Returns the currentUser if it exists on the options.
*/
static getCurrentUser(options: IRepositoryOptions) {
return (options && options.currentUser) || { id: null }
}
/**
* Returns the tenant if it exists on the options.
*/
static getCurrentTenant(options: IRepositoryOptions) {
return (options && options.currentTenant) || { id: null }
}
static getCurrentSegments(options: IRepositoryOptions) {
return (options && options.currentSegments) || []
}
static getStrictlySingleActiveSegment(
options: IRepositoryOptions | IServiceOptions,
): SegmentData {
if (options.currentSegments.length !== 1) {
throw new Error400(
`This operation can have exactly one segment. Found ${options.currentSegments.length} segments.`,
)
}
return options.currentSegments[0]
}
static getStrictlySingleProjectGroupSegment(
options: IRepositoryOptions | IServiceOptions,
): SegmentData {
const segment = this.getStrictlySingleActiveSegment(options)
if (segment.parentId != null || segment.grandparentId != null) {
throw new Error400(
`This operation requires a project group segment. Segment ${segment.id} is not a project group.`,
)
}
return segment
}
/**
* Returns the transaction if it exists on the options.
*/
static getTransaction(options: IRepositoryOptions) {
return (options && options.transaction) || undefined
}
/**
* Creates a database transaction.
*/
static async createTransaction(options: IRepositoryOptions) {
if (options.transaction) {
if (options.transaction.crowdNestedTransactions !== undefined) {
options.transaction.crowdNestedTransactions++
} else {
options.transaction.crowdNestedTransactions = 1
}
return options.transaction
}
return options.database.sequelize.transaction()
}
static async withTx<T>(options: IRepositoryOptions, fn: (tx: Transaction) => Promise<T>) {
const tx = await this.createTransaction(options)
try {
const result = await fn(tx)
await this.commitTransaction(tx)
return result
} catch (error) {
await this.rollbackTransaction(tx)
throw error
}
}
/**
* Creates a transactional repository options instance
*/
static async createTransactionalRepositoryOptions(
options: IRepositoryOptions,
): Promise<IRepositoryOptions> {
const transaction = await this.createTransaction(options)
return {
...options,
transaction,
}
}
/**
* Commits a database transaction.
*/
static async commitTransaction(transaction) {
if (
transaction.crowdNestedTransactions !== undefined &&
transaction.crowdNestedTransactions > 0
) {
transaction.crowdNestedTransactions--
return Promise.resolve()
}
return transaction.commit()
}
/**
* Rolls back a database transaction.
*/
static async rollbackTransaction(transaction) {
if (
transaction.crowdNestedTransactions !== undefined &&
transaction.crowdNestedTransactions > 0
) {
transaction.crowdNestedTransactions--
return Promise.resolve()
}
return transaction.rollback()
}
static handleUniqueFieldError(error, language, entityName) {
if (!(error instanceof UniqueConstraintError)) {
return
}
const fieldName = lodash.get(error, 'errors[0].path')
throw new Error400(language, `entities.${entityName}.errors.unique.${fieldName}`)
}
static getSequelize(options: IRepositoryOptions): Sequelize {
return options.database.sequelize as Sequelize
}
static getQueryExecutor(options: IRepositoryOptions): QueryExecutor {
const seq = this.getSequelize(options)
const transaction = this.getTransaction(options)
return transaction
? new TransactionalSequelizeQueryExecutor(seq, transaction)
: new SequelizeQueryExecutor(seq)
}
static getSegmentIds(options: IRepositoryOptions): string[] {
return options.currentSegments.map((s) => s.id)
}
}