This repository has been archived by the owner on Mar 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
82 lines (75 loc) · 1.95 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
const rp = require('request-promise')
const snx = require('synthetix')
const Decimal = require('decimal.js')
const getPriceData = async (synth) => {
try {
return await rp({
url: 'https://min-api.cryptocompare.com/data/price',
qs: {
tsyms: 'USD',
fsym: synth.symbol
},
json: true
})
} catch (error) {
throw error.message
}
}
const calculateIndex = (indexes) => {
let value = new Decimal(0)
try {
indexes.forEach(i => {
const price = i.priceData.USD
if (price <= 0)
throw 'invalid price'
value = value.plus(new Decimal(i.units).times(new Decimal(price)))
})
} catch (error) {
throw error.message
}
return value.toNumber()
}
const createRequest = async (input, callback) => {
const asset = input.data.asset || 'sCEX'
const datas = snx.getSynths({ network: 'mainnet' }).filter(({ index, inverted }) => index && !inverted)
const data = datas.find(d => d.name.toLowerCase() === asset.toLowerCase())
try {
await Promise.all(data.index.map(async (synth) => {
synth.priceData = await getPriceData(synth)
}))
data.result = calculateIndex(data.index)
callback(200, {
jobRunID: input.id,
data: data,
result: data.result,
statusCode: 200
})
} catch (error) {
callback(500, {
jobRunID: input.id,
status: 'errored',
error: error,
statusCode: 500
})
}
}
exports.gcpservice = (req, res) => {
createRequest(req.body, (statusCode, data) => {
res.status(statusCode).send(data)
})
}
exports.handler = (event, context, callback) => {
createRequest(event, (statusCode, data) => {
callback(null, data)
})
}
exports.handlerv2 = (event, context, callback) => {
createRequest(JSON.parse(event.body), (statusCode, data) => {
callback(null, {
statusCode: statusCode,
body: JSON.stringify(data),
isBase64Encoded: false
})
})
}
module.exports.createRequest = createRequest