|
| 1 | +import { Context, Middleware } from 'koa'; |
1 | 2 | import { HTTPError } from 'koajax'; |
2 | | -import { NextApiRequest, NextApiResponse } from 'next'; |
3 | | -import { githubOAuth2 } from 'next-ssr-middleware'; |
4 | 3 | import { ProxyAgent, setGlobalDispatcher } from 'undici'; |
5 | 4 |
|
6 | 5 | const { HTTP_PROXY } = process.env; |
7 | 6 |
|
8 | 7 | if (HTTP_PROXY) setGlobalDispatcher(new ProxyAgent(HTTP_PROXY)); |
9 | 8 |
|
10 | | -export type NextAPI = ( |
11 | | - req: NextApiRequest, |
12 | | - res: NextApiResponse, |
13 | | -) => Promise<any>; |
| 9 | +export const safeAPI: Middleware<any, any> = async (context: Context, next) => { |
| 10 | + try { |
| 11 | + return await next(); |
| 12 | + } catch (error) { |
| 13 | + if (!(error instanceof HTTPError)) { |
| 14 | + console.error(error); |
14 | 15 |
|
15 | | -export function safeAPI(handler: NextAPI): NextAPI { |
16 | | - return async (req, res) => { |
17 | | - try { |
18 | | - return await handler(req, res); |
19 | | - } catch (error) { |
20 | | - if (!(error instanceof HTTPError)) { |
21 | | - console.error(error); |
| 16 | + context.status = 400; |
22 | 17 |
|
23 | | - res.status(400); |
24 | | - |
25 | | - return res.send({ message: (error as Error).message }); |
26 | | - } |
27 | | - const { message, response } = error; |
28 | | - let { body } = response; |
29 | | - |
30 | | - res.status(response.status); |
31 | | - res.statusMessage = message; |
32 | | - |
33 | | - if (body instanceof ArrayBuffer) |
34 | | - try { |
35 | | - body = new TextDecoder().decode(new Uint8Array(body)); |
36 | | - console.error(body); |
37 | | - |
38 | | - body = JSON.parse(body); |
39 | | - console.error(body); |
40 | | - } catch { |
41 | | - // |
42 | | - } |
43 | | - res.send(body); |
| 18 | + return (context.body = { message: (error as Error).message }); |
44 | 19 | } |
45 | | - }; |
46 | | -} |
| 20 | + const { message, response } = error; |
| 21 | + let { body } = response; |
47 | 22 |
|
48 | | -const client_id = process.env.GITHUB_OAUTH_CLIENT_ID!, |
49 | | - client_secret = process.env.GITHUB_OAUTH_CLIENT_SECRET!; |
| 23 | + context.status = response.status; |
| 24 | + context.statusMessage = message; |
50 | 25 |
|
51 | | -export const ProxyBaseURL = 'https://chinese.fcc-cd.dev/proxy'; |
| 26 | + if (body instanceof ArrayBuffer) |
| 27 | + try { |
| 28 | + body = new TextDecoder().decode(new Uint8Array(body)); |
| 29 | + |
| 30 | + body = JSON.parse(body); |
| 31 | + } catch { |
| 32 | + // |
| 33 | + } |
| 34 | + console.error(JSON.stringify(body, null, 2)); |
52 | 35 |
|
53 | | -export const githubSigner = githubOAuth2({ |
54 | | - rootBaseURL: process.env.VERCEL ? undefined : `${ProxyBaseURL}/github.com/`, |
55 | | - client_id, |
56 | | - client_secret, |
57 | | - scopes: ['user:email', 'read:user', 'public_repo', 'read:project'], |
58 | | -}); |
| 36 | + context.body = body; |
| 37 | + } |
| 38 | +}; |
0 commit comments