Set Cache-Control headers in route controllers

Signed-off-by: Fred Boniface <fred@fjla.uk>
This commit is contained in:
Fred Boniface 2024-04-24 20:07:24 +01:00
parent c698187cdf
commit dad9f46d86
9 changed files with 32 additions and 16 deletions

9
app.js
View File

@ -1,7 +1,4 @@
// OwlBoard - © Fred Boniface 2022-2023 - Licensed under GPLv3 (or later) // OwlBoard - © Fred Boniface 2022-2023 - Licensed under GPLv3 (or later)
import { setCacheHeaders } from "./src/middlewares/setHeaders.middlewares";
// Please see the included LICENSE file // Please see the included LICENSE file
const mode = process.env.NODE_ENV || "development"; const mode = process.env.NODE_ENV || "development";
@ -78,15 +75,15 @@ app.use("/api/v1/auth/test", authenticate, (req, res) =>
}) })
); // Returns 401 if auth failed, 200 if successful. ); // Returns 401 if auth failed, 200 if successful.
// Post middleware
app.use(setCacheHeaders)
// Number of proxies: // Number of proxies:
app.set("trust proxy", 4); app.set("trust proxy", 4);
mode === "development" mode === "development"
? app.get("/api/v1/ip", (req, res) => res.send(req.ip)) ? app.get("/api/v1/ip", (req, res) => res.send(req.ip))
: null; : null;
// Disable etags
app.set('etag', false)
// Start Express // Start Express
app.listen(srvPort, srvListen, (error) => { app.listen(srvPort, srvListen, (error) => {
if (!error) { if (!error) {

View File

@ -4,6 +4,7 @@ const log = require("../utils/logs.utils");
async function post(req, res, next) { async function post(req, res, next) {
try { try {
log.out(`issueControllers.post: Request Body: ${JSON.stringify(req.body)}`); log.out(`issueControllers.post: Request Body: ${JSON.stringify(req.body)}`);
setCache(res, "no-store")
res.json(await issue.processor(req.body)); res.json(await issue.processor(req.body));
} catch (err) { } catch (err) {
console.error("Controller Error", err.message); console.error("Controller Error", err.message);

View File

@ -1,5 +1,7 @@
const ldb = require("../services/ldb.services"); const ldb = require("../services/ldb.services");
import { setCache } from "../utils/cacheHeader.utils";
async function getTrain(req, res, next) { async function getTrain(req, res, next) {
// API v2 Only // API v2 Only
if (!req.isAuthed) { if (!req.isAuthed) {
@ -7,6 +9,7 @@ async function getTrain(req, res, next) {
err.status = 401; err.status = 401;
throw err; throw err;
} }
setCache(res, "private", 180)
let type = req.params.searchType; let type = req.params.searchType;
let id = req.params.id; let id = req.params.id;
try { try {
@ -42,11 +45,14 @@ async function getStation(req, res, next) {
err.status = 401; err.status = 401;
return next(err); return next(err);
} }
setCache(res, "public", 120)
res.json(await ldb.get(id, true)); res.json(await ldb.get(id, true));
} else { } else {
setCache(res, "public", 240)
res.json(await ldb.get(id, false)); res.json(await ldb.get(id, false));
} }
} catch (err) { } catch (err) {
setCache(res, "no-store")
console.error("Unknown Error", err.message); console.error("Unknown Error", err.message);
err.status = 500; err.status = 500;
next(err); next(err);

View File

@ -1,5 +1,6 @@
import { Request, Response, NextFunction } from "express"; import { Request, Response, NextFunction } from "express";
import { findPisByOrigDest, findPisByCode } from "../services/pis.services"; import { findPisByOrigDest, findPisByCode } from "../services/pis.services";
import { setCache } from "../utils/cacheHeader.utils";
async function byStartEndCRS(req: Request, res: Response, next: NextFunction) { async function byStartEndCRS(req: Request, res: Response, next: NextFunction) {
// if (!req.isAuthed) { // if (!req.isAuthed) {
@ -10,6 +11,7 @@ async function byStartEndCRS(req: Request, res: Response, next: NextFunction) {
try { try {
let startCrs = req.params.startCrs; let startCrs = req.params.startCrs;
let endCrs = req.params.endCrs; let endCrs = req.params.endCrs;
setCache(res, "public", 600)
res.json(await findPisByOrigDest(startCrs, endCrs)); res.json(await findPisByOrigDest(startCrs, endCrs));
} catch (err: any) { } catch (err: any) {
console.error("Unknown Error", err.message); console.error("Unknown Error", err.message);

View File

@ -1,5 +1,7 @@
/* API V2 Exclusive Controller */ /* API V2 Exclusive Controller */
import { setCache } from "../utils/cacheHeader.utils";
const ldb = require("../services/ldb.services"); const ldb = require("../services/ldb.services");
const find = require("../services/find.services"); const find = require("../services/find.services");
@ -7,6 +9,7 @@ async function getReasonCode(req, res, next) {
try { try {
const code = req.params.code; const code = req.params.code;
if (code === "all") { if (code === "all") {
setCache(res, "public", 604800)
res.json(await ldb.getReasonCodeList()); res.json(await ldb.getReasonCodeList());
next; next;
} }
@ -23,6 +26,7 @@ async function getLocationReference(req, res, next) {
try { try {
const searchType = req.params.searchType; const searchType = req.params.searchType;
const id = req.params.id; const id = req.params.id;
setCache(res, "public", 604800)
switch (searchType) { switch (searchType) {
case "name": case "name":
res.json(await find.name(id)); res.json(await find.name(id));

View File

@ -1,8 +1,11 @@
import { setCache } from "../utils/cacheHeader.utils";
const stat = require("../services/stats.services"); const stat = require("../services/stats.services");
async function versions(req, res, next) { async function versions(req, res, next) {
// API v2 // API v2
try { try {
setCache(res, "public", 60)
res.json(await stat.getVersions()); res.json(await stat.getVersions());
} catch (err) { } catch (err) {
console.error("Controller Error", err); console.error("Controller Error", err);
@ -14,6 +17,7 @@ async function versions(req, res, next) {
async function statistics(req, res, next) { async function statistics(req, res, next) {
// Api v2 // Api v2
try { try {
setCache(res, "public", 60)
res.json(await stat.statistics()); res.json(await stat.statistics());
} catch (err) { } catch (err) {
console.error("Controller Error", err); console.error("Controller Error", err);

View File

@ -1,3 +1,4 @@
import { setCache } from "../utils/cacheHeader.utils";
import { logger } from "../utils/logger.utils"; import { logger } from "../utils/logger.utils";
const train = require("../services/trainService.services"); const train = require("../services/trainService.services");
@ -32,9 +33,11 @@ async function get(req, res, next) {
try { try {
switch (searchType) { switch (searchType) {
case "headcode": case "headcode":
setCache(res, "private", 1800)
res.json(await train.findByHeadcode(id, date)); res.json(await train.findByHeadcode(id, date));
break; break;
case "byTrainUid": case "byTrainUid":
setCache(res, "private", 1800)
res.json(await train.findByTrainUid(id, date)); res.json(await train.findByTrainUid(id, date));
break; break;
default: default:

View File

@ -1,10 +0,0 @@
import { NextFunction, Request, Response } from "express";
export function setCacheHeaders(req: Request, res: Response, next: NextFunction) {
if (res.cacheType && res.cacheSecs) {
const cacheCtlHeader = `${res.cacheType}, max-age=${res.cacheSecs}`;
res.setHeader('Cache-Control', cacheCtlHeader)
}
res.send();
}

View File

@ -0,0 +1,9 @@
import type { Response } from "express"
export function setCache(res: Response, type="private", time=120): void {
if (type === "no-store") {
res.setHeader('Cache-Control', 'no-store')
return
}
res.setHeader('Cache-Control', `${type}, max-age=${time}`)
}