@defra/lis-hubs-infra-core 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@defra/lis-hubs-infra-core",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "Shared hub mechanics for livestock platform.",
5
5
  "main": "src/index.js",
6
6
  "repository": {
@@ -34,6 +34,7 @@
34
34
  "@defra/lis-hubs-infra-registry": "^0.3.0",
35
35
  "@elastic/ecs-pino-format": "1.5.0",
36
36
  "@hapi/h2o2": "10.0.4",
37
+ "@hapi/wreck": "^18.1.2",
37
38
  "hapi-pino": "13.0.0",
38
39
  "pino": "10.1.0",
39
40
  "pino-pretty": "13.1.3"
@@ -0,0 +1,174 @@
1
+ import Wreck from '@hapi/wreck'
2
+
3
+ import * as requestContext from './request-context.js'
4
+ import { getServiceBaseUrl } from './get-service-base-url.js'
5
+
6
+ const BAD_REQUEST = 400
7
+ const UNPROCESSABLE_ENTITY = 422
8
+
9
+ /**
10
+ * A generic Wreck wrapper for a BE4FE or other upstream service, shared
11
+ * across spokes and hubs. It resolves its own baseUrl via getServiceBaseUrl,
12
+ * so a consumer only supplies the environment and the target service's name.
13
+ * Subclass it and add named methods that call
14
+ * _get()/_post()/_put()/_patch()/_delete() with a path.
15
+ */
16
+ export class BaseClient {
17
+ /** @protected */
18
+ _baseUrl
19
+
20
+ /** @protected */
21
+ _apiKey
22
+
23
+ /** @protected */
24
+ _apiKeyHeader
25
+
26
+ /** @protected */
27
+ _timeout
28
+
29
+ /**
30
+ * @param {{ environment: string, serviceName: string, port?: number, apiKey?: string, apiKeyHeader?: string, timeout?: number }} options
31
+ */
32
+ constructor({
33
+ environment,
34
+ serviceName,
35
+ port,
36
+ apiKey,
37
+ apiKeyHeader,
38
+ timeout
39
+ }) {
40
+ this._baseUrl = getServiceBaseUrl(environment, serviceName, port).origin
41
+ this._apiKey = apiKey
42
+ this._apiKeyHeader = apiKeyHeader
43
+ this._timeout = timeout
44
+ }
45
+
46
+ /**
47
+ * @protected
48
+ * @param {string} path Path relative to baseUrl
49
+ * @param {object} [options] Wreck request options
50
+ * @returns {Promise<object>} the Wreck result ({ res, payload })
51
+ */
52
+ _get(path, options) {
53
+ return this._request('GET', path, this._buildOptions(options))
54
+ }
55
+
56
+ /**
57
+ * @protected
58
+ * @param {string} path Path relative to baseUrl
59
+ * @param {object} [options] Wreck request options
60
+ * @returns {Promise<object>} the Wreck result ({ res, payload })
61
+ */
62
+ _post(path, options) {
63
+ return this._request('POST', path, this._buildOptions(options))
64
+ }
65
+
66
+ /**
67
+ * @protected
68
+ * @param {string} path Path relative to baseUrl
69
+ * @param {object} [options] Wreck request options
70
+ * @returns {Promise<object>} the Wreck result ({ res, payload })
71
+ */
72
+ _put(path, options) {
73
+ return this._request('PUT', path, this._buildOptions(options))
74
+ }
75
+
76
+ /**
77
+ * @protected
78
+ * @param {string} path Path relative to baseUrl
79
+ * @param {object} [options] Wreck request options
80
+ * @returns {Promise<object>} the Wreck result ({ res, payload })
81
+ */
82
+ _patch(path, options) {
83
+ return this._request('PATCH', path, this._buildOptions(options))
84
+ }
85
+
86
+ /**
87
+ * @protected
88
+ * @param {string} path Path relative to baseUrl
89
+ * @param {object} [options] Wreck request options
90
+ * @returns {Promise<object>} the Wreck result ({ res, payload })
91
+ */
92
+ _delete(path, options) {
93
+ return this._request('DELETE', path, this._buildOptions(options))
94
+ }
95
+
96
+ /**
97
+ * @protected
98
+ * @param {object} [options] caller-supplied Wreck request options
99
+ * @returns {object} Wreck request options with baseUrl/json/timeout/headers applied
100
+ */
101
+ _buildOptions(options = {}) {
102
+ return {
103
+ baseUrl: this._baseUrl,
104
+ json: true,
105
+ timeout: this._timeout,
106
+ ...options,
107
+ headers: this._buildHeaders(options.headers)
108
+ }
109
+ }
110
+
111
+ /**
112
+ * @protected
113
+ * @param {object} [callerHeaders] headers supplied on this call
114
+ * @returns {object} correlation, api key and caller headers merged
115
+ */
116
+ _buildHeaders(callerHeaders) {
117
+ const headers = { ...requestContext.getHeaders() }
118
+
119
+ if (this._apiKey) {
120
+ headers[this._apiKeyHeader] = this._apiKey
121
+ }
122
+
123
+ return { ...headers, ...callerHeaders }
124
+ }
125
+
126
+ /**
127
+ * @protected
128
+ * @param {string} method HTTP method
129
+ * @param {string} path Path relative to baseUrl
130
+ * @param {object} options Wreck request options
131
+ * @returns {Promise<object>} the Wreck result ({ res, payload })
132
+ */
133
+ async _request(method, path, options) {
134
+ let res
135
+
136
+ try {
137
+ res = await Wreck.request(method, path, options)
138
+ } catch (error) {
139
+ throw this.#parseError(error.output?.statusCode, error.data?.payload)
140
+ }
141
+
142
+ let payload
143
+
144
+ try {
145
+ payload = await Wreck.read(res, options)
146
+ } catch {
147
+ throw this.#parseError(res.statusCode)
148
+ }
149
+
150
+ if (res.statusCode >= BAD_REQUEST) {
151
+ throw this.#parseError(res.statusCode, payload)
152
+ }
153
+
154
+ return { res, payload }
155
+ }
156
+
157
+ #parseError(statusCode, payload) {
158
+ let message
159
+
160
+ if (payload?.error?.code) {
161
+ message = `${payload.error.code} - ${payload.error.message}`
162
+ } else if (payload?.detail || payload?.title) {
163
+ message = `${payload.status} - ${payload.detail || payload.title}`
164
+ } else if (statusCode === UNPROCESSABLE_ENTITY) {
165
+ message = 'Validation failed'
166
+ } else {
167
+ message = `Request failed - ${statusCode}`
168
+ }
169
+
170
+ const error = new Error(message)
171
+ error.statusCode = statusCode
172
+ return error
173
+ }
174
+ }
@@ -0,0 +1,262 @@
1
+ import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest'
2
+
3
+ import Wreck from '@hapi/wreck'
4
+
5
+ import * as requestContext from './request-context.js'
6
+ import { getServiceBaseUrl } from './get-service-base-url.js'
7
+ import { BaseClient } from './base-client.js'
8
+
9
+ vi.mock('./request-context.js')
10
+ vi.mock('./get-service-base-url.js')
11
+
12
+ const mocks = {
13
+ requestContextGetHeaders: vi.mocked(requestContext.getHeaders),
14
+ getServiceBaseUrl: vi.mocked(getServiceBaseUrl)
15
+ }
16
+
17
+ function createClient(options = {}) {
18
+ return new BaseClient({
19
+ environment: 'local',
20
+ serviceName: 'lis-be4fe-cattle-home',
21
+ port: 8085,
22
+ ...options
23
+ })
24
+ }
25
+
26
+ beforeEach(() => {
27
+ mocks.requestContextGetHeaders.mockReturnValue({
28
+ 'x-correlation-id': 'correlation-1',
29
+ 'x-cdp-request-id': 'correlation-1'
30
+ })
31
+ mocks.getServiceBaseUrl.mockReturnValue(new URL('http://localhost:8085'))
32
+ })
33
+
34
+ afterEach(() => {
35
+ vi.restoreAllMocks()
36
+ })
37
+
38
+ describe('BaseClient constructor', () => {
39
+ test('it resolves its baseUrl via getServiceBaseUrl', async () => {
40
+ // Arrange
41
+ const client = createClient()
42
+ vi.spyOn(Wreck, 'request').mockResolvedValue({ statusCode: 200 })
43
+ vi.spyOn(Wreck, 'read').mockResolvedValue({})
44
+
45
+ // Act
46
+ await client._get('api/users/user-1/cphs')
47
+
48
+ // Assert
49
+ expect(mocks.getServiceBaseUrl).toHaveBeenCalledWith(
50
+ 'local',
51
+ 'lis-be4fe-cattle-home',
52
+ 8085
53
+ )
54
+ expect(Wreck.request.mock.calls[0][2].baseUrl).toBe('http://localhost:8085')
55
+ })
56
+ })
57
+
58
+ describe('request verbs', () => {
59
+ test.each([
60
+ ['_get', 'GET'],
61
+ ['_post', 'POST'],
62
+ ['_put', 'PUT'],
63
+ ['_patch', 'PATCH'],
64
+ ['_delete', 'DELETE']
65
+ ])(
66
+ 'it sends %s requests via Wreck.request with the api key and correlation headers',
67
+ async (method, httpMethod) => {
68
+ // Arrange
69
+ const client = createClient({
70
+ apiKey: 'test-api-key',
71
+ apiKeyHeader: 'x-api-key',
72
+ timeout: 5000
73
+ })
74
+ const res = { statusCode: 200 }
75
+ const request = vi.spyOn(Wreck, 'request').mockResolvedValue(res)
76
+ const read = vi.spyOn(Wreck, 'read').mockResolvedValue({ data: [] })
77
+
78
+ // Act
79
+ const result = await client[method]('api/users/user-1/cphs')
80
+
81
+ // Assert
82
+ expect(request).toHaveBeenCalledTimes(1)
83
+ const [calledMethod, path, options] = request.mock.calls[0]
84
+ expect(calledMethod).toBe(httpMethod)
85
+ expect(path).toBe('api/users/user-1/cphs')
86
+ expect(options.baseUrl).toBe('http://localhost:8085')
87
+ expect(options.json).toBe(true)
88
+ expect(options.timeout).toBe(5000)
89
+ expect(options.headers).toEqual({
90
+ 'x-correlation-id': 'correlation-1',
91
+ 'x-cdp-request-id': 'correlation-1',
92
+ 'x-api-key': 'test-api-key'
93
+ })
94
+ expect(read).toHaveBeenCalledWith(res, options)
95
+ expect(result).toEqual({ res, payload: { data: [] } })
96
+ }
97
+ )
98
+
99
+ test('it omits the api key header when no api key is configured', async () => {
100
+ // Arrange
101
+ const client = createClient()
102
+ vi.spyOn(Wreck, 'request').mockResolvedValue({ statusCode: 200 })
103
+ vi.spyOn(Wreck, 'read').mockResolvedValue({ data: [] })
104
+
105
+ // Act
106
+ await client._get('api/users/user-1/cphs')
107
+
108
+ // Assert
109
+ expect(Wreck.request.mock.calls[0][2].headers).toEqual({
110
+ 'x-correlation-id': 'correlation-1',
111
+ 'x-cdp-request-id': 'correlation-1'
112
+ })
113
+ })
114
+
115
+ test('it lets per-call headers override the defaults', async () => {
116
+ // Arrange
117
+ const client = createClient({
118
+ apiKey: 'test-api-key',
119
+ apiKeyHeader: 'x-api-key'
120
+ })
121
+ vi.spyOn(Wreck, 'request').mockResolvedValue({ statusCode: 200 })
122
+ vi.spyOn(Wreck, 'read').mockResolvedValue({})
123
+
124
+ // Act
125
+ await client._get('api/cattle/UK123', {
126
+ headers: { 'x-api-key': 'override-key' }
127
+ })
128
+
129
+ // Assert
130
+ expect(Wreck.request.mock.calls[0][2].headers['x-api-key']).toBe(
131
+ 'override-key'
132
+ )
133
+ })
134
+ })
135
+
136
+ describe('error handling', () => {
137
+ test('it throws using the error payload when the response is non-2xx', async () => {
138
+ // Arrange
139
+ const client = createClient()
140
+ vi.spyOn(Wreck, 'request').mockResolvedValue({ statusCode: 404 })
141
+ vi.spyOn(Wreck, 'read').mockResolvedValue({
142
+ error: { code: 'not_found', message: 'CPH not found' }
143
+ })
144
+
145
+ // Act
146
+ let result, error
147
+ try {
148
+ result = await client._get('api/cphs/missing/cattle')
149
+ } catch (e) {
150
+ error = e
151
+ }
152
+
153
+ // Assert
154
+ expect(result).not.toBeDefined()
155
+ expect(error).toBeInstanceOf(Error)
156
+ expect(error.message).toBe('not_found - CPH not found')
157
+ expect(error.statusCode).toBe(404)
158
+ })
159
+
160
+ test('it throws using the ProblemDetails payload when the response is non-2xx', async () => {
161
+ // Arrange
162
+ const client = createClient()
163
+ vi.spyOn(Wreck, 'request').mockResolvedValue({ statusCode: 404 })
164
+ vi.spyOn(Wreck, 'read').mockResolvedValue({
165
+ status: 404,
166
+ title: 'Not Found',
167
+ detail: 'CPH not found'
168
+ })
169
+
170
+ // Act
171
+ let error
172
+ try {
173
+ await client._get('api/cphs/missing/cattle')
174
+ } catch (e) {
175
+ error = e
176
+ }
177
+
178
+ // Assert
179
+ expect(error).toBeInstanceOf(Error)
180
+ expect(error.message).toBe('404 - CPH not found')
181
+ })
182
+
183
+ test('it throws a generic validation error for a 422 response', async () => {
184
+ // Arrange
185
+ const client = createClient()
186
+ vi.spyOn(Wreck, 'request').mockResolvedValue({ statusCode: 422 })
187
+ vi.spyOn(Wreck, 'read').mockResolvedValue({
188
+ PropertyName: ['must not be empty']
189
+ })
190
+
191
+ // Act
192
+ let error
193
+ try {
194
+ await client._post('api/cattle')
195
+ } catch (e) {
196
+ error = e
197
+ }
198
+
199
+ // Assert
200
+ expect(error).toBeInstanceOf(Error)
201
+ expect(error.message).toBe('Validation failed')
202
+ })
203
+
204
+ test('it falls back to a status-only message for an unrecognised error payload', async () => {
205
+ // Arrange
206
+ const client = createClient()
207
+ vi.spyOn(Wreck, 'request').mockResolvedValue({ statusCode: 503 })
208
+ vi.spyOn(Wreck, 'read').mockResolvedValue(null)
209
+
210
+ // Act
211
+ let error
212
+ try {
213
+ await client._get('api/cphs/missing/cattle')
214
+ } catch (e) {
215
+ error = e
216
+ }
217
+
218
+ // Assert
219
+ expect(error).toBeInstanceOf(Error)
220
+ expect(error.message).toBe('Request failed - 503')
221
+ })
222
+
223
+ test('it throws when Wreck.request itself throws', async () => {
224
+ // Arrange
225
+ const client = createClient()
226
+ const wreckError = new Error('socket hang up')
227
+ wreckError.output = { statusCode: 503 }
228
+ wreckError.data = { payload: null }
229
+ vi.spyOn(Wreck, 'request').mockRejectedValue(wreckError)
230
+
231
+ // Act
232
+ let error
233
+ try {
234
+ await client._get('api/users/user-1/cphs')
235
+ } catch (e) {
236
+ error = e
237
+ }
238
+
239
+ // Assert
240
+ expect(error).toBeInstanceOf(Error)
241
+ expect(error.message).toBe('Request failed - 503')
242
+ })
243
+
244
+ test('it throws when the response body cannot be read', async () => {
245
+ // Arrange
246
+ const client = createClient()
247
+ vi.spyOn(Wreck, 'request').mockResolvedValue({ statusCode: 200 })
248
+ vi.spyOn(Wreck, 'read').mockRejectedValue(new Error('Invalid JSON'))
249
+
250
+ // Act
251
+ let error
252
+ try {
253
+ await client._get('api/users/user-1/cphs')
254
+ } catch (e) {
255
+ error = e
256
+ }
257
+
258
+ // Assert
259
+ expect(error).toBeInstanceOf(Error)
260
+ expect(error.message).toBe('Request failed - 200')
261
+ })
262
+ })
package/src/index.js CHANGED
@@ -6,3 +6,4 @@ export * as requestContext from './request-context.js'
6
6
  export { logger } from './logging/index.js'
7
7
  export { createProxyPlugin } from './proxy-plugin.js'
8
8
  export { getServiceBaseUrl } from './get-service-base-url.js'
9
+ export { BaseClient } from './base-client.js'