This repository has been archived by the owner on Feb 10, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
InitService.ts
55 lines (39 loc) · 1.54 KB
/
InitService.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
// Copyright (c) 2021-2022. Heusala Group Oy <info@heusalagroup.fi>. All rights reserved.
import { reduce } from "./functions/reduce";
export interface InitCallback {
() : Promise<void> | void;
}
export class InitService {
private static _initialized : boolean = false;
private static _initializing : boolean = false;
private static _initializers : InitCallback[] = [];
public static registerInitializer (callback: InitCallback) {
if (InitService._initialized) throw new TypeError('Service already initialized');
if (InitService._initializing) throw new TypeError('Service already initializing');
InitService._initializers.push(callback);
}
public static isInitializing () : boolean {
return InitService._initializing;
}
public static isInitialized () : boolean {
return InitService._initialized;
}
/**
* Initializes dynamic data for SSR / SEO
*/
public static async initialize () {
if (InitService._initialized) throw new TypeError('Service already initialized');
if (InitService._initializing) throw new TypeError('Service already initializing');
InitService._initializing = true;
await reduce(
InitService._initializers,
async (p: Promise<void>, callback: InitCallback) : Promise<void> => {
await p;
await callback();
},
Promise.resolve()
);
InitService._initializing = false;
InitService._initialized = true;
}
}