index.ts 2.59 KB
Newer Older
Hanadi's avatar
Hanadi committed
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
import express from "express";
import cron from "node-cron";
import {HereClient} from "./src/here/HereClient";
import {FrostClient} from "./src/frost/FrostClient";
import {GeoProximity} from "./src/here/DataTypes";
import {error, info} from "./src/logger/logger";

const app = express();
const PORT = 8089;

const geoProximity: GeoProximity = {
    latitude: 48.791348,
    longitude: 9.190342,
    distance: 3000
};

if (!process.env.HERE_API_KEY) {
    throw new Error("HERE_API_KEY environment variable should be present!");
}

if (!process.env.FROST_URL) {
    throw new Error("FROST_URL environment variable should be present!");
}

const hereClient = new HereClient(process.env.HERE_API_KEY);
const frostClient = new FrostClient(process.env.FROST_URL);

async function triggerJob(forceUpdateLocations: boolean = false) {
    const now = new Date().getTime();
    return hereClient.flow(geoProximity)
        .then(flowResponse => frostClient.mapAndInsertHereFlowResponse(flowResponse, forceUpdateLocations))
        .then(insertedObservations => ({
            status: 200,
            success: true,
            millis: new Date().getTime() - now,
            insertedObservations
        }))
        .catch((err: Error) => {
            error(err.message, err);
            return {
                ...err,
                insertedObservations: "Unknown",
                status: 500,
                success: false,
                message: err.message,
                name: err.name,
                stack: err.stack,
                millis: new Date().getTime() - now
            };
        });
}

// Routes
app.get("/", (req, res) => res.send("Healthy!"));

app.get("/here", (req, res) => {
    hereClient.flow(geoProximity)
        .then(body => res.send(body))
        .catch(err => console.error(err));
});

app.get("/trigger-job", (req, res) => {
    info("Received trigger-job request");
    const forceUpdateLocations = !!req.query.forceUpdateLocations
    triggerJob(forceUpdateLocations).then(result => {
        res.status(result.status).send(result);
        info(`trigger-job request completed after ${result.millis} ms with status ${result.status}.`);
    });
});

cron.schedule("*/5 * * * *", () => {
    info("Triggering job");
    triggerJob().then(result => {
        if (result.success)
            info(`Job executed after ${result.millis} ms. Inserted observations: ${result.insertedObservations}.`);
        else
            info(`Job execution failed after ${result.millis} ms.`);
    });
});

// Start Application
app.listen(PORT, () => {
    info(`⚡️[server]: Server is running at http://localhost:${PORT}`);
});