| 170 | } |
| 171 | |
| 172 | async function requestRouter( |
| 173 | router: Router, |
| 174 | path: string, |
| 175 | options: { method?: string; body?: Record<string, string> | string; headers?: Record<string, string> } = {}, |
| 176 | ) { |
| 177 | const server = http.createServer(createAppForRouter(router)); |
| 178 | |
| 179 | await new Promise<void>((resolve, reject) => { |
| 180 | server.on('error', reject); |
| 181 | server.listen(0, resolve); |
| 182 | }); |
| 183 | |
| 184 | const { port } = server.address() as AddressInfo; |
| 185 | let encodedBody: string | undefined; |
| 186 | |
| 187 | if (typeof options.body === 'string') { |
| 188 | encodedBody = options.body; |
| 189 | } else if (options.body) { |
| 190 | encodedBody = new URLSearchParams(options.body).toString(); |
| 191 | } |
| 192 | |
| 193 | try { |
| 194 | const response = await fetch(`http://127.0.0.1:${port}${path}`, { |
| 195 | method: options.method ?? 'GET', |
| 196 | headers: { |
| 197 | 'User-Agent': 'test', |
| 198 | ...options.headers, |
| 199 | }, |
| 200 | body: encodedBody, |
| 201 | }); |
| 202 | |
| 203 | const text = await response.text(); |
| 204 | let body; |
| 205 | |
| 206 | try { |
| 207 | body = text ? JSON.parse(text) : undefined; |
| 208 | } catch { |
| 209 | body = undefined; |
| 210 | } |
| 211 | |
| 212 | return { |
| 213 | body, |
| 214 | headers: response.headers, |
| 215 | status: response.status, |
| 216 | text, |
| 217 | }; |
| 218 | } finally { |
| 219 | await new Promise<void>((resolve, reject) => { |
| 220 | server.close((error) => (error ? reject(error) : resolve())); |
| 221 | }); |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | async function postForm( |
| 226 | router: Router, |