forked from djyde/cusdis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.server.ts
96 lines (88 loc) · 2.55 KB
/
utils.server.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
import { PrismaClient } from '@prisma/client'
import { UserSession } from './service'
import { getSession as nextAuthGetSession } from 'next-auth/client'
import * as Sentry from '@sentry/node'
import * as Tracing from '@sentry/tracing'
type EnvVariable = string | undefined
export const resolvedConfig = {
useLocalAuth: process.env.USERNAME && process.env.PASSWORD,
useGithub: process.env.GITHUB_ID && process.env.GITHUB_SECRET,
jwtSecret: process.env.JWT_SECRET,
isHosted: process.env.IS_HOSTED === 'true',
host: process.env.HOST || 'https://cusdis.com',
umami: {
id: process.env.UMAMI_ID as EnvVariable,
src: process.env.UMAMI_SRC as EnvVariable,
},
google: {
id: process.env.GOOGLE_ID as EnvVariable,
secret: process.env.GOOGLE_SECRET as EnvVariable,
},
smtp: {
host: process.env.SMTP_HOST as EnvVariable,
port: Number((process.env.SMTP_PORT as EnvVariable) || '587'),
secure: Boolean((process.env.SMTP_SECURE as EnvVariable) || 'true'),
auth: {
user: process.env.SMTP_USER as EnvVariable,
pass: process.env.SMTP_PASSWORD as EnvVariable,
},
senderAddress:
(process.env.SMTP_SENDER as EnvVariable) ||
'Cusdis Notification<[email protected]>',
},
sendgrid: {
apiKey: process.env.SENDGRID_API_KEY as EnvVariable,
},
posthog: {
apiKey: process.env.POSTHOG_API_KEY as EnvVariable,
},
sentry: {
dsn: process.env.SENTRY_DSN as EnvVariable,
},
}
export const singleton = async <T>(id: string, fn: () => Promise<T>) => {
if (process.env.NODE_ENV === 'production') {
return await fn()
} else {
if (!global[id]) {
global[id] = await fn()
}
return global[id] as T
}
}
export const singletonSync = <T>(id: string, fn: () => T) => {
if (process.env.NODE_ENV === 'production') {
return fn()
} else {
if (!global[id]) {
global[id] = fn()
}
return global[id] as T
}
}
export const prisma = singletonSync('prisma', () => {
return new PrismaClient()
})
export const sentry = singletonSync('sentry', () => {
if (resolvedConfig.sentry.dsn) {
Sentry.init({
dsn: resolvedConfig.sentry.dsn,
tracesSampleRate: 1.0,
})
return Sentry
}
})
export function initMiddleware(middleware) {
return (req, res) =>
new Promise((resolve, reject) => {
middleware(req, res, (result) => {
if (result instanceof Error) {
return reject(result)
}
return resolve(result)
})
})
}
export const getSession = async (req) => {
return (await nextAuthGetSession({ req })) as UserSession
}