-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
246 lines (202 loc) · 6.37 KB
/
index.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
import PocketBase from "pocketbase";
import { BackendModule, InitOptions, Services } from "i18next";
import { arrayToObject } from "utilities";
/**
* A function that creates a PocketBase collection schema
* @param languages - The languages that are being loaded
* @param namespace - The namespace that is being loaded
* @param key - The key that is being loaded
* @param value - The value that is being loaded
* @returns An array of PocketBase collection schema objects
*/
export type CollectionSchemaCreator = (
languages: readonly string[],
namespace: string,
key: string,
value: string
) => Array<{
name: string;
required: boolean;
type: string;
unique: boolean;
}>;
/**
* A function that creates a PocketBase resource data object
* @param language - The language that is being loaded
* @param namespace - The namespace that is being loaded
* @param key - The key that is being loaded
* @param value - The value that is being loaded
* @returns A PocketBase resource data object
*/
export type ResourceDataCreator = (
language: string,
namespace: string,
key: string,
value: string
) => Record<string, string | number | boolean>;
export type PocketBaseI18NextBackendOptions = {
collectionSchemaCreator?: CollectionSchemaCreator;
pocketbaseUrl?: string;
pocketbaseAdminName?: string;
pocketbaseAdminPassword?: string;
refetchInterval?: number;
resourceDataCreator?: ResourceDataCreator;
};
class PocketBaseI18NextBackend implements BackendModule {
public static type = "backend";
public type = "backend" as const;
private services: Services | undefined;
private backendOptions: PocketBaseI18NextBackendOptions = {};
private i18nextOptions: InitOptions = {};
private collectionSchemaCreator: CollectionSchemaCreator = () => [
{
name: "key",
required: true,
type: "text",
unique: true,
},
{
name: "translation",
required: true,
type: "text",
unique: false,
},
];
private resourceDataCreator: ResourceDataCreator = (
language,
namespace,
key,
value
) => ({
key,
translation: value,
});
private translationsCache: Record<string, Record<string, string>> = {};
private _pb: PocketBase | undefined;
private get pb() {
if (!this._pb) {
if (!this.backendOptions.pocketbaseUrl) {
throw new Error("PocketBaseI18NextBackend: PocketBase URL is required");
}
this._pb = new PocketBase(this.backendOptions.pocketbaseUrl);
}
return this._pb;
}
private async authToPocketBase() {
const { pocketbaseAdminPassword, pocketbaseAdminName } =
this.backendOptions;
if (!pocketbaseAdminName || !pocketbaseAdminPassword) {
throw new Error(
"PocketBaseI18NextBackend: PocketBase username and password are required"
);
}
this.pb.admins.authWithPassword(
pocketbaseAdminName,
pocketbaseAdminPassword
);
}
private async refetchTranslations() {
await Promise.all(
Object.keys(this.translationsCache).map(async (collectionName) => {
const resp = await this.pb
.collection(collectionName)
.getFullList(undefined, { $autoCancel: false });
const translations = arrayToObject(
resp,
(resource) => resource.key,
(resource) => resource.translation
);
this.translationsCache[collectionName] = translations;
})
);
}
public async init(
services: Services,
backendOptions: PocketBaseI18NextBackendOptions,
i18nextOptions: InitOptions
) {
this.services = services;
this.backendOptions = backendOptions;
this.i18nextOptions = i18nextOptions;
if (backendOptions.collectionSchemaCreator) {
this.collectionSchemaCreator = backendOptions.collectionSchemaCreator;
}
if (backendOptions.resourceDataCreator) {
this.resourceDataCreator = backendOptions.resourceDataCreator;
}
if (!backendOptions.pocketbaseUrl) {
throw new Error("PocketBaseI18NextBackend: PocketBase URL is required");
}
if (backendOptions.refetchInterval) {
setInterval(
() => this.refetchTranslations(),
backendOptions.refetchInterval
);
}
this._pb = new PocketBase(backendOptions.pocketbaseUrl);
await this.authToPocketBase();
}
/** Load a translation */
public async read(language: string, namespace: string) {
const collectionName = `${language}_${namespace}`;
let translations: Record<string, string>;
if (!this.translationsCache[collectionName]) {
const resp = await this.pb
.collection(collectionName)
.getFullList(undefined, { $autoCancel: false });
translations = arrayToObject(
resp,
(resource) => resource.key,
(resource) => resource.translation
);
this.translationsCache[collectionName] = translations;
}
translations = this.translationsCache[collectionName];
return translations;
}
/** Save the missing translation */
async create?(
languages: readonly string[],
namespace: string,
key: string,
value = key
) {
for (const language of languages) {
const collectionName = `${language}_${namespace}`;
const collections = await this.pb.collections.getFullList(undefined, {
$autoCancel: false,
});
const targetCollection = collections.find((collection) => {
return collection.name === collectionName;
});
if (!targetCollection) {
await this.pb.collections.create(
{
name: collectionName,
schema: this.collectionSchemaCreator(
languages,
namespace,
key,
value
),
type: "base",
},
{ $autoCancel: false }
);
}
const data = this.resourceDataCreator(language, namespace, key, value);
await this.pb
.collection(collectionName)
.create(data, { $autoCancel: false });
}
}
// /** Load multiple languages and namespaces. For backends supporting multiple resources loading */
// readMulti?(
// languages: readonly string[],
// namespaces: readonly string[],
// callback: MultiReadCallback
// ): void {};
// /** Store the translation. For backends acting as cache layer */
// save?(language: string, namespace: string, data: ResourceLanguage): void {}
}
export default PocketBaseI18NextBackend;