Skip to content

Commit

Permalink
add channel cache & fix etag
Browse files Browse the repository at this point in the history
  • Loading branch information
sphinxrave committed Dec 8, 2020
1 parent d9d3e3b commit cd2b80c
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 5 deletions.
19 changes: 17 additions & 2 deletions apps/client-api/routes/v1/channels.js
Original file line number Diff line number Diff line change
@@ -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: {
Expand Down Expand Up @@ -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) => {
Expand Down
4 changes: 2 additions & 2 deletions apps/client-api/routes/v1/live.js
Original file line number Diff line number Diff line change
Expand Up @@ -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),
);
}));
Expand Down
2 changes: 1 addition & 1 deletion consts/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
};

Expand Down

0 comments on commit cd2b80c

Please sign in to comment.