-
-
Notifications
You must be signed in to change notification settings - Fork 196
/
UrlTokenStorage.ts
78 lines (66 loc) · 2.28 KB
/
UrlTokenStorage.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
import { ThemeObjectsList } from '@/types';
import { AnyTokenSet } from '@/types/tokens';
import { RemoteTokenStorage, RemoteTokenStorageFile } from './RemoteTokenStorage';
import { singleFileSchema } from './schemas/singleFileSchema';
import IsJSONString from '@/utils/isJSONString';
import { tokensMapSchema } from './schemas/tokensMapSchema';
type UrlData = {
values: Record<string, AnyTokenSet<false>>
$themes?: ThemeObjectsList
};
export class UrlTokenStorage extends RemoteTokenStorage {
private url: string;
private secret: string;
constructor(url: string, secret: string) {
super();
this.url = url;
this.secret = secret;
}
private convertUrlDataToFiles(data: UrlData): RemoteTokenStorageFile[] {
return [
{
type: 'themes',
path: '$themes.json',
data: data.$themes ?? [],
},
...Object.entries(data.values).map<RemoteTokenStorageFile>(([name, tokenSet]) => ({
name,
type: 'tokenSet',
path: `${name}.json`,
data: tokenSet,
})),
];
}
public async read(): Promise<RemoteTokenStorageFile[]> {
const customHeaders = IsJSONString(this.secret)
? JSON.parse(this.secret) as Record<string, string>
: {};
const headers = {
Accept: 'application/json',
...customHeaders,
};
const response = await fetch(this.url, {
method: 'GET',
headers,
});
if (response.ok) {
const parsedJsonData = await response.json();
const validationResult = await singleFileSchema.safeParseAsync(parsedJsonData);
// @README if this validation passes we can assume it is in a newer format
if (validationResult.success) {
const urlstorageData = validationResult.data as UrlData;
return this.convertUrlDataToFiles(urlstorageData);
}
// @README if not this is an older format where we just have tokens
const onlyTokensValidationResult = await tokensMapSchema.safeParseAsync(parsedJsonData);
if (onlyTokensValidationResult.success) {
const urlstorageData = onlyTokensValidationResult.data as UrlData['values'];
return this.convertUrlDataToFiles({ values: urlstorageData });
}
}
return [];
}
public async write(): Promise<boolean> {
throw new Error('Not implemented');
}
}