-
Notifications
You must be signed in to change notification settings - Fork 201
Expand file tree
/
Copy pathindex.ts
More file actions
75 lines (65 loc) · 1.91 KB
/
index.ts
File metadata and controls
75 lines (65 loc) · 1.91 KB
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
import { Cacheable, type CacheableOptions } from "cacheable";
import { Hookified, type HookifiedOptions } from "hookified";
import {
type FetchOptions,
type FetchRequestInit,
type Response as FetchResponse,
fetch,
} from "./fetch.js";
export type CacheableNetOptions = {
cache?: Cacheable | CacheableOptions;
} & HookifiedOptions;
export class CacheableNet extends Hookified {
private _cache: Cacheable = new Cacheable();
constructor(options?: CacheableNetOptions) {
super(options);
if (options?.cache) {
this._cache =
options.cache instanceof Cacheable
? options.cache
: new Cacheable(options.cache);
}
}
public get cache(): Cacheable {
return this._cache;
}
public set cache(value: Cacheable) {
this._cache = value;
}
/**
* Fetch data from a URL with optional request options. Will use the cache that is already set in the instance.
* @param {string} url The URL to fetch.
* @param {FetchRequestInit} options Optional request options.
* @returns {Promise<FetchResponse>} The response from the fetch.
*/
public async fetch(
url: string,
options?: FetchRequestInit,
): Promise<FetchResponse> {
const fetchOptions: FetchOptions = {
...options,
cache: this._cache,
};
return fetch(url, fetchOptions);
}
/**
* Perform a GET request to a URL with optional request options. Will use the cache that is already set in the instance.
* @param {string} url The URL to fetch.
* @param {Omit<FetchRequestInit, 'method'>} options Optional request options (method will be set to GET).
* @returns {Promise<FetchResponse>} The response from the fetch.
*/
public async get(
url: string,
options?: Omit<FetchRequestInit, "method">,
): Promise<FetchResponse> {
return this.fetch(url, { ...options, method: "GET" });
}
}
export const Net = CacheableNet;
export {
type FetchOptions,
type FetchRequestInit,
fetch,
get,
type Response as FetchResponse,
} from "./fetch.js";