forked from EvolutionAPI/evolution-api
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-multi-file-auth-state-redis-db.ts
More file actions
93 lines (81 loc) · 2.56 KB
/
use-multi-file-auth-state-redis-db.ts
File metadata and controls
93 lines (81 loc) · 2.56 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
import { CacheService } from '@api/services/cache.service';
import { Logger } from '@config/logger.config';
import { AuthenticationCreds, AuthenticationState, initAuthCreds, proto, SignalDataTypeMap } from 'baileys';
export async function useMultiFileAuthStateRedisDb(
instanceName: string,
cache: CacheService,
): Promise<{
state: AuthenticationState;
saveCreds: () => Promise<void>;
removeCreds: () => Promise<void>;
}> {
const logger = new Logger('useMultiFileAuthStateRedisDb');
const writeData = async (data: any, key: string): Promise<any> => {
try {
return await cache.hSet(instanceName, key, data);
} catch (error) {
return logger.error({ localError: 'writeData', error });
}
};
const readData = async (key: string): Promise<any> => {
try {
return await cache.hGet(instanceName, key);
} catch (error) {
logger.error({ localError: 'readData', error });
return;
}
};
const removeData = async (key: string) => {
try {
return await cache.hDelete(instanceName, key);
} catch (error) {
logger.error({ readData: 'removeData', error });
}
};
async function removeCreds(): Promise<any> {
try {
logger.warn({ action: 'redis.delete', instanceName });
return await cache.delete(instanceName);
} catch {
return;
}
}
const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds();
return {
state: {
creds,
keys: {
get: async (type, ids: string[]) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const data: { [_: string]: SignalDataTypeMap[type] } = {};
await Promise.all(
ids.map(async (id) => {
let value = await readData(`${type}-${id}`);
if (type === 'app-state-sync-key' && value) {
value = proto.Message.AppStateSyncKeyData.create(value);
}
data[id] = value;
}),
);
return data;
},
set: async (data: any) => {
const tasks: Promise<void>[] = [];
for (const category in data) {
for (const id in data[category]) {
const value = data[category][id];
const key = `${category}-${id}`;
tasks.push(value ? await writeData(value, key) : await removeData(key));
}
}
await Promise.all(tasks);
},
},
},
saveCreds: async () => {
return await writeData(creds, 'creds');
},
removeCreds,
};
}