diff --git a/packages/server/modules/core/graph/resolvers/server.ts b/packages/server/modules/core/graph/resolvers/server.ts index b8cafa420e..7b80e443c6 100644 --- a/packages/server/modules/core/graph/resolvers/server.ts +++ b/packages/server/modules/core/graph/resolvers/server.ts @@ -9,11 +9,18 @@ import { getServerInfoFactory, updateServerInfoFactory, getPublicRolesFactory, - getPublicScopesFactory + getPublicScopesFactory, + getServerInfoFromCacheFactory, + storeServerInfoInCacheFactory } from '@/modules/core/repositories/server' import { db } from '@/db/knex' import { Resolvers } from '@/modules/core/graph/generated/graphql' +import { LRUCache } from 'lru-cache' +import { ServerInfo } from '@/modules/core/helpers/types' +const cache = new LRUCache({ max: 1, ttl: 60 * 1000 }) +const getServerInfoFromCache = getServerInfoFromCacheFactory({ cache }) +const storeServerInfoInCache = storeServerInfoInCacheFactory({ cache }) const getServerInfo = getServerInfoFactory({ db }) const updateServerInfo = updateServerInfoFactory({ db }) const getPublicRoles = getPublicRolesFactory({ db }) @@ -22,7 +29,11 @@ const getPublicScopes = getPublicScopesFactory({ db }) export = { Query: { async serverInfo() { - return await getServerInfo() + const cachedServerInfo = getServerInfoFromCache() + if (cachedServerInfo) return cachedServerInfo + const serverInfo = await getServerInfo() + storeServerInfoInCache({ serverInfo }) + return serverInfo } }, ServerInfo: { @@ -58,6 +69,9 @@ export = { const update = removeNullOrUndefinedKeys(args.info) await updateServerInfo(update) + // we're currently going to ignore, that this should be propagated to all + // backend instances, and going to rely on the TTL in the cache to propagate the changes + cache.clear() return true }, serverInfoMutations: () => ({}) diff --git a/packages/server/modules/core/repositories/server.ts b/packages/server/modules/core/repositories/server.ts index c24477755b..1360adba9b 100644 --- a/packages/server/modules/core/repositories/server.ts +++ b/packages/server/modules/core/repositories/server.ts @@ -18,6 +18,7 @@ import { getServerVersion } from '@/modules/shared/helpers/envHelper' import { Knex } from 'knex' +import { LRUCache } from 'lru-cache' const ServerConfig = buildTableHelper('server_config', [ 'id', @@ -38,6 +39,21 @@ const tables = { scopes: (db: Knex) => db(Scopes.name) } +const SERVER_CONFIG_CACHE_KEY = 'server_config' + +export const getServerInfoFromCacheFactory = + ({ cache }: { cache: LRUCache }) => + () => { + const serverInfo = cache.get(SERVER_CONFIG_CACHE_KEY) + return serverInfo ?? null + } + +export const storeServerInfoInCacheFactory = + ({ cache }: { cache: LRUCache }) => + ({ serverInfo }: { serverInfo: ServerInfo }) => { + cache.set(SERVER_CONFIG_CACHE_KEY, serverInfo) + } + export const getServerInfoFactory = (deps: { db: Knex }): GetServerInfo => async () => {