From dd5fe9e7fd750c3752a2fceb8a4ddc42c1403da3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mathias=20T=C3=B8rhaug?= Date: Mon, 27 Jan 2025 19:10:01 +0100 Subject: [PATCH] fix: Add cache for sanity language query We had a issue where we would query sanity for supported languages for each field in our schemas. This would result in over 100 api requests on some pages, draining our total api requests --- studio/studioConfig.tsx | 32 ++++++++++++++++++++++---------- 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/studio/studioConfig.tsx b/studio/studioConfig.tsx index 10878e7b8..14dcdf398 100644 --- a/studio/studioConfig.tsx +++ b/studio/studioConfig.tsx @@ -1,10 +1,14 @@ import { colorInput } from "@sanity/color-input"; import { documentInternationalization } from "@sanity/document-internationalization"; import { visionTool } from "@sanity/vision"; +import { SanityClient } from "next-sanity"; import { WorkspaceOptions } from "sanity"; import { presentationTool } from "sanity/presentation"; import { structureTool } from "sanity/structure"; -import { internationalizedArray } from "sanity-plugin-internationalized-array"; +import { + Language, + internationalizedArray, +} from "sanity-plugin-internationalized-array"; import { media } from "sanity-plugin-media"; import { languageID } from "i18n/languageSchemaField"; @@ -17,6 +21,21 @@ import { legalDocumentID } from "./schemas/documents/admin/legalDocuments"; const SUPPORTED_LANGUAGES_QUERY = `*[_type == "languageSettings" && !(_id in path("drafts.*"))].languages[]{id, title}`; +let cachedSupportedLanguages: Promise | null = null; +//TODO: This might not be the perfect solution, but it works for now. +function getSupportedLanguages(client: SanityClient) { + if (!cachedSupportedLanguages) { + cachedSupportedLanguages = client + .fetch(SUPPORTED_LANGUAGES_QUERY) + .catch((err: Error) => { + cachedSupportedLanguages = null; // Reset cache on error + throw err; + }); + } + + return cachedSupportedLanguages; +} + const config: WorkspaceOptions = { name: "studio", title: "Studio", @@ -32,20 +51,13 @@ const config: WorkspaceOptions = { }), visionTool({ defaultApiVersion: apiVersion }), documentInternationalization({ - supportedLanguages: (client) => { - return client.fetch(SUPPORTED_LANGUAGES_QUERY); - }, + supportedLanguages: (client) => getSupportedLanguages(client), schemaTypes: [legalDocumentID], languageField: languageID, apiVersion, - // Optional. Adds UI for publishing all translations at once. Requires access to the Scheduling API - // https://www.sanity.io/docs/scheduling-api - // bulkPublish: true, }), internationalizedArray({ - languages: (client) => { - return client.fetch(SUPPORTED_LANGUAGES_QUERY); - }, + languages: (client) => getSupportedLanguages(client), fieldTypes: ["string", "richText", "seo", "text"], }), presentationTool({