From 0ddf0dd003e9c205c585bfe90a6dd86640ca6c07 Mon Sep 17 00:00:00 2001 From: Naz Date: Wed, 22 Feb 2023 15:31:05 +0800 Subject: [PATCH] Added simple non-expiring caching to Posts API refs https://github.com/TryGhost/Toolbox/issues/522 - The public posts "browse" endpoint is causing the most strain on the instance performance. Caching responses with small TTL would allow to reduce the amount of request processing. --- .../core/server/api/endpoints/posts-public.js | 1 + .../server/services/posts-public/service.js | 26 ++++++++++++++----- .../lib/PublicResourcesRepository.js | 2 +- 3 files changed, 21 insertions(+), 8 deletions(-) diff --git a/ghost/core/core/server/api/endpoints/posts-public.js b/ghost/core/core/server/api/endpoints/posts-public.js index 8e0e803d2a..a38aeabd73 100644 --- a/ghost/core/core/server/api/endpoints/posts-public.js +++ b/ghost/core/core/server/api/endpoints/posts-public.js @@ -13,6 +13,7 @@ module.exports = { docName: 'posts', browse: { + cache: postsPublicService.api?.cache, options: [ 'include', 'filter', diff --git a/ghost/core/core/server/services/posts-public/service.js b/ghost/core/core/server/services/posts-public/service.js index b8aa3c99a8..c370636249 100644 --- a/ghost/core/core/server/services/posts-public/service.js +++ b/ghost/core/core/server/services/posts-public/service.js @@ -12,17 +12,29 @@ class PostsPublicServiceWrapper { let postsCache; if (config.get('hostSettings:postsPublicCache:enabled')) { - postsCache = adapterManager.getAdapter('cache:postsPublic'); + const cache = adapterManager.getAdapter('cache:postsPublic'); + postsCache = new EventAwareCacheWrapper({ + cache: cache, + resetEvents: ['site.changed'], + eventRegistry: EventRegistry + }); } - const {PublicResourcesRepository} = require('@tryghost/public-resource-repository'); - - this.postsRepository = new PublicResourcesRepository({ - Model: Post, - cache: postsCache - }); + let cache; + if (postsCache) { + // @NOTE: exposing cache through getter and setter to not loose the context of "this" + cache = { + get() { + return postsCache.get(...arguments); + }, + set() { + return postsCache.set(...arguments); + } + }; + } this.api = { + cache: cache, browse: this.postsRepository.getAll.bind(this.postsRepository) }; } diff --git a/ghost/public-resource-repository/lib/PublicResourcesRepository.js b/ghost/public-resource-repository/lib/PublicResourcesRepository.js index b797200758..53546139c9 100644 --- a/ghost/public-resource-repository/lib/PublicResourcesRepository.js +++ b/ghost/public-resource-repository/lib/PublicResourcesRepository.js @@ -10,7 +10,7 @@ module.exports = class PublicResourcesRepository { /** * @param {object} deps * @param {object} deps.Model Bookshelf Model instance of TagPublic/Post/Author etc. - * @param {object} deps.cache cache instance + * @param {object} [deps.cache] cache instance */ constructor(deps) { this.#Model = deps.Model;