cache.ts 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import express from 'express'
  2. import { HttpStatusCode } from '@peertube/peertube-models'
  3. import { ApiCache, APICacheOptions } from './shared/index.js'
  4. const defaultOptions: APICacheOptions = {
  5. excludeStatus: [
  6. HttpStatusCode.FORBIDDEN_403,
  7. HttpStatusCode.NOT_FOUND_404
  8. ]
  9. }
  10. export function cacheRoute (duration: string) {
  11. const instance = new ApiCache(defaultOptions)
  12. return instance.buildMiddleware(duration)
  13. }
  14. export function cacheRouteFactory (options: APICacheOptions = {}) {
  15. const instance = new ApiCache({ ...defaultOptions, ...options })
  16. return { instance, middleware: instance.buildMiddleware.bind(instance) }
  17. }
  18. // ---------------------------------------------------------------------------
  19. export function buildPodcastGroupsCache (options: {
  20. channelId: number
  21. }) {
  22. return 'podcast-feed-' + options.channelId
  23. }
  24. export function buildAPVideoChaptersGroupsCache (options: {
  25. videoId: number | string
  26. }) {
  27. return 'ap-video-chapters-' + options.videoId
  28. }
  29. // ---------------------------------------------------------------------------
  30. export const videoFeedsPodcastSetCacheKey = [
  31. (req: express.Request, res: express.Response, next: express.NextFunction) => {
  32. if (req.query.videoChannelId) {
  33. res.locals.apicacheGroups = [ buildPodcastGroupsCache({ channelId: req.query.videoChannelId }) ]
  34. }
  35. return next()
  36. }
  37. ]
  38. export const apVideoChaptersSetCacheKey = [
  39. (req: express.Request, res: express.Response, next: express.NextFunction) => {
  40. if (req.params.id) {
  41. res.locals.apicacheGroups = [ buildAPVideoChaptersGroupsCache({ videoId: req.params.id }) ]
  42. }
  43. return next()
  44. }
  45. ]