SpaceCache/app.js

77 lines
2.2 KiB
JavaScript
Raw Normal View History

2023-01-18 20:01:58 +01:00
// load configs and spaces
2023-01-18 17:28:38 +01:00
const config = require("./config.json");
const spaces = require("./spaces.json");
2023-01-18 12:15:52 +01:00
2023-01-18 20:01:58 +01:00
// load modules
2023-01-18 17:28:38 +01:00
const { setInterval } = require("node:timers/promises");
const fetch = require("node-fetch");
2023-01-18 20:01:58 +01:00
const express = require("express");
const { graphqlHTTP } = require('express-graphql');
const { buildSchema } = require('graphql');
2023-01-18 17:28:38 +01:00
const NodeCache = require("node-cache");
2023-01-18 12:15:52 +01:00
const jp = require('jsonpath');
const { PrismaClient } = require('@prisma/client');
const prisma = new PrismaClient();
2023-01-18 12:15:52 +01:00
2023-01-18 20:01:58 +01:00
// set up things
2023-01-18 17:28:38 +01:00
const cache = new NodeCache({ stdTTL: config.checkperiod * 3 });
2023-01-18 12:15:52 +01:00
2023-01-18 20:01:58 +01:00
let schema = buildSchema(`
type Query {
isOpen(id: String): Boolean
}
2023-01-18 20:01:58 +01:00
`);
let root = {
2023-01-19 08:29:27 +01:00
isOpen({ id }) {
let open = cache.get(id);
return { open };
}
2023-01-18 20:01:58 +01:00
};
let app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
2023-01-18 20:01:58 +01:00
}));
app.listen(4000);
2023-01-18 20:01:58 +01:00
// CHECK LOOP
2023-01-18 17:28:38 +01:00
(async function () {
for await (const time of setInterval(config.checkperiod * 10)) {
console.log("Checking for spaces...");
2023-01-18 12:15:52 +01:00
for (const space of spaces) {
2023-01-18 17:28:38 +01:00
console.log(`Checking ${space.id}...`);
let o = await checkSpace(space);
console.log(`Space ${space.id} is ${o ? "open" : "closed"}`);
if (o !== cache.get(space.id)) {
cache.set(space.id, o);
let update = await prisma.space.upsert({
where: { id: space.id },
update: { open: o },
create: { id: space.id, open: o }
});
}
2023-01-18 12:15:52 +01:00
}
}
2023-01-18 17:28:38 +01:00
})();
2023-01-18 12:15:52 +01:00
2023-01-18 20:01:58 +01:00
// HELPER FUNCTIONS
2023-01-18 12:15:52 +01:00
async function checkSpace(space) {
2023-01-18 17:36:19 +01:00
let response, data, open;
try {
response = await fetch(space.endpoint);
data = await response.json();
} catch (e) { console.error(`The space ${space.id} might not be reachable. Please check the endpoint. Error: ${e}`); }
2023-01-18 12:15:52 +01:00
if (!space.path) {
try { open = data.state.open; }
catch { console.error(`The space ${space.id} is not using the SpaceAPI standard. Please specify a path.`); }
} else {
try { open = (jp.query(data, space.path) == (space.expected ? space.expected : true)); }
catch { console.error(`The space ${space.id} has an invalid JSONPath to the target value. Please use https://jsonpath.com/ to evaluate the path.`); }
}
return open;
}