-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathapp.ts
More file actions
94 lines (74 loc) · 2.24 KB
/
app.ts
File metadata and controls
94 lines (74 loc) · 2.24 KB
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
import process from 'node:process'
import { initLogger, LoggerFormat, LoggerLevel, useLogger } from '@guiiai/logg'
import { serve } from '@hono/node-server'
import { Hono } from 'hono'
import { cors } from 'hono/cors'
import { logger as honoLogger } from 'hono/logger'
import { createAuth } from './services/auth'
import { createDrizzle } from './services/db'
import { parseEnv } from './services/env'
import { getTrustedOrigin } from './utils/origin'
function createApp() {
initLogger(LoggerLevel.Debug, LoggerFormat.Pretty)
const app = new Hono<{
Variables: {
user: typeof auth.$Infer.Session.user | null
session: typeof auth.$Infer.Session.session | null
}
}>()
const env = parseEnv(process.env)
const logger = useLogger('app').useGlobalConfig()
const db = createDrizzle(env.DATABASE_URL)
const auth = createAuth(db, env)
db.execute('SELECT 1')
.then(() => {
logger.log('Connected to database')
})
.catch((err) => {
logger.withError(err).error('Failed to connect to database')
process.exit(1)
})
app.use(
'/api/auth/*', // or replace with "*" to enable cors for all routes
cors({
origin(origin: string) {
return getTrustedOrigin(origin)
},
credentials: true,
}),
)
app.use(honoLogger())
app.use('*', async (c, next) => {
const session = await auth.api.getSession({ headers: c.req.raw.headers })
if (!session) {
c.set('user', null)
c.set('session', null)
await next()
return
}
c.set('user', session.user)
c.set('session', session.session)
await next()
})
app.get('/session', (c) => {
const session = c.get('session')
const user = c.get('user')
if (!user)
return c.body(null, 401)
return c.json({
session,
user,
})
})
app.on(['POST', 'GET'], '/api/auth/*', (c) => {
return auth.handler(c.req.raw)
})
logger.withFields({ port: 3000 }).log('Server started')
return app
}
serve(createApp())
function handleError(error: unknown, type: string) {
useLogger().withError(error).error(type)
}
process.on('uncaughtException', error => handleError(error, 'Uncaught exception'))
process.on('unhandledRejection', error => handleError(error, 'Unhandled rejection'))