-
-
Notifications
You must be signed in to change notification settings - Fork 768
/
Copy pathdb-lock.test.ts
67 lines (54 loc) · 2 KB
/
db-lock.test.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import { withDbLock } from './db-lock';
import { getDbConfig } from '../../test/e2e/helpers/database-config';
import type { IDBOption } from '../types';
import type { Logger } from '../logger';
test('should lock access to any action', async () => {
const lock = withDbLock(getDbConfig() as IDBOption);
const asyncAction = (input: string) => Promise.resolve(`result: ${input}`);
const result = await lock(asyncAction)('data');
expect(result).toBe('result: data');
});
const ms = (millis: number) =>
new Promise((resolve) => {
setTimeout(() => resolve('time'), millis);
});
test('should await other actions on lock', async () => {
const lock = withDbLock(getDbConfig() as IDBOption);
const results: string[] = [];
const slowAsyncAction = (input: string) => {
return new Promise((resolve) => {
setTimeout(() => {
results.push(input);
resolve(input);
}, 200);
});
};
const fastAction = async (input: string) => {
results.push(input);
};
const lockedAction = lock(slowAsyncAction);
const lockedAnotherAction = lock(fastAction);
// deliberately skipped await to simulate another server running slow operation
lockedAction('first');
await ms(100); // start fast action after slow action established DB connection
await lockedAnotherAction('second');
expect(results).toStrictEqual(['first', 'second']);
});
test('should handle lock timeout', async () => {
const timeoutMs = 10;
let loggedError = '';
const lock = withDbLock(getDbConfig() as IDBOption, {
lockKey: 1,
timeout: timeoutMs,
logger: {
error(msg: string) {
loggedError = msg;
},
} as unknown as Logger,
});
const asyncAction = () => ms(100);
await expect(lock(asyncAction)()).rejects.toStrictEqual(
new Error('Query read timeout'),
);
expect(loggedError).toBe('Locking error: Query read timeout');
});