From b921a3fe9fc981faa377ff3fdf5ac25ad8b391b0 Mon Sep 17 00:00:00 2001 From: Alexander Horn Date: Sat, 9 Jan 2021 15:00:47 +0100 Subject: [PATCH] Add /api/mensa endpoint --- rogue-thi-app/package-lock.json | 13 +++++++++++++ rogue-thi-app/package.json | 3 ++- rogue-thi-app/pages/api/mensa.js | 31 +++++++++++++++++++++++++++++++ 3 files changed, 46 insertions(+), 1 deletion(-) create mode 100644 rogue-thi-app/pages/api/mensa.js diff --git a/rogue-thi-app/package-lock.json b/rogue-thi-app/package-lock.json index 355ab8b8..41b0872a 100644 --- a/rogue-thi-app/package-lock.json +++ b/rogue-thi-app/package-lock.json @@ -5427,6 +5427,11 @@ } } }, + "sax": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", + "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==" + }, "scheduler": { "version": "0.20.1", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.20.1.tgz", @@ -7080,6 +7085,14 @@ "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", "integrity": "sha1-tSQ9jz7BqjXxNkYFvA0QNuMKtp8=" }, + "xml-js": { + "version": "1.6.11", + "resolved": "https://registry.npmjs.org/xml-js/-/xml-js-1.6.11.tgz", + "integrity": "sha512-7rVi2KMfwfWFl+GpPg6m80IVMWXLRjO+PxTq7V2CDhoGak0wzYzFgUY2m4XJ47OGdXd8eLE8EmwfAmdjw7lC1g==", + "requires": { + "sax": "^1.2.4" + } + }, "xtend": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", diff --git a/rogue-thi-app/package.json b/rogue-thi-app/package.json index e8290953..6fc18b42 100644 --- a/rogue-thi-app/package.json +++ b/rogue-thi-app/package.json @@ -22,7 +22,8 @@ "react-bootstrap": "^1.4.0", "react-dom": "^17.0.1", "react-leaflet": "^3.0.5", - "react-placeholder": "^4.0.3" + "react-placeholder": "^4.0.3", + "xml-js": "^1.6.11" }, "devDependencies": { "eslint": "^7.15.0", diff --git a/rogue-thi-app/pages/api/mensa.js b/rogue-thi-app/pages/api/mensa.js new file mode 100644 index 00000000..e6330333 --- /dev/null +++ b/rogue-thi-app/pages/api/mensa.js @@ -0,0 +1,31 @@ +import xmljs from 'xml-js' +import MemoryCache from '../../lib/memory-cache' + +const CACHE_TTL = 60 * 60 * 1000 +const URL_DE = 'https://www.max-manager.de/daten-extern/sw-erlangen-nuernberg/xml/mensa-ingolstadt.xml' +const URL_EN = 'https://www.max-manager.de/daten-extern/sw-erlangen-nuernberg/xml/en/mensa-ingolstadt.xml' + +const cache = new MemoryCache({ ttl: CACHE_TTL }) + +async function fetchPlan (lang) { + const url = (lang || 'de') === 'de' ? URL_DE : URL_EN + + let plan = cache.get(url) + + if (!plan) { + const resp = await fetch(url) + plan = xmljs.xml2js(await resp.text(), { compact: true }) + + cache.set(url, plan) + } + + return plan +} + +export default async function handler (req, res) { + const plan = await fetchPlan(req.query.lang) + + res.statusCode = 200 + res.setHeader('Content-Type', 'application/json') + res.end(JSON.stringify(plan)) +}