This repository has been archived by the owner on Jan 9, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSearch.ts
68 lines (62 loc) · 1.76 KB
/
Search.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
import { ResponseFilter, SafeSearch } from '../YouTypes';
import { Fetcher } from '../Fetcher';
export interface SearchOptions {
q: string; // query
page: number;
count: number;
safeSearch: SafeSearch;
onShoppingPage: boolean;
responseFilter: ResponseFilter;
domain: string; // 'search', 'image', 'video', etc.
tbm?: string; // 'isch', 'vid', etc.
// fromSearchBar: boolean; // not a good idea to use this
}
const jsonQueryURL = 'https://you.com/api/search';
const streamQueryURL = 'https://you.com/api/streamingSearch';
function optionsToUrl(
options: SearchOptions,
url: string = jsonQueryURL
): string {
const responseFilter =
typeof options.responseFilter === 'string'
? options.responseFilter
: options.responseFilter.join(',');
return (
`${url}?q=${encodeURIComponent(options.q)}&page=${options.page}` +
`&count=${options.count}&safeSearch=${options.safeSearch}` +
`&onShoppingPage=${options.onShoppingPage}` +
`&responseFilter=${responseFilter}&domain=${options.domain}`
);
}
export function search(
fetcher: Fetcher,
query: SearchOptions
): Promise<string> {
return new Promise((resolve, reject) => {
fetcher(optionsToUrl(query))
.then(response => {
if (response.status === 200) {
resolve(response.body);
} else {
reject(response.status);
}
})
.catch(reject);
});
}
export function streamingSearch(
fetcher: Fetcher,
query: SearchOptions
): Promise<string> {
return new Promise((resolve, reject) => {
fetcher(optionsToUrl(query, streamQueryURL))
.then(response => {
if (response.status === 200) {
resolve(response.body);
} else {
reject(response.status);
}
})
.catch(reject);
});
}