-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommon.ts
72 lines (66 loc) · 1.68 KB
/
common.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
export const queryEnv = async (
envKey: string,
defaultValue: string | (() => Promise<string>),
): Promise<string> => {
if (Deno.permissions) {
const { state } = await Deno.permissions.query({
name: 'env',
variable: envKey,
})
if (state !== 'granted') {
if (typeof defaultValue === 'function') {
return await defaultValue()
} else {
return defaultValue
}
}
}
return Deno.env.get(envKey) ||
(typeof defaultValue === 'function' ? await defaultValue() : defaultValue)
}
export class EnvError extends Error {
}
export const requireEnv = async (envKey: string): Promise<string> => {
if (Deno.permissions) {
const { state } = await Deno.permissions.query({
name: 'env',
variable: envKey,
})
if (state !== 'granted') {
throw new EnvError(
`Did not have permission to read environment variable ${envKey}`,
)
}
}
const result = Deno.env.get(envKey)
if (result === undefined) {
throw new EnvError(
`Environment variable ${envKey} not set`,
)
}
return result
}
export const jsonResponse = (
object: any,
additionalResponseOptions?: ResponseInit,
) => {
const headers = Object.assign({}, additionalResponseOptions?.headers || {}, {
headers: {
'content-type': 'application/json; charset=utf8',
},
})
const options = Object.assign({}, additionalResponseOptions, { headers })
return new Response(JSON.stringify(object), options)
}
export class HttpError extends Error {
status: number
constructor(message: string, name: string, status = 500) {
super(message)
this.name = name
this.status = status
}
toResponse() {
const { name, status, message } = this
return jsonResponse({ id: name, status, message }, { status: status })
}
}