@defra/lis-hubs-infra-core 0.1.0 → 0.2.0-lreg-358.alpha.2

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.1.0",
3
+ "version": "0.2.0-lreg-358.alpha.2",
4
4
  "description": "Shared hub mechanics for livestock platform.",
5
5
  "main": "src/index.js",
6
6
  "repository": {
package/src/index.js CHANGED
@@ -1,3 +1,5 @@
1
1
  export const HUB_TYPES = ['front-office', 'back-office']
2
2
 
3
3
  export const HUB_CORE_STATUS = 'scaffolded'
4
+
5
+ export * as requestContext from './request-context.js'
@@ -0,0 +1,73 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks'
2
+
3
+ const storage = new AsyncLocalStorage()
4
+
5
+ export const plugin = {
6
+ name: 'requestContext',
7
+ version: '1.0.0',
8
+ register(server) {
9
+ server.ext('onRequest', (request, h) => {
10
+ const store = new Map()
11
+
12
+ store.set(
13
+ 'correlation_id',
14
+ request.headers['x-cdp-request-id'] || crypto.randomUUID()
15
+ )
16
+
17
+ for (const cycle of ['_lifecycle', '_postCycle']) {
18
+ const original = request[cycle].bind(request)
19
+ request[cycle] = () => storage.run(store, original)
20
+ }
21
+ return h.continue
22
+ })
23
+ }
24
+ }
25
+
26
+ const getStore = () => {
27
+ const store = storage.getStore()
28
+ if (store === undefined) {
29
+ throw new Error('No request context available')
30
+ }
31
+ return store
32
+ }
33
+
34
+ /**
35
+ * Gets a value from the current request context.
36
+ * Returns null if no context is available or the key is not set.
37
+ *
38
+ * @param {string} key
39
+ * @returns {string | number | boolean | null}
40
+ */
41
+ export const get = (key) => storage.getStore()?.get(key) ?? null
42
+
43
+ /**
44
+ * Sets a primitive value in the current request context.
45
+ * Throws if called outside a request context.
46
+ *
47
+ * @param {string} key
48
+ * @param {string | number | boolean | null} value
49
+ * @returns {void}
50
+ */
51
+ export const set = (key, value) => {
52
+ getStore().set(key, value)
53
+ }
54
+
55
+ /**
56
+ * Removes a key from the current request context.
57
+ * Throws if called outside a request context.
58
+ *
59
+ * @param {string} key
60
+ * @returns {void}
61
+ */
62
+ export const clear = (key) => {
63
+ getStore().delete(key)
64
+ }
65
+
66
+ /**
67
+ * Removes all keys from the current request context.
68
+ * Throws if called outside a request context.
69
+ * @returns {void}
70
+ */
71
+ export const clearAll = () => {
72
+ getStore().clear()
73
+ }
@@ -0,0 +1,226 @@
1
+ import { AsyncLocalStorage } from 'node:async_hooks'
2
+ import { afterEach, describe, expect, test, vi } from 'vitest'
3
+
4
+ import { clear, clearAll, get, plugin, set } from './request-context.js'
5
+
6
+ const mocks = {
7
+ run: vi.spyOn(AsyncLocalStorage.prototype, 'run'),
8
+ getStore: vi.spyOn(AsyncLocalStorage.prototype, 'getStore')
9
+ }
10
+
11
+ function getStoreFromRequest(headers) {
12
+ const ext = vi.fn()
13
+ const server = { ext }
14
+
15
+ plugin.register(server)
16
+
17
+ const handler = ext.mock.calls[0][1]
18
+ const request = { headers, _lifecycle: vi.fn(), _postCycle: vi.fn() }
19
+
20
+ handler(request, { continue: Symbol('continue') })
21
+ request._lifecycle()
22
+
23
+ const [store] = mocks.run.mock.calls[0]
24
+ return store
25
+ }
26
+
27
+ describe('requestContext', () => {
28
+ afterEach(() => {
29
+ vi.resetAllMocks()
30
+ })
31
+
32
+ describe('plugin', () => {
33
+ test('it registers an onRequest extension', () => {
34
+ // Arrange
35
+ const ext = vi.fn()
36
+ const server = { ext }
37
+
38
+ // Act
39
+ plugin.register(server)
40
+
41
+ // Assert
42
+ expect(ext).toHaveBeenCalledWith('onRequest', expect.any(Function))
43
+ })
44
+
45
+ test('onRequest wraps _lifecycle and _postCycle in an ALS context and continues', () => {
46
+ // Arrange
47
+ const ext = vi.fn()
48
+ const server = { ext }
49
+ plugin.register(server)
50
+ const [[, handler]] = ext.mock.calls
51
+ const h = { continue: Symbol('continue') }
52
+ const lifecycle = vi.fn()
53
+ const postCycle = vi.fn()
54
+ const request = {
55
+ headers: {},
56
+ _lifecycle: lifecycle,
57
+ _postCycle: postCycle
58
+ }
59
+
60
+ // Act
61
+ const result = handler(request, h)
62
+
63
+ // Assert
64
+ expect(request._lifecycle).not.toBe(lifecycle)
65
+ expect(request._postCycle).not.toBe(postCycle)
66
+ request._lifecycle()
67
+ request._postCycle()
68
+ expect(mocks.run).toHaveBeenCalledTimes(2)
69
+ const [firstStore] = mocks.run.mock.calls[0]
70
+ const [secondStore] = mocks.run.mock.calls[1]
71
+ expect(firstStore).toBe(secondStore)
72
+ expect(firstStore).toBeInstanceOf(Map)
73
+ expect(result).toBe(h.continue)
74
+ })
75
+
76
+ test('onRequest stores correlation_id from the x-cdp-request-id header', () => {
77
+ // Arrange
78
+ // Act
79
+ const store = getStoreFromRequest({ 'x-cdp-request-id': 'cdp-1' })
80
+
81
+ // Assert
82
+ expect(store.get('correlation_id')).toBe('cdp-1')
83
+ })
84
+
85
+ test('onRequest generates a correlation_id when the header is missing', () => {
86
+ // Arrange
87
+ // Act
88
+ const store = getStoreFromRequest({})
89
+
90
+ // Assert
91
+ expect(typeof store.get('correlation_id')).toBe('string')
92
+ expect(store.get('correlation_id').length).toBeGreaterThan(0)
93
+ })
94
+ })
95
+
96
+ describe('get()', () => {
97
+ test('it returns null when there is no store', () => {
98
+ // Arrange
99
+ mocks.getStore.mockReturnValue(undefined)
100
+
101
+ // Act
102
+ const result = get('foo')
103
+
104
+ // Assert
105
+ expect(result).toBeNull()
106
+ })
107
+
108
+ test('it returns null when the key is not in the store', () => {
109
+ // Arrange
110
+ mocks.getStore.mockReturnValue(new Map())
111
+
112
+ // Act
113
+ const result = get('foo')
114
+
115
+ // Assert
116
+ expect(result).toBeNull()
117
+ })
118
+
119
+ test('it returns the value when the key is in the store', () => {
120
+ // Arrange
121
+ mocks.getStore.mockReturnValue(new Map([['foo', 'bar']]))
122
+
123
+ // Act
124
+ const result = get('foo')
125
+
126
+ // Assert
127
+ expect(result).toBe('bar')
128
+ })
129
+ })
130
+
131
+ describe('set()', () => {
132
+ test('it throws when there is no store', () => {
133
+ // Arrange
134
+ mocks.getStore.mockReturnValue(undefined)
135
+ let error
136
+
137
+ // Act
138
+ try {
139
+ set('foo', 'bar')
140
+ } catch (e) {
141
+ error = e
142
+ }
143
+
144
+ // Assert
145
+ expect(error).toBeInstanceOf(Error)
146
+ expect(error?.message).toBe('No request context available')
147
+ })
148
+
149
+ test('it sets the value on the store', () => {
150
+ // Arrange
151
+ const store = new Map()
152
+ mocks.getStore.mockReturnValue(store)
153
+
154
+ // Act
155
+ set('foo', 'bar')
156
+
157
+ // Assert
158
+ expect(store.get('foo')).toBe('bar')
159
+ })
160
+ })
161
+
162
+ describe('clear()', () => {
163
+ test('it throws when there is no store', () => {
164
+ // Arrange
165
+ mocks.getStore.mockReturnValue(undefined)
166
+ let error
167
+
168
+ // Act
169
+ try {
170
+ clear('foo')
171
+ } catch (e) {
172
+ error = e
173
+ }
174
+
175
+ // Assert
176
+ expect(error).toBeInstanceOf(Error)
177
+ expect(error?.message).toBe('No request context available')
178
+ })
179
+
180
+ test('it removes the key from the store', () => {
181
+ // Arrange
182
+ const store = new Map([['foo', 'bar']])
183
+ mocks.getStore.mockReturnValue(store)
184
+
185
+ // Act
186
+ clear('foo')
187
+
188
+ // Assert
189
+ expect(store.has('foo')).toBe(false)
190
+ })
191
+ })
192
+
193
+ describe('clearAll()', () => {
194
+ test('it throws when there is no store', () => {
195
+ // Arrange
196
+ mocks.getStore.mockReturnValue(undefined)
197
+ let error
198
+
199
+ // Act
200
+ try {
201
+ clearAll()
202
+ } catch (e) {
203
+ error = e
204
+ }
205
+
206
+ // Assert
207
+ expect(error).toBeInstanceOf(Error)
208
+ expect(error?.message).toBe('No request context available')
209
+ })
210
+
211
+ test('it removes all keys from the store', () => {
212
+ // Arrange
213
+ const store = new Map([
214
+ ['foo', 'bar'],
215
+ ['baz', 'qux']
216
+ ])
217
+ mocks.getStore.mockReturnValue(store)
218
+
219
+ // Act
220
+ clearAll()
221
+
222
+ // Assert
223
+ expect(store.size).toBe(0)
224
+ })
225
+ })
226
+ })