forked from SmartThingsCommunity/smartthings-core-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathendpoint-client.ts
More file actions
286 lines (253 loc) · 9.25 KB
/
endpoint-client.ts
File metadata and controls
286 lines (253 loc) · 9.25 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
import axios, { AxiosRequestConfig } from 'axios'
import qs from 'qs'
import { Authenticator } from './authenticator'
import { Logger, noLogLogger } from './logger'
export interface HttpClientHeaders {
[name: string]: string
}
export type HttpClientParamValue = string | string[] | number
export interface HttpClientParams {
[name: string]: HttpClientParamValue
}
export type HttpClientMethod =
| 'get' | 'GET'
| 'post' | 'POST'
| 'put' | 'PUT'
| 'patch' | 'PATCH'
| 'delete' | 'DELETE'
export interface SmartThingsURLProvider {
baseURL: string
authURL?: string
keyApiURL?: string
}
export const globalSmartThingsURLProvider: Required<SmartThingsURLProvider> = {
baseURL: 'https://api.smartthings.com',
authURL: 'https://auth-global.api.smartthings.com/oauth/token',
keyApiURL: 'https://key.smartthings.com',
}
export const chinaSmartThingsURLProvider: SmartThingsURLProvider = {
// When login auth flow is added for China, make authURL required again.
baseURL: 'https://api.samsungiotcloud.cn',
}
export interface EndpointClientConfig {
authenticator: Authenticator
urlProvider?: SmartThingsURLProvider
logger?: Logger
loggingId?: string
version?: string
headers?: HttpClientHeaders
locationId?: string
installedAppId?: string
/**
* You can use this to supply a method that can log RFC 2068 warning headers.
*
* The messages are parsed into `WarningFromHeader` but if for any reason that parsing
* fails, the headers are simply returned as a comma-separated string.
*/
warningLogger?: (warnings: WarningFromHeader[] | string) => void | Promise<void>
}
export interface ItemsList<T> {
items: T[]
_links?: {
next?: {
href: string
}
previous?: {
href: string
}
}
}
export interface EndpointClientRequestOptions <T> {
headerOverrides?: HttpClientHeaders
dryRun?: boolean
dryRunReturnValue?: T
}
/**
* Convert to string and scrub sensitive values like auth tokens
* Meant to be used before logging the request
*/
function scrubConfig(config: AxiosRequestConfig): string {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { paramsSerializer: _unused, ...cleanerConfig } = config
const message = JSON.stringify(cleanerConfig)
const bearerRegex = /"(Bearer [0-9a-f]{8})[0-9a-f-]{28}"/i
if (bearerRegex.test(message)) {
return message.replace(bearerRegex, '"$1-xxxx-xxxx-xxxx-xxxxxxxxxxxx"')
} else { // assume there is some other auth format and redact the entire header value
const authHeaderRegex = /"(Authorization":")([\s\S]*)"/i
return message.replace(authHeaderRegex, '"$1(redacted)"')
}
}
export interface WarningFromHeader {
code: number
agent: string
text: string
date?: string
}
/**
* Parses Axios comma-joined warning headers into individual warnings. If, for any reason, the
* header string cannot be parsed, it will be returned unchanged.
*
* This method does not handle escaped quotes inside quoted strings.
*/
export const parseWarningHeader = (header: string): WarningFromHeader[] | string => {
if (header === '') {
return []
}
const warnings = header.match(/[^, ]+ [^, ]+ "[^"]+"( "[^"]+")?/g)
if (!warnings) {
return header
}
let failed = false
const retVal = warnings.map(warning => {
const fields = warning.match(/^(?<code>\d+) (?<agent>[^ ]+) "(?<text>.*?)"( "(?<date>.*?)")?$/)
if (!fields) {
failed = true
return { code: 1, agent: '-', text: 'unused' }
}
const { code, agent, text, date } = fields.groups as
{ code: string; agent: string; text: string; date?: string }
return { code: parseInt(code), agent, text, date }
})
return failed ? header : retVal
}
export class EndpointClient {
private logger: Logger
constructor(public readonly basePath: string, public readonly config: EndpointClientConfig) {
this.logger = config.logger ? config.logger : noLogLogger
}
public setHeader(name: string, value: string): EndpointClient {
if (!this.config.headers) {
this.config.headers = {}
}
this.config.headers[name] = value
return this
}
public removeHeader(name: string): EndpointClient {
if (this.config.headers) {
delete this.config.headers[name]
}
return this
}
private url(path?: string): string {
if (path) {
if (path.startsWith('/')) {
return `${this.config.urlProvider?.baseURL}${path}`
} else if (path.startsWith('https://')) {
return path
}
return `${this.config.urlProvider?.baseURL}/${this.basePath}/${path}`
}
return `${this.config.urlProvider?.baseURL}/${this.basePath}`
}
public async request<T = unknown>(method: HttpClientMethod, path?: string,
data?: unknown, params?: HttpClientParams, options?: EndpointClientRequestOptions<T>): Promise<T> {
const headers: HttpClientHeaders = this.config.headers ? { ...this.config.headers } : {}
if (this.config.loggingId) {
headers['X-ST-CORRELATION'] = this.config.loggingId
}
if (this.config.version) {
const versionString = `application/vnd.smartthings+json;v=${this.config.version}`
// Prepare the accept header
if (typeof headers.Accept === 'undefined' || headers.Accept === 'application/json') {
headers.Accept = versionString
} else {
headers.Accept = `${versionString}, ${headers.Accept}`
}
}
const axiosConfig: AxiosRequestConfig = {
url: this.url(path),
method,
headers: options?.headerOverrides ? { ...headers, ...options.headerOverrides } : headers,
params,
data,
paramsSerializer: {
serialize: params => qs.stringify(params, { indices: false }),
},
}
const authHeaders = await this.config.authenticator.authenticate()
axiosConfig.headers = { ...axiosConfig.headers, ...authHeaders }
if (this.logger.isDebugEnabled()) {
this.logger.debug(`making axios request: ${scrubConfig(axiosConfig)}`)
}
if (options?.dryRun) {
if (options.dryRunReturnValue) {
return options.dryRunReturnValue
}
throw new Error('skipping request; dry run mode')
}
try {
const response = await axios.request(axiosConfig)
if (this.logger.isTraceEnabled()) {
this.logger.trace(`axios response ${response.status}: data=${JSON.stringify(response.data)}`)
}
if (response.headers?.warning && this.config.warningLogger) {
// warningLogger allows for return of a promise or just void for flexibility
// it's not important to us here that it finish.
// eslint-disable-next-line @typescript-eslint/no-floating-promises
this.config.warningLogger(parseWarningHeader(response.headers.warning))
}
return response.data
} catch (error) {
if (this.logger.isTraceEnabled()) {
// https://www.npmjs.com/package/axios#handling-errors
if (error.response) {
// server responded with non-200 response code
this.logger.trace(`axios response ${error.response.status}: data=${JSON.stringify(error.response.data)}`)
} else if (error.request) {
// server never responded
this.logger.trace(`no response from server for request ${JSON.stringify(error.request)}`)
} else {
this.logger.trace(`error making request: ${error.message}`)
}
}
if (error.response && error.response.status === 401 && this.config.authenticator.refresh) {
if (this.config.authenticator.acquireRefreshMutex) {
const release = await this.config.authenticator.acquireRefreshMutex()
try {
const newAuthHeaders = await this.config.authenticator.refresh(this.config)
axiosConfig.headers = { ...axiosConfig.headers, ...newAuthHeaders }
const response = await axios.request(axiosConfig)
return response.data
} finally {
release()
}
} else {
const newAuthHeaders = await this.config.authenticator.refresh(this.config)
axiosConfig.headers = { ...axiosConfig.headers, ...newAuthHeaders }
const response = await axios.request(axiosConfig)
return response.data
}
}
// Annotate message with SmartThings API error data
if (error.response && error.response.data) {
error.message = error.message + ': ' + JSON.stringify(error.response.data)
}
throw error
}
}
public async get<T = unknown>(path?: string, params?: HttpClientParams, options?: EndpointClientRequestOptions<T>): Promise<T> {
return this.request('get', path, undefined, params, options)
}
public post<T = unknown>(path?: string, data?: unknown, params?: HttpClientParams, options?: EndpointClientRequestOptions<T>): Promise<T> {
return this.request('post', path, data, params, options)
}
public put<T = unknown>(path?: string, data?: unknown, params?: HttpClientParams, options?: EndpointClientRequestOptions<T>): Promise<T> {
return this.request('put', path, data, params, options)
}
public patch<T = unknown>(path?: string, data?: unknown, params?: HttpClientParams, options?: EndpointClientRequestOptions<T>): Promise<T> {
return this.request('patch', path, data, params, options)
}
public delete<T = unknown>(path?: string, params?: HttpClientParams, options?: EndpointClientRequestOptions<T>): Promise<T> {
return this.request('delete', path, undefined, params, options)
}
public async getPagedItems<T = unknown>(path?: string, params?: HttpClientParams, options?: EndpointClientRequestOptions<ItemsList<T>>): Promise<T[]> {
let list = await this.get<ItemsList<T>>(path, params, options)
const result = list.items
while (list._links && list._links.next) {
list = await this.get<ItemsList<T>>(list._links.next.href, undefined, options)
result.push(...list.items)
}
return result
}
}