diff --git a/src/cache.ts b/src/cache.ts index 3a2f56f..85a482a 100644 --- a/src/cache.ts +++ b/src/cache.ts @@ -1,11 +1,11 @@ -export class Cache { +export default class Cache { cachedData: any; lastUsed: Date; lifeTime: number; mensa: string; constructor() { - this.cachedData = {}; + this.cachedData = null; this.lastUsed = new Date(); this.lifeTime = 1000 * 30; this.mensa = ""; @@ -16,7 +16,7 @@ export class Cache { return null; } - if (this.cachedData === null) { + if (this.cachedData == null) { return null; } diff --git a/src/index.ts b/src/index.ts index 2b1a6e4..c7b88e0 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,32 +2,43 @@ import express, { Express, Request, Response} from "express"; import dotenv from "dotenv"; import cors from "cors"; -import bodyParser from "body-parser"; +import bodyParser, { text } from "body-parser"; import morgan from "morgan"; import fetch from './fetch.js'; +import Cache from './cache.js'; +import stripHtml from "./stripper.js"; dotenv.config(); -const app: Express = express().use(cors({ origin: '*' })).use(bodyParser.json()); +const app: Express = express().use(cors({ origin: '*' })); app.use(morgan('combined')) const port = process.env.PORT || 3000; const baseUrl = "https://www.imensa.de/"; +const cache = new Cache(); + app.get("/", (req: Request, res: Response) => { res.send("Mensa API"); }); -app.get("/api/:Ort/:Mensa", (req: Request, res: Response) => { +app.get("/api/:Ort", (req: Request, res: Response) => { if (req.params.Ort === null) { return res.send("Invalid request"); } - let url = baseUrl + req.params.Ort.toLowerCase(); - fetch(url).then((data) => { - res.send(data); - }); + let cachedData = cache.get(); + if (cachedData !== null) { + return res.send(cachedData); + }else { + let url = baseUrl + req.params.Ort.toLowerCase(); + fetch(url).then((data) => { + let stripedData = stripHtml(data); + cache.set(req.params.Ort, stripedData); + res.send(stripedData); + }); + } }); diff --git a/src/stripper.ts b/src/stripper.ts index e69de29..3af75db 100644 --- a/src/stripper.ts +++ b/src/stripper.ts @@ -0,0 +1,3 @@ +export default function stripHtml(html: string): string { + return html; +}