1 |
rakinar2 |
577 |
import { Class, DefaultExport } from "../types/Utils"; |
2 |
|
|
import { logInfo } from "../utils/logger"; |
3 |
|
|
import type Client from "./Client"; |
4 |
|
|
import Service from "./Service"; |
5 |
|
|
|
6 |
|
|
export default class ServiceManager { |
7 |
|
|
constructor(protected readonly client: Client) {} |
8 |
|
|
|
9 |
|
|
async loadServices() { |
10 |
|
|
const serviceFiles = this.client.services.map(service => { |
11 |
|
|
let filepath = service; |
12 |
|
|
|
13 |
|
|
for (const alias in this.client.aliases) { |
14 |
|
|
filepath = filepath.replaceAll(`@${alias}`, this.client.aliases[alias as keyof typeof this.client.aliases]); |
15 |
|
|
} |
16 |
|
|
|
17 |
|
|
return filepath; |
18 |
|
|
}); |
19 |
|
|
|
20 |
|
|
for (const file of serviceFiles) { |
21 |
|
|
await this.loadService(file); |
22 |
|
|
} |
23 |
|
|
} |
24 |
|
|
|
25 |
|
|
async loadService(filepath: string) { |
26 |
|
|
const { default: ServiceClass, name }: DefaultExport<Class<Service, [Client]>> & { name?: string } = await import( |
27 |
|
|
filepath |
28 |
|
|
); |
29 |
|
|
|
30 |
|
|
if (!name) { |
31 |
|
|
throw new Error(`Name is empty for service ${filepath}`); |
32 |
|
|
} |
33 |
|
|
|
34 |
|
|
const previousServiceInstance = this.client[name as "startupManager"]; |
35 |
|
|
const service = new ServiceClass(this.client); |
36 |
|
|
|
37 |
|
|
if (previousServiceInstance) { |
38 |
|
|
logInfo(`Previous instance of service ${name} found. Deactivating`); |
39 |
|
|
await this.client.dynamicLoader.unloadEventsFromMetadata(previousServiceInstance); |
40 |
|
|
await previousServiceInstance.deactivate(); |
41 |
|
|
} |
42 |
|
|
|
43 |
|
|
this.client[name as "startupManager"] = service as any; |
44 |
|
|
await this.client.dynamicLoader.loadEventsFromMetadata(service); |
45 |
|
|
await service.boot(); |
46 |
|
|
|
47 |
|
|
logInfo(`${previousServiceInstance ? "Rel" : "L"}oaded Service: `, name); |
48 |
|
|
} |
49 |
|
|
|
50 |
|
|
loadServiceFromDirectory(servicesDirectory: string) { |
51 |
|
|
return this.client.dynamicLoader.loadServiceFromDirectory(servicesDirectory); |
52 |
|
|
} |
53 |
|
|
} |