-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathsnapper.ts
50 lines (43 loc) · 1.18 KB
/
snapper.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
import { SNAPPER_API_BASE } from '@dao-dao/utils'
export type QuerySnapperOptions = {
query: string
parameters?: Record<string, any>
}
export const querySnapper = async <T = any>({
query,
parameters,
}: QuerySnapperOptions): Promise<T | undefined> => {
// Filter out undefined args.
if (parameters) {
parameters = Object.entries(parameters).reduce(
(acc, [key, value]) => {
if (value !== undefined) {
acc[key] = value
}
return acc
},
{} as Record<string, any>
)
}
const params = new URLSearchParams(parameters)
const url = `${SNAPPER_API_BASE}/q/${query}?${params.toString()}`
const response = await fetch(url)
if (response.status >= 300) {
throw new Error(
`Error querying snapper for ${query} with params ${params.toString()}: ${
response.status
} ${await response.text().catch(() => '')}`.trim()
)
}
// Return undefined and do not attempt to parse body if no content.
if (response.status === 204) {
return
}
try {
const text = await response.text()
return text ? JSON.parse(text) : undefined
} catch (err) {
console.error(err)
// Return undefined
}
}