This repository has been archived by the owner on Apr 16, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
64 lines (52 loc) · 1.79 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
const { NodeClient } = require('hs-client')
const express = require('express')
const host = process.env.HOST || 'localhost'
const port = Number(process.env.PORT) || 3100
const portal = process.env.PORTAL || 'https://siasky.net'
const hsdNetworkType = process.env.HSD_NETWORK || 'regtest'
const hsdHost = process.env.HSD_HOST || 'localhost'
const hsdPort = Number(process.env.HSD_PORT) || 12037
const hsdApiKey = process.env.HSD_API_KEY || 'foo'
const clientOptions = {
network: hsdNetworkType,
host: hsdHost,
port: hsdPort,
apiKey: hsdApiKey
}
const client = new NodeClient(clientOptions)
const hsdHandler = async (req, res) => {
try {
const { records } = await client.execute('getnameresource', [req.params.name])
console.log(`Received records: ${JSON.stringify(records)}`)
let resolved = records?.find(r => Boolean(r.address)).address
console.log(`Resolved: ${resolved}`)
if (isValidSkylink(resolved)) {
res.redirect(`${portal}/${resolved}`)
} else {
res.sendStatus(404)
}
} catch (e) {
res.status(500).json(e).end()
}
}
const SIA_LINK_RE = /^([a-zA-Z0-9-_]{46}.*)$/
// Checks if the given string is a valid Sia link.
function isValidSkylink(link) {
if (!link || link.length === 0) {
return false
}
return Boolean(link.match(SIA_LINK_RE))
}
const server = express()
server.get('/hsd/:name', hsdHandler)
// Handle all other routes.
server.use(function (req, res, next) {
if (!req.route)
return next(new Error('404'))
next()
})
server.listen(port, host, (error) => {
if (error) throw error
console.info(`API will look for HSD Server at ${hsdHost}:${hsdPort}, "${hsdNetworkType}" network.`)
console.info(`Server listening at http://${host}:${port}`)
})