-
-
Notifications
You must be signed in to change notification settings - Fork 137
/
Copy pathutils.ts
61 lines (53 loc) · 1.6 KB
/
utils.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
import pgcs from 'pg-connection-string'
import { FastifyRequest } from 'fastify'
import { compile } from 'json-schema-to-typescript'
export const extractRequestForLogging = (request: FastifyRequest) => {
let pg: string = 'unknown'
try {
if (request.headers.pg) {
pg = pgcs.parse(request.headers.pg as string).host || pg
}
} catch (e: any) {
console.warn('failed to parse PG connstring for ' + request.url)
}
const additional = request.headers['x-supabase-info']?.toString() || ''
return {
method: request.method,
url: request.url,
pg,
opt: additional,
}
}
export function translateErrorToResponseCode(
error: { message: string },
defaultResponseCode = 400
): number {
if (error.message === 'Connection terminated due to connection timeout') {
return 504
} else if (error.message === 'sorry, too many clients already') {
return 503
}
return defaultResponseCode
}
export async function generateTypeFromCheckConstraint(
checkConstraints: string | null
): Promise<string> {
if (!checkConstraints) {
throw new Error('check constraint is empty')
}
if (typeof checkConstraints !== 'string') {
throw new Error('invalid input type')
}
const match = /jsonb?_matches_schema\(\'([\{|\[].*[\}|\]])/gms.exec(checkConstraints)
const extractedJsonStr = match ? match[1] : null
const jsonSchema = JSON.parse(extractedJsonStr ?? '{}')
const tsType = await compile(jsonSchema, 'Type', {
bannerComment: '',
style: {
singleQuote: true,
semi: false,
},
format: false
})
return tsType.replaceAll('export interface Type ', '')
}