aboutsummaryrefslogtreecommitdiff
path: root/api/routes/getAKNSKey/index.js
blob: 5e78f8159a5e7d1674110d9bbbfe05fa8f1de873 (plain)
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
const { spawn } = require('child_process');
const fs = require('fs');
const config = require("../../config.js");

/*
 * Gets the local latest zblock AKA zlatest
 *
 * Returns:
 *     - JSON object
 *     { zlatest: "Qm..." }
 *
 */
function replyIfOkay(key, res)
{
    const program = "ak-ns";
    const command = spawn(program, ["-rj", key]);
    var buffer = "";
    command.stdout.on("data", data => {
        buffer += data;
    });
    command.stderr.on("data", data => {
        console.log(`stderr: ${data}`);
    });
    command.on('error', (error) => {
        console.log(`error: ${error.message}`);
    });
    command.on("close", code => {
        console.log(`child process ${program} exited with code ${code}`);
        if (code === 0){
            buffer = buffer.trim()
            res.writeHead(200, {'Content-Type': 'application/json'});
            res.end(`${buffer}`);
        } else {
            res.writeHead(404, {'Content-Type': 'application/json'});
            res.end({"error":"unreachable"});
        }
    });
}

function getAKNSKey(req, res)
{
    var args = req.url.split("/");
    var key = args[3];
    regex= /[a-fA-F0-9]{40}/
    if (regex.test(key))
    {
        key = key.toUpperCase();
        var path = config.akNSDir+"/"+key;
        try
        {
            if(fs.existsSync(path))
            {
                replyIfOkay(key, res)
            }
            else
            {
                res.writeHead(404, {'Content-Type': 'application/json'});
                res.end(JSON.stringify({"error":"not found"}));
            }
        }
        catch (error)
        {
            res.writeHead(404, {'Content-Type': 'application/json'});
            res.end(JSON.stringify({"error":error.message}));
        }
    }
    else
    {
        res.writeHead(404, {'Content-Type': 'application/json'});
        res.end(JSON.stringify({error:"No hash"}));
    }
}

module.exports = getAKNSKey;