🎨 make the code less shit to read

This commit is contained in:
ryzetech 2023-01-23 12:43:59 +01:00
parent 9b65bd5419
commit ce19124286

52
app.js
View file

@ -44,16 +44,7 @@ let root = {
let app = express();
/* leaving this here for reference
app.options('/graphql', function (req, res) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS');
res.send(200);
});
*/
app.use(cors());
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
@ -75,20 +66,31 @@ async function loop() {
console.log(new Date(), "Checking for spaces...");
let changecount = 0;
for (const space of spaces) {
//console.log(`Checking ${space.id}...`);
let response = await checkSpace(space);
//console.log(`Space ${space.id} is ${o ? "open" : "closed"}`);
if (typeof response.open === "undefined") {
console.error(`The space ${space.id} might not be reachable. Please check the endpoint.`);
continue;
}
if (JSON.stringify(response) != JSON.stringify(cache.get(space.id))) {
cache.set(space.id, response);
// update or create the space in the database
let update = await prisma.space.upsert({
where: { id: space.id },
update: { open: response.open, lastChange: response.lastchange },
create: { id: space.id, open: response.open, lastChange: response.lastchange, name: space.name }
update: {
open: response.open,
lastChange: response.lastchange
},
create: {
id: space.id,
open: response.open,
lastChange: response.lastchange,
name: space.name,
}
});
changecount++;
}
}
@ -99,20 +101,34 @@ async function loop() {
async function checkSpace(space) {
let response, data, open;
let lastchange = null;
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}`); }
}
catch (e) {
console.error(`The space ${space.id} might not be reachable. Please check the endpoint. Error: ${e}`);
}
// Check if the space is using the SpaceAPI standard
if (!space.path) {
try {
open = data.state.open;
lastchange = new Date(data.state.lastchange*1000);
}
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.`); }
catch {
console.error(`The space ${space.id} is not using the SpaceAPI standard. Please specify a path.`);
}
}
else {
try {
// Query the JSONPath. If the expected value is not set, assume true or a similar value like 1.
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, lastchange };
}