fixed Cache + implemented Cache

This commit is contained in:
Jan Barfuß 2023-12-20 01:15:23 +01:00
parent 268d3132d5
commit b8234748ad
3 changed files with 24 additions and 10 deletions

View File

@ -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;
}

View File

@ -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);
});
}
});

View File

@ -0,0 +1,3 @@
export default function stripHtml(html: string): string {
return html;
}