-
Notifications
You must be signed in to change notification settings - Fork 8
/
cron.ts
81 lines (74 loc) · 2.64 KB
/
cron.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { IsNull, Not } from "typeorm";
import { DiscordServer } from "./db/entity/DiscordServer";
import { refreshDiscordMember } from "./utils/discord/refreshRoles";
import config from "./config";
import {
DiscordMemberRepository,
DiscordServerConfigRepository,
DiscordServerRepository,
} from "./db";
import modules from "./starkyModules";
const refreshDiscordServers = async () => {
const discordServers = await DiscordServerRepository.find();
console.log(`[Cron] Refreshing ${discordServers.length} discord servers`);
for (let discordServer of discordServers) {
await refreshDiscordServer(discordServer);
}
};
export const refreshDiscordServer = async (discordServer: DiscordServer) => {
const discordMembers = await DiscordMemberRepository.find({
where: {
discordServerId: discordServer.id,
starknetWalletAddress: Not(IsNull()),
},
withDeleted: true,
});
const discordConfigs = await DiscordServerConfigRepository.findBy({
discordServerId: discordServer.id,
});
// Refreshing each member one by one. We could
// optimize using a pool in parallel.
for (let discordMember of discordMembers) {
let deleteDiscordMember = !!discordMember.deletedAt;
const walletAddress = discordMember.starknetWalletAddress;
if (!walletAddress) continue;
const network = discordMember.starknetNetwork;
if (!network) continue;
for (let discordConfig of discordConfigs) {
const starkyModule = modules[discordConfig.starkyModuleType];
try {
if (starkyModule.refreshInCron)
await refreshDiscordMember(
discordConfig,
discordMember,
starkyModule
);
} catch (e: any) {
if (e?.code === 10007) {
// This user is no longer a member of this discord server, we should just remove it
deleteDiscordMember = true;
console.log(
`Discord member ${discordMember.discordMemberId} does not exist in Discord server ${discordConfig.discordServerId} and will be deleted`
);
} else {
console.error(
`Could not refresh discord member ${discordMember.discordMemberId} with configuration ${discordConfig.id} in server : ${discordConfig.discordServerId} ${e}`
);
}
}
}
if (deleteDiscordMember) {
await DiscordMemberRepository.remove(discordMember);
}
}
};
const cronInterval = async () => {
try {
await refreshDiscordServers();
} catch (e) {
console.log("[Cron] Error while refreshing discord servers");
console.error(e);
}
setTimeout(cronInterval, config.UPDATE_STATUS_EVERY_SECONDS * 1000);
};
export default cronInterval;