-
Notifications
You must be signed in to change notification settings - Fork 23
/
httpStore.ts
81 lines (68 loc) · 2.59 KB
/
httpStore.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
import { ValidStoreType, AsyncStore } from './types';
import { IS_NODE, joinUrlParts } from '../util';
import { KeyError, HTTPError } from '../errors';
enum HTTPMethod {
HEAD = 'HEAD',
GET = 'GET',
PUT = 'PUT',
}
const DEFAULT_METHODS = [HTTPMethod.HEAD, HTTPMethod.GET, HTTPMethod.PUT];
interface HTTPStoreOptions {
fetchOptions?: RequestInit;
supportedMethods?: HTTPMethod[];
}
export class HTTPStore implements AsyncStore<ArrayBuffer> {
listDir?: undefined;
rmDir?: undefined;
getSize?: undefined;
rename?: undefined;
public url: string;
public fetchOptions: RequestInit;
private supportedMethods: Set<HTTPMethod>;
constructor(url: string, options: HTTPStoreOptions = {}) {
this.url = url;
const { fetchOptions = {}, supportedMethods = DEFAULT_METHODS } = options;
this.fetchOptions = fetchOptions;
this.supportedMethods = new Set(supportedMethods);
}
keys(): Promise<string[]> {
throw new Error('Method not implemented.');
}
async getItem(item: string, opts?: RequestInit) {
const url = joinUrlParts(this.url, item);
const value = await fetch(url, { ...this.fetchOptions, ...opts });
if (value.status === 404) {
// Item is not found
throw new KeyError(item);
} else if (value.status !== 200) {
throw new HTTPError(String(value.status));
}
// only decode if 200
if (IS_NODE) {
return Buffer.from(await value.arrayBuffer());
} else {
return value.arrayBuffer(); // Browser
}
}
async setItem(item: string, value: ValidStoreType): Promise<boolean> {
if (!this.supportedMethods.has(HTTPMethod.PUT)) {
throw new Error('HTTP PUT no a supported method for store.');
}
const url = joinUrlParts(this.url, item);
if (typeof value === 'string') {
value = new TextEncoder().encode(value).buffer;
}
const set = await fetch(url, { ...this.fetchOptions, method: HTTPMethod.PUT, body: value });
return set.status.toString()[0] === '2';
}
deleteItem(_item: string): Promise<boolean> {
throw new Error('Method not implemented.');
}
async containsItem(item: string): Promise<boolean> {
const url = joinUrlParts(this.url, item);
// Just check headers if HEAD method supported
const method = this.supportedMethods.has(HTTPMethod.HEAD) ? HTTPMethod.HEAD : HTTPMethod.GET;
const value = await fetch(url, { ...this.fetchOptions, method });
return value.status === 200;
}
}