-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
214 lines (186 loc) · 5.51 KB
/
main.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
import { connect, dbStateMiddleware } from './db/mongodb.ts';
import { Ctx, getEndpoints } from './endpoints.ts';
import { applyMiddleware } from '@/middlewares/applyMiddleware.ts';
import { H } from 'hono/types';
import { Middleware as auth_validToken } from '@/middlewares/auth/validToken.ts';
import {
endTrace,
initTrace,
printTrace,
startTrace,
} from '@/lib/requestTracer.ts';
import { setMiddleware } from '@/lib/requestTracer.ts';
import { config } from 'https://deno.land/x/[email protected]/mod.ts';
import * as Sentry from 'npm:@sentry/node';
import { OpenAPIHono } from 'npm:@hono/zod-openapi';
import { apiReference } from 'npm:@scalar/hono-api-reference';
import * as v from 'npm:valibot';
import { openAPISpecs } from 'npm:hono-openapi';
import { addOpenAPIEndpoint, initOpenAPI, openAPI } from '@/lib/openAPI.ts';
import {
OpenAPIMethods,
type AddOpenAPIEndpointParams,
} from '@/lib/openAPI.types.ts';
import { serveStatic } from 'npm:@hono/node-server/serve-static'
config({ export: true, path: '.env.local' });
async function main() {
const endpoints = await getEndpoints();
// async, so we can wait for the connection to be established
connect();
const app = new OpenAPIHono();
// const v1 = new OpenAPIHono();
app.use('/public/*', serveStatic({ root: './' }))
// cors
app.use(async (c: Ctx, next) => {
c.res.headers.set('Access-Control-Allow-Origin', '*');
c.res.headers.set(
'Access-Control-Allow-Methods',
'GET, POST, PUT, DELETE, OPTIONS'
);
c.res.headers.set(
'Access-Control-Allow-Headers',
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
);
await next();
});
initOpenAPI({
title: 'SwiftBuddies API',
description: 'API for SwiftBuddies',
servers: [
{
url: 'https://swiftbuddies.deno.dev',
description: 'Production Server',
},
{ url: 'http://localhost:3000', description: 'Local Server' },
],
excludeMethods: ['options'],
});
Sentry.init({
dsn: Deno.env.get('SENTRY_DSN'),
tracesSampleRate: 1.0,
tracePropagationTargets: [
'localhost',
/^https:\/\/swiftbuddies.deno\.dev\/api/,
],
});
app.onError(async (err: Error, c) => {
console.error(err);
Sentry.captureException(err);
c.status(500);
return await c.json({ error: err.message });
});
app.use(async (c: Ctx, next) => {
initTrace(c);
await next();
printTrace(c);
});
app.use('/api/*', async (c: Ctx, next) => {
const res = await dbStateMiddleware(c, next);
return res;
});
for (const endpoint of endpoints) {
const handler = endpoint.handler;
const { path, middlewares, method, validation, openAPI } =
endpoint.endpoint;
// deno-lint-ignore no-explicit-any
const options = (path: string, ...handlers: H<any, any, any, any>[]) =>
app.on('OPTIONS', path, ...handlers);
// deno-lint-ignore no-explicit-any
const methods: Record<string, any> = {
GET: app.get.bind(app),
POST: app.post.bind(app),
PUT: app.put.bind(app),
DELETE: app.delete.bind(app),
PATCH: app.patch.bind(app),
OPTIONS: options,
};
if (!(method in methods)) {
console.warn(`Method ${method} not found`);
continue;
}
const steps: H[] = [];
const apiDoc: AddOpenAPIEndpointParams = {
path: path,
method: method.toLocaleLowerCase() as OpenAPIMethods,
description: openAPI?.description ?? '',
inputs: validation,
responses: openAPI?.responses ?? {},
tags: openAPI?.tags,
};
addOpenAPIEndpoint(apiDoc);
const middlewareList = [
...(openAPI ? [openAPI] : []),
...(middlewares ?? []),
'dataValidation',
];
for (const middleware of middlewareList) {
if (middleware === 'auth:validToken') {
steps.push(auth_validToken);
continue;
}
if (typeof middleware === 'string') {
const middlewareF = setMiddleware(middleware, async (c, next) => {
const middlewareData = await applyMiddleware({
ctx: c,
middleware,
endpoint: {
path,
middlewares,
validation,
method,
},
});
if (middlewareData.base.responseStatus === 'end') {
c.status(middlewareData.base.status);
const res = c.json(middlewareData.base.body);
return res;
}
if (!c.get(middleware)) {
c.set(middleware, {
middleware: middleware,
base: {},
user: middlewareData.user,
});
}
await next();
});
steps.push(middlewareF);
}
}
methods[method as keyof typeof methods](path, ...steps, async (c: Ctx) => {
startTrace(c, `${method} ${path}`);
const res = await handler(c, []);
endTrace(c, `${method} ${path}`);
return res;
});
}
app.get(
'/openapi',
openAPISpecs(app, {
documentation: {
info: {
title: 'Hono API',
version: '1.0.0',
description: 'Greeting API',
},
servers: [
{ url: 'http://localhost:3000', description: 'Local Server' },
],
},
})
);
app.get('/opendocs', (c) => {
return c.json(openAPI, 200);
});
app.get(
'/docs',
apiReference({
theme: 'saturn',
spec: { url: '/opendocs' },
favicon: '/public/favicon.ico',
pageTitle: 'SwiftBuddies API Docs',
})
);
await Deno.serve(app.fetch);
}
await main();