UNPKG

2.07 kBJavaScriptView Raw
1import {
2 canPrefetch,
3 createPrefetchClient,
4 createClient,
5 getCache,
6 getInternal,
7 processCache,
8 modifyCache,
9 catchInvalidSignatureException
10} from '@middy/util'
11import {
12 ServiceDiscoveryClient,
13 DiscoverInstancesCommand
14} from '@aws-sdk/client-servicediscovery'
15
16const defaults = {
17 AwsClient: ServiceDiscoveryClient,
18 awsClientOptions: {},
19 awsClientAssumeRole: undefined,
20 awsClientCapture: undefined,
21 fetchData: {}, // { contextKey: {NamespaceName, ServiceName, HealthStatus} }
22 disablePrefetch: false,
23 cacheKey: 'cloud-map',
24 cacheKeyExpiry: {},
25 cacheExpiry: -1,
26 setToContext: false
27}
28
29const serviceDiscoveryMiddleware = (opts = {}) => {
30 const options = { ...defaults, ...opts }
31
32 const fetch = (request, cachedValues = {}) => {
33 const values = {}
34
35 for (const internalKey of Object.keys(options.fetchData)) {
36 if (cachedValues[internalKey]) continue
37
38 const command = new DiscoverInstancesCommand(
39 options.fetchData[internalKey]
40 )
41 values[internalKey] = client
42 .send(command)
43 .catch((e) => catchInvalidSignatureException(e, client, command))
44 .then((resp) => resp.Instances)
45 .catch((e) => {
46 const value = getCache(options.cacheKey).value ?? {}
47 value[internalKey] = undefined
48 modifyCache(options.cacheKey, value)
49 throw e
50 })
51 }
52
53 return values
54 }
55
56 let client
57 if (canPrefetch(options)) {
58 client = createPrefetchClient(options)
59 processCache(options, fetch)
60 }
61
62 const serviceDiscoveryMiddlewareBefore = async (request) => {
63 if (!client) {
64 client = await createClient(options, request)
65 }
66
67 const { value } = processCache(options, fetch, request)
68
69 Object.assign(request.internal, value)
70
71 if (options.setToContext) {
72 const data = await getInternal(Object.keys(options.fetchData), request)
73 if (options.setToContext) Object.assign(request.context, data)
74 }
75 }
76
77 return {
78 before: serviceDiscoveryMiddlewareBefore
79 }
80}
81export default serviceDiscoveryMiddleware