-
-
Notifications
You must be signed in to change notification settings - Fork 275
Expand file tree
/
Copy pathclient.ts
More file actions
80 lines (70 loc) · 2.07 KB
/
client.ts
File metadata and controls
80 lines (70 loc) · 2.07 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
import { getConfig } from '../../config'
import { getTenantConfig } from './tenant'
import { User, TenantConnection } from './connection'
import { ERRORS } from '@internal/errors'
interface ConnectionOptions {
host: string
tenantId: string
maxConnections?: number
headers?: Record<string, string | undefined | string[]>
method?: string
path?: string
user: User
superUser: User
disableHostCheck?: boolean
operation?: () => string | undefined
}
/**
* Creates a tenant specific knex client
* @param options
*/
export async function getPostgresConnection(options: ConnectionOptions): Promise<TenantConnection> {
const dbCredentials = await getDbCredentials(options.tenantId, options.host, {
disableHostCheck: options.disableHostCheck,
})
return await TenantConnection.create({
...dbCredentials,
...options,
})
}
async function getDbCredentials(
tenantId: string,
host: string | undefined,
options?: { disableHostCheck?: boolean }
) {
const {
isMultitenant,
databasePoolURL,
databaseURL,
databaseMaxConnections,
requestXForwardedHostRegExp,
} = getConfig()
let dbUrl = databasePoolURL || databaseURL
let maxConnections = databaseMaxConnections
let isExternalPool = Boolean(databasePoolURL)
if (isMultitenant) {
if (!tenantId) {
throw ERRORS.InvalidTenantId()
}
if (requestXForwardedHostRegExp && !options?.disableHostCheck) {
const xForwardedHost = host
if (typeof xForwardedHost !== 'string') {
throw ERRORS.InvalidXForwardedHeader('X-Forwarded-Host header is not a string')
}
if (!new RegExp(requestXForwardedHostRegExp).test(xForwardedHost)) {
throw ERRORS.InvalidXForwardedHeader(
'X-Forwarded-Host header does not match regular expression'
)
}
}
const tenant = await getTenantConfig(tenantId)
dbUrl = tenant.databasePoolUrl || tenant.databaseUrl
isExternalPool = Boolean(tenant.databasePoolUrl)
maxConnections = tenant.maxConnections ?? maxConnections
}
return {
dbUrl,
isExternalPool,
maxConnections,
}
}