-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathexist-client.js
More file actions
65 lines (58 loc) · 2.03 KB
/
exist-client.js
File metadata and controls
65 lines (58 loc) · 2.03 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
import { Client, interceptors } from 'undici'
/**
* @typedef { import("undici").Client } Client
*/
/**
* @typedef {Object} ConnectionOptions
* @prop {string} user the user account name connecting to the database
* @prop {string} server full URL prefix for requests
* @prop {Object} headers base headers for requests
* @prop {boolean} secure indicates if connection is using an encrypted channel (https)
* @prop {boolean} [rejectUnauthorized=false] enforce valid SSL certs, if https: is used
* @prop {boolean} [throwOnError=true] controls if the client throws on error
*/
/**
* @typedef {Object} Connection
* @prop {Client} client underlying undici.Client instance
* @prop {string} user the user account name connecting to the database
* @prop {string} server full URL prefix for requests
* @prop {string} pathname path prefix that is used for requests
* @prop {boolean} secure indicates if connection is using an encrypted channel (https)
*/
const existRequestInterceptor = (basepath, baseheaders) => dispatch => {
return (opts, handler) => {
const { path, headers } = opts
opts.path = `${basepath}/${path}`
opts.headers = { ...headers, ...baseheaders }
return dispatch(opts, handler)
}
}
/**
* create a REST client to interact with an exist-db instance
* @param {ClientOptions} options the connection options
* @returns {Connection} undici.Client instance
*/
export function createExistClient ({ server, headers, rejectUnauthorized, user, secure, throwOnError = true }) {
const parsed = new URL(server)
// path prefix has to be passed in to interceptor
// client cannot work with anything other than clean origin
const { pathname } = parsed
parsed.pathname = '/'
const _client = new Client(parsed, {
connect: {
keepAlive: true,
rejectUnauthorized
}
})
.compose(existRequestInterceptor(pathname, headers))
const client = throwOnError
? _client.compose(interceptors.responseError({ throwOnError }))
: _client
return {
secure,
server,
user,
pathname,
client
}
}