Skip to content

Commit 146bd92

Browse files
committed
feat: [v2] add batch requests to cms client (#415)
1 parent 7567586 commit 146bd92

File tree

5 files changed

+439
-56
lines changed

5 files changed

+439
-56
lines changed

docs/utils/cms-route.ts

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ export function cmsRoute(options: CMSRouteOptions) {
8585
return options.slug;
8686
}
8787
const slugParam = options.slugParam || 'slug';
88-
return params[slugParam] || 'index';
88+
return (params[slugParam] || 'index').replaceAll('/', '--');
8989
}
9090

9191
async function fetchData(
@@ -180,22 +180,22 @@ export function cmsRoute(options: CMSRouteOptions) {
180180
res.setHeader('cache-control', 'private');
181181
return ctx.render404();
182182
}
183+
const primaryDocId = `${options.collection}/${slug}`;
183184
const mode = String(req.query.preview) === 'true' ? 'draft' : 'published';
184185
const routeContext: CMSRouteContext = {req, slug, mode, cmsClient};
185186

186-
const translationsTags = ['common', `${options.collection}/${slug}`];
187-
if (options.translations) {
188-
const tags = options.translations(routeContext)?.tags || [];
189-
translationsTags.push(...tags);
190-
}
187+
const batchRequest = cmsClient.createBatchRequest({
188+
mode,
189+
translate: true,
190+
});
191+
batchRequest.addDoc(primaryDocId);
191192

192-
const [doc, translationsMap, data] = await Promise.all([
193-
cmsClient.getDoc<CMSDoc>(options.collection, slug, {
194-
mode,
195-
}),
196-
cmsClient.loadTranslations({tags: translationsTags}),
193+
const [batchRes, data] = await Promise.all([
194+
batchRequest.fetch(),
197195
fetchData(routeContext),
198196
]);
197+
const doc = batchRes.docs[primaryDocId];
198+
199199
if (!doc) {
200200
res.setHeader('cache-control', 'private');
201201
return ctx.render404();
@@ -215,8 +215,19 @@ export function cmsRoute(options: CMSRouteOptions) {
215215
req.get('x-country-code') ||
216216
req.get('x-appengine-country') ||
217217
null;
218-
const translations = translationsForLocale(translationsMap, locale);
219-
let props: any = {...data, req, locale, mode, slug, doc, country};
218+
219+
const i18nFallbacks = req.rootConfig.i18n?.fallbacks || {};
220+
const translationFallbackLocales = i18nFallbacks[locale] || [locale];
221+
const translations = batchRes.getTranslations(translationFallbackLocales);
222+
let props: any = {
223+
...data,
224+
req,
225+
locale,
226+
mode,
227+
slug,
228+
doc,
229+
country,
230+
};
220231
if (options.preRenderHook) {
221232
props = await options.preRenderHook(props, routeContext);
222233
}

0 commit comments

Comments
 (0)