71 lines
2.8 KiB
JavaScript
71 lines
2.8 KiB
JavaScript
import { buildLocalizedPath, getLocaleCodes } from '../i18n/index.js';
|
|
/** Resolve a doc's path in one locale (root for home). Null if no slug there. */ function pathForLocale(doc, locale, config, homeSlug) {
|
|
const slugField = doc.slug;
|
|
const slug = typeof slugField === 'string' ? slugField : slugField && typeof slugField === 'object' ? slugField[locale] : undefined;
|
|
if (!slug) {
|
|
return null;
|
|
}
|
|
return buildLocalizedPath({
|
|
config,
|
|
homeSlug,
|
|
locale,
|
|
slugs: {
|
|
[locale]: slug
|
|
}
|
|
}) ?? null;
|
|
}
|
|
/**
|
|
* Builds afterChange + afterDelete hooks that revalidate a page's ISR cache when
|
|
* an editor saves or deletes it — so changes appear immediately instead of
|
|
* waiting for the revalidate window. Without this, ISR means editors wait; with
|
|
* it, ISR is usable for a CMS.
|
|
*
|
|
* Handles every locale, the root (home), AND a changed slug (revalidates both the
|
|
* old and new path so neither goes stale). revalidatePath is injected — the
|
|
* plugin never imports next/cache (safe under generate:importmap / plain Node).
|
|
*
|
|
* // in your Media/Pages collection config, from a project file that CAN import next/cache:
|
|
* import { revalidatePath } from 'next/cache'
|
|
* import { buildRevalidateHook } from '@intecion/ipal-kit'
|
|
* const { afterChange, afterDelete } = buildRevalidateHook({ revalidatePath, config: i18nConfig })
|
|
* // hooks: { afterChange: [afterChange], afterDelete: [afterDelete] }
|
|
*/ export function buildRevalidateHook({ config, homeSlug, revalidatePath }) {
|
|
const locales = getLocaleCodes(config);
|
|
const afterChange = ({ doc, previousDoc })=>{
|
|
const seen = new Set();
|
|
for (const locale of locales){
|
|
// New path.
|
|
const newPath = pathForLocale(doc, locale, config, homeSlug);
|
|
if (newPath && !seen.has(newPath)) {
|
|
revalidatePath(newPath);
|
|
seen.add(newPath);
|
|
}
|
|
// Old path, if the slug changed — so the old URL doesn't serve stale content.
|
|
if (previousDoc) {
|
|
const oldPath = pathForLocale(previousDoc, locale, config, homeSlug);
|
|
if (oldPath && oldPath !== newPath && !seen.has(oldPath)) {
|
|
revalidatePath(oldPath);
|
|
seen.add(oldPath);
|
|
}
|
|
}
|
|
}
|
|
return doc;
|
|
};
|
|
const afterDelete = ({ doc })=>{
|
|
const seen = new Set();
|
|
for (const locale of locales){
|
|
const path = pathForLocale(doc, locale, config, homeSlug);
|
|
if (path && !seen.has(path)) {
|
|
revalidatePath(path);
|
|
seen.add(path);
|
|
}
|
|
}
|
|
return doc;
|
|
};
|
|
return {
|
|
afterChange,
|
|
afterDelete
|
|
};
|
|
}
|
|
|
|
//# sourceMappingURL=buildRevalidateHook.js.map
|