|
1 | 1 | import fetch from "cross-fetch"; |
2 | | -import EventSource from 'eventsource-platform-specific'; |
3 | | - |
4 | | -const apiUrl = 'https://api.indexsupply.net' |
5 | | - |
6 | | -type APISchemaType = string[] |
7 | | -type APIQueryRow = string[] |
8 | | -type APIResultType = [] | [APISchemaType, ...APIQueryRow[]] |
9 | | -type APIDataFormat = { |
10 | | - block_height: number |
11 | | - result: APIResultType[] |
12 | | -} |
13 | | - |
14 | | -export type SupportedChainId = number |
15 | | - |
16 | | -export type QuerySingleRawOptions = { |
17 | | - apiKey?: string, |
18 | | - chainId: SupportedChainId |
19 | | - query: string |
20 | | - eventSignatures: ReadonlyArray<string> |
21 | | -} |
22 | | - |
23 | | -export type QuerySingleData<FormattedRow> = { |
24 | | - blockNumber: number |
25 | | - result: FormattedRow[] |
26 | | -} |
27 | | - |
28 | | -export type QuerySingleRawFunction = typeof querySingleRaw |
29 | | - |
30 | | -export async function querySingleRaw(options: QuerySingleRawOptions): Promise<QuerySingleData<string[]>> { |
| 2 | +import EventSource from "eventsource-platform-specific"; |
| 3 | + |
| 4 | +export type Response<T> = { |
| 5 | + blockNumber: bigint; |
| 6 | + result: T[]; |
| 7 | +}; |
| 8 | + |
| 9 | +type JsonValue = ReturnType<typeof JSON.parse>; |
| 10 | +type DefaultType = { [key: string]: JsonValue }; |
| 11 | +type Formatter<T> = (row: JsonValue[]) => T; |
| 12 | + |
| 13 | +export type Request<T> = { |
| 14 | + apiUrl?: string; |
| 15 | + apiKey?: string; |
| 16 | + chainId: bigint; |
| 17 | + query: string; |
| 18 | + eventSignatures?: ReadonlyArray<string>; |
| 19 | + formatRow?: T extends DefaultType ? undefined | Formatter<T> : Formatter<T>; |
| 20 | +}; |
| 21 | + |
| 22 | +function url<T>( |
| 23 | + path: string, |
| 24 | + request: Request<T> & { blockNumber?: bigint }, |
| 25 | +): string { |
31 | 26 | const params = new URLSearchParams(); |
32 | | - params.append("chain", options.chainId.toString()); |
33 | | - params.append("query", options.query); |
34 | | - params.append("event_signatures", options.eventSignatures.join(',')); |
35 | | - if (options.apiKey) { |
36 | | - params.append("api-key", options.apiKey.toString()); |
| 27 | + params.append("chain", request.chainId.toString()); |
| 28 | + params.append("query", request.query); |
| 29 | + if (request.eventSignatures) { |
| 30 | + params.append("event_signatures", request.eventSignatures.join(",")); |
37 | 31 | } |
38 | | - |
39 | | - const response = await fetch(`${apiUrl}/query?${params.toString()}`) |
40 | | - if (response.status !== 200) { |
41 | | - throw new Error(`Invalid API response: Status ${response.status}`) |
| 32 | + if (request.apiKey) { |
| 33 | + params.append("api-key", request.apiKey.toString()); |
| 34 | + } |
| 35 | + if (request.blockNumber) { |
| 36 | + params.append("block_height", request.blockNumber.toString()); |
42 | 37 | } |
43 | | - const data = await response.json() as APIDataFormat; |
| 38 | + let apiUrl = "https://api.indexsupply.net"; |
| 39 | + if (request.apiUrl) { |
| 40 | + apiUrl = request.apiUrl; |
| 41 | + } |
| 42 | + return `${apiUrl}/${path}?${params.toString()}`; |
| 43 | +} |
44 | 44 |
|
| 45 | +const defaultFormatRow = (names: string[]): Formatter<DefaultType> => { |
| 46 | + return (row: JsonValue[]) => { |
| 47 | + if (row.length !== names.length) { |
| 48 | + throw new Error( |
| 49 | + `Row length (${row.length}) does not match column names length (${names.length})`, |
| 50 | + ); |
| 51 | + } |
| 52 | + return names.reduce((acc, name, index) => { |
| 53 | + acc[name] = row[index]; |
| 54 | + return acc; |
| 55 | + }, {} as DefaultType); |
| 56 | + }; |
| 57 | +}; |
| 58 | + |
| 59 | +export async function query<T = DefaultType>( |
| 60 | + request: Request<T>, |
| 61 | +): Promise<Response<T>> { |
| 62 | + const resp = await fetch(url("query", request)); |
| 63 | + if (resp.status !== 200) { |
| 64 | + throw new Error(`Invalid API response: Status ${resp.status}`); |
| 65 | + } |
| 66 | + const data = await resp.json(); |
45 | 67 | if (data.result.length === 0) { |
46 | | - return { blockNumber: data.block_height, result: [] } |
| 68 | + return { blockNumber: data.block_height, result: [] }; |
47 | 69 | } |
48 | | - |
49 | 70 | if (data.result.length !== 1) { |
50 | | - throw new Error(`Expected 1 result, got ${data.result.length}`) |
| 71 | + throw new Error(`Expected 1 result, got ${data.result.length}`); |
51 | 72 | } |
52 | | - |
53 | | - const result = data.result[0] |
54 | | - |
55 | | - if (result.length === 0) { |
56 | | - return { blockNumber: data.block_height, result: [] } |
| 73 | + const rows = data.result[0]; |
| 74 | + if (rows.length === 0) { |
| 75 | + return { blockNumber: data.blockHeight, result: [] }; |
57 | 76 | } |
58 | | - |
| 77 | + const columnNames = rows.shift(); |
| 78 | + const formatRow = request.formatRow || defaultFormatRow(columnNames); |
59 | 79 | return { |
60 | 80 | blockNumber: data.block_height, |
61 | | - result: result.slice(1), |
62 | | - } |
63 | | -} |
64 | | - |
65 | | -export type QuerySingleLiveRawFunction = typeof querySingleLiveRaw |
66 | | - |
67 | | -export type QuerySingleOptions<FormattedRow> = QuerySingleRawOptions & { |
68 | | - formatRow: (row: string[]) => FormattedRow |
| 81 | + result: rows.map(formatRow), |
| 82 | + }; |
69 | 83 | } |
70 | 84 |
|
71 | | -export async function querySingle<FormattedRow>( |
72 | | - { formatRow, ...options }: QuerySingleOptions<FormattedRow> |
73 | | -): Promise<QuerySingleData<FormattedRow>> { |
74 | | - const { blockNumber, result } = await querySingleRaw(options) |
75 | | - |
76 | | - return { |
77 | | - blockNumber, |
78 | | - result: result.map(formatRow) |
79 | | - } |
80 | | -} |
81 | | - |
82 | | -export type QuerySingleLiveRawOptions = { |
83 | | - apiKey?: string |
84 | | - chainId: SupportedChainId |
85 | | - query: string |
86 | | - eventSignatures: ReadonlyArray<string> |
87 | | - blockNumber?: number |
88 | | -} |
89 | | - |
90 | | -export async function* querySingleLiveRaw(options: QuerySingleLiveRawOptions): AsyncGenerator<QuerySingleData<string[]>> { |
91 | | - const params = new URLSearchParams(); |
92 | | - params.append("chain", options.chainId.toString()); |
93 | | - params.append("query", options.query); |
94 | | - params.append("event_signatures", options.eventSignatures.join(',')); |
95 | | - if (options.apiKey) { |
96 | | - params.append("api-key", options.apiKey.toString()); |
97 | | - } |
98 | | - if (options.blockNumber) { |
99 | | - params.append('block_height', options.blockNumber.toString()) |
100 | | - } |
101 | | - const url = new URL(`${apiUrl}/query-live?${params}`) |
102 | | - |
103 | | - const eventSource = new EventSource(url.toString()) |
104 | | - |
| 85 | +export async function* queryLive<T = DefaultType>( |
| 86 | + request: Request<T> & { blockNumber?: bigint }, |
| 87 | +): AsyncGenerator<Response<T>> { |
| 88 | + const eventSource = new EventSource(url("query-live", request)); |
105 | 89 | try { |
106 | 90 | while (true) { |
107 | 91 | const event = await new Promise<MessageEvent>((resolve, reject) => { |
108 | 92 | eventSource.onmessage = (event) => { |
109 | | - resolve(event) |
110 | | - } |
111 | | - |
| 93 | + resolve(event); |
| 94 | + }; |
112 | 95 | eventSource.onerror = (error) => { |
113 | | - reject(error) |
114 | | - } |
115 | | - }) |
116 | | - |
117 | | - const data = JSON.parse(event.data) as APIDataFormat |
| 96 | + reject(error); |
| 97 | + }; |
| 98 | + }); |
| 99 | + const data = JSON.parse(event.data); |
118 | 100 | if (data.result.length === 0) { |
119 | | - yield { blockNumber: data.block_height, result: [] } |
120 | | - continue |
| 101 | + yield { blockNumber: data.block_height, result: [] }; |
| 102 | + continue; |
121 | 103 | } |
122 | | - |
123 | 104 | if (data.result.length !== 1) { |
124 | | - throw new Error(`Expected 1 result, got ${data.result.length}`) |
| 105 | + throw new Error(`Expected 1 result, got ${data.result.length}`); |
125 | 106 | } |
126 | | - |
127 | | - const result = data.result[0] |
| 107 | + let result = data.result[0]; |
128 | 108 | if (result.length === 0) { |
129 | | - yield { blockNumber: data.block_height, result: [] } |
130 | | - continue |
| 109 | + yield { blockNumber: data.block_height, result: [] }; |
| 110 | + continue; |
131 | 111 | } |
132 | | - |
| 112 | + const columnNames = result.shift(); |
| 113 | + const formatRow = request.formatRow || defaultFormatRow(columnNames); |
133 | 114 | yield { |
134 | 115 | blockNumber: data.block_height, |
135 | | - result: result.slice(1), |
136 | | - } |
| 116 | + result: result.map(formatRow), |
| 117 | + }; |
137 | 118 | } |
138 | 119 | } finally { |
139 | | - eventSource.close() |
140 | | - } |
141 | | -} |
142 | | - |
143 | | -export type QuerySingleLiveOptions<FormattedRow> = QuerySingleLiveRawOptions & { |
144 | | - formatRow: (row: string[]) => FormattedRow |
145 | | -} |
146 | | - |
147 | | -export async function* querySingleLive<FormattedRow>( |
148 | | - { formatRow, ...options }: QuerySingleLiveOptions<FormattedRow> |
149 | | -): AsyncGenerator<QuerySingleData<FormattedRow>> { |
150 | | - for await (const { blockNumber, result } of querySingleLiveRaw(options)) { |
151 | | - yield { |
152 | | - blockNumber, |
153 | | - result: result.map(formatRow), |
154 | | - } |
| 120 | + eventSource.close(); |
155 | 121 | } |
156 | 122 | } |
0 commit comments