create-dacosta-proj 1.0.24 → 1.0.25
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/package.json
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* db: import('simple-supabase').DB | null,
|
|
4
4
|
* supabase: import('@supabase/supabase-js').SupabaseClient | null,
|
|
5
5
|
* redis: import('redis').RedisClientType | null,
|
|
6
|
+
* redisLock: ((lockName: string, timeout?: number) => Promise<() => Promise<void>>) | null,
|
|
6
7
|
* }}
|
|
7
8
|
*/
|
|
8
9
|
|
|
@@ -10,5 +11,6 @@ const global = {
|
|
|
10
11
|
db: null,
|
|
11
12
|
supabase: null,
|
|
12
13
|
redis: null,
|
|
14
|
+
redisLock: null,
|
|
13
15
|
};
|
|
14
16
|
module.exports = { global };
|
|
@@ -5,6 +5,7 @@ const { global } = require('@/config/global');
|
|
|
5
5
|
const { SimpleSupabase } = require('simple-supabase');
|
|
6
6
|
const { createClient: createSupabaseClient } = require('@supabase/supabase-js');
|
|
7
7
|
const { createClient: createRedisClient } = require('redis');
|
|
8
|
+
const redisLock = require('@/helpers/redisLock');
|
|
8
9
|
|
|
9
10
|
module.exports = async () => {
|
|
10
11
|
|
|
@@ -29,4 +30,5 @@ module.exports = async () => {
|
|
|
29
30
|
await redis.connect();
|
|
30
31
|
|
|
31
32
|
global.redis = redis;
|
|
33
|
+
global.redisLock = redisLock(redis);
|
|
32
34
|
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const DEFAULT_TIMEOUT = 5000;
|
|
4
|
+
const DEFAULT_RETRY_DELAY = 50;
|
|
5
|
+
|
|
6
|
+
function redisLock(client, retryDelay = DEFAULT_RETRY_DELAY) {
|
|
7
|
+
async function lock(lockName, timeout = DEFAULT_TIMEOUT) {
|
|
8
|
+
const lockKey = `lock.${lockName}`;
|
|
9
|
+
const lockExpiry = Date.now() + timeout + 1;
|
|
10
|
+
while (true) {
|
|
11
|
+
const result = await client.set(lockKey, lockExpiry, { PX: timeout, NX: true });
|
|
12
|
+
if (result !== null) {
|
|
13
|
+
return async () => {
|
|
14
|
+
if (lockExpiry > Date.now()) await client.del(lockKey);
|
|
15
|
+
};
|
|
16
|
+
}
|
|
17
|
+
await new Promise(r => setTimeout(r, retryDelay));
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
return lock;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
module.exports = redisLock;
|