This repository has been archived by the owner on Feb 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
85 lines (77 loc) · 2.26 KB
/
index.js
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
const endpoint = process.env.ENGINE_ENDPOINT || process.env.coreAddr
const mesg = require('mesg-js').application({ endpoint })
const debug = require('debug')('marketplace')
const handleError = err => {
console.error(err)
process.exit(1)
}
// cache caches api response for endpoint with given content & 200 code.
const cache = async (endpoint, content) => mesg.executeTaskAndWaitResult({
serviceID: 'http-server',
taskKey: 'cache',
inputData: JSON.stringify({
method: 'get',
path: endpoint,
code: 200,
mimeType: 'application/json',
content: JSON.stringify(content),
})
})
const fetch = async (task, params = {}) => {
const { outputData } = await mesg.executeTaskAndWaitResult({
serviceID: 'marketplace',
taskKey: task,
inputData: JSON.stringify(params)
})
return JSON.parse(outputData)
}
const refreshAllCache = async () => {
const { services } = await fetch('listServices')
const servicesToCache = []
for (const service of services) {
const srv = await fetch('getService', { sid: service.sid })
await cache(`/services/${srv.sid}`, srv)
debug(`CACHE /services/${srv.sid}`)
servicesToCache.push(srv)
}
await cache('/services', servicesToCache)
debug('CACHE /services')
}
const main = async () => {
await refreshAllCache()
const events = [
'serviceCreated',
'serviceOfferCreated',
'serviceOfferDisabled',
'serviceOwnershipTransferred',
'servicePurchased',
'serviceVersionCreated'
]
events.forEach((eventKey) => {
mesg.listenEvent({ serviceID: 'marketplace', eventFilter: eventKey })
.on('data', refreshAllCache)
.on('error', handleError)
})
// serve 404 for all(*) other requests.
mesg.listenEvent({ serviceID: 'http-server', eventFilter: 'request' })
.on('data', async (event) => {
const data = JSON.parse(event.eventData)
const sessionID = data.sessionID
try {
await mesg.executeTaskAndWaitResult({
serviceID: 'http-server',
taskKey: 'completeSession',
inputData: JSON.stringify({ sessionID, code: 404 })
})
} catch (err) {
console.error('error while responding api request:', err)
}
})
.on('error', handleError)
}
try {
main()
} catch (e) {
console.error(e)
process.exit(0)
}