-
Notifications
You must be signed in to change notification settings - Fork 119
/
mongoose.utils.ts
44 lines (41 loc) · 1.21 KB
/
mongoose.utils.ts
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
import { Logger } from '@nestjs/common';
import { Observable } from 'rxjs';
import { delay, retryWhen, scan } from 'rxjs/operators';
import { DEFAULT_DB_CONNECTION } from '../mongoose.constants';
export function getModelToken(model: string, connectionName?: string) {
if (connectionName === undefined) {
return `${model}Model`;
}
return `${getConnectionToken(connectionName)}/${model}Model`;
}
export function getConnectionToken(name?: string) {
return name && name !== DEFAULT_DB_CONNECTION
? `${name}Connection`
: DEFAULT_DB_CONNECTION;
}
export function handleRetry(
retryAttempts = 9,
retryDelay = 3000,
): <T>(source: Observable<T>) => Observable<T> {
const logger = new Logger('MongooseModule');
return <T>(source: Observable<T>) =>
source.pipe(
retryWhen((e) =>
e.pipe(
scan((errorCount, error) => {
logger.error(
`Unable to connect to the database. Retrying (${
errorCount + 1
})...`,
'',
);
if (errorCount + 1 >= retryAttempts) {
throw error;
}
return errorCount + 1;
}, 0),
delay(retryDelay),
),
),
);
}