-
Notifications
You must be signed in to change notification settings - Fork 0
/
narou-fetch.ts
45 lines (37 loc) · 1.02 KB
/
narou-fetch.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
import { unzipp } from "./util/unzipp.js";
import NarouNovel from "./narou.js";
import type { NarouParams } from "./narou.js";
type Fetch = typeof fetch;
/**
* なろう小説APIへのリクエストを実行する
*/
export default class NarouNovelFetch extends NarouNovel {
/**
* コンストラクタ
* @param fetch fetch関数(デフォルトはネイティブのfetch)
*/
constructor(private fetch?: Fetch) {
super();
}
protected async execute<T>(
params: NarouParams,
endpoint: string
): Promise<T> {
const query = { ...params, out: "json" };
if (query.gzip === undefined) {
query.gzip = 5;
}
const url = new URL(endpoint);
Object.entries(query).forEach(([key, value]) => {
if (value) {
url.searchParams.append(key, value.toString());
}
});
const res = await (this.fetch ?? fetch)(url);
if (query.gzip === 0) {
return (await res.json()) as T;
}
const buffer = await res.arrayBuffer();
return await unzipp(buffer);
}
}