From cd2b80cd2a4a14aeb041244c386cab60b81978c7 Mon Sep 17 00:00:00 2001 From: sphinxrave <62570796+sphinxrave@users.noreply.github.com> Date: Tue, 8 Dec 2020 04:08:01 -0800 Subject: [PATCH] add channel cache & fix etag --- apps/client-api/routes/v1/channels.js | 19 +++++++++++++++++-- apps/client-api/routes/v1/live.js | 4 ++-- consts/index.js | 2 +- 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/apps/client-api/routes/v1/channels.js b/apps/client-api/routes/v1/channels.js index 1551edf..286c2c4 100644 --- a/apps/client-api/routes/v1/channels.js +++ b/apps/client-api/routes/v1/channels.js @@ -1,16 +1,26 @@ const { Op } = require('sequelize'); const { Router } = require('express'); const { db } = require('../../../../modules'); -const { ORGANIZATIONS } = require('../../../../consts'); +const { ORGANIZATIONS, CACHE_TTL } = require('../../../../consts'); const { asyncMiddleware } = require('../../middleware/error'); const { limitChecker } = require('../../middleware/filters'); const { RESPONSE_FIELDS } = require('../../../../consts/v1_consts'); +const cacheService = require('../../services/CacheService'); const router = new Router(); router.get('/', limitChecker, asyncMiddleware(async (req, res) => { const { limit = 25, offset = 0, sort = 'id', order = 'asc', name } = req.query; + const cacheKey = (limit || offset || sort || order || name) + ? `channel-${limit}-${offset}-${sort}-${order}-${name}` : 'channel'; + + const cache = await cacheService.getStringFromCache(cacheKey); // nonnull indicates cached. + res.setHeader('Content-Type', 'application/json'); + if (cache) { + return res.send(cache); + } + const { rows, count } = await db.Channel.findAndCountAll({ attributes: RESPONSE_FIELDS.CHANNEL, where: { @@ -43,7 +53,12 @@ router.get('/', limitChecker, asyncMiddleware(async (req, res) => { }); }); - res.json(results); + const resultsJSON = JSON.stringify(results); + cacheService.saveStringToCache(cacheKey, resultsJSON, CACHE_TTL.CHANNELS); + + res.send( + resultsJSON, + ); })); router.get('/:id', asyncMiddleware(async (req, res) => { diff --git a/apps/client-api/routes/v1/live.js b/apps/client-api/routes/v1/live.js index 13b55d8..c3afa8a 100644 --- a/apps/client-api/routes/v1/live.js +++ b/apps/client-api/routes/v1/live.js @@ -22,9 +22,9 @@ router.get('/', asyncMiddleware(async (req, res) => { res.setHeader('Content-Type', 'application/json'); if (cache) { - return res.end(cache); + return res.send(cache); } - return res.end( + return res.send( await computeLive(cacheKey, channel_id, max_upcoming_hours, lookback_hours, hide_channel_desc, channel_simple), ); })); diff --git a/consts/index.js b/consts/index.js index 0b6ecf5..0b4dff8 100644 --- a/consts/index.js +++ b/consts/index.js @@ -23,7 +23,7 @@ exports.STATUSES = { exports.CACHE_TTL = { LIVE: 20, - CHANNELS: 6 * 60 * 60, // 1 hour + CHANNELS: 30 * 60, // 30 minutes COMMENTS: 2 * 60, // 2 minutes };