-
Notifications
You must be signed in to change notification settings - Fork 0
/
utility.ts
51 lines (49 loc) · 1.91 KB
/
utility.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
export type validatorFunc = (arg0: string) => boolean;
export type normalizorFunc = (arg0: string) => string;
export type verifyFunc = (arg0: string) => Promise<boolean>;
/**
* verifyIdentifier attempts to retrieve an object from a remote source.
* @param identifier: string, the identifier of the object to be retrieved.
* @param url: string, the URL to use to retrieve the object from.
* @param validate: validatorFunc, a function that accepts a string and returns a boolean, the fetch will not occur if false is returned.
* @returns Promise<boolean> - True if the identifier can be retrieved exists, false otherwise.
*/
export async function verifyIdentifier(
identifier: string,
u: string,
validate: validatorFunc,
): Promise<boolean> {
if (validate(identifier)) {
const response = await fetch(u);
if (response !== undefined && response !== null) {
return response.ok;
}
}
return false;
}
/**
* getObject is a generic retrieval of an object from a remote source. It applies the normalizer, validator to the provided identfier before
* fetching the URL.
* @param identifier: string, the identifier of the object to be retrieved.
* @param url: string, the URL to use to retrieve the object from.
* @param validate: validatorFunc, a function that accepts a string and returns a boolean, the fetch will not occur if false is returned.
* @return Promise<object | undefined>, if the retrieval failes or can't be parse as JSON it returns undefined, otherwise the object
*/
export async function getObject(
identifier: string,
url: string,
validate: validatorFunc,
): Promise<object | undefined> {
if (validate(identifier)) {
const response = await fetch(url);
if (response !== undefined && response !== null && response.ok) {
const src = await response.text();
try {
return JSON.parse(src);
} catch {
return undefined;
}
}
}
return undefined;
}