feat(core-shared): add slugifyIfMissing hook
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { slugifyIfMissing } from "./slugify-if-missing";
|
||||
|
||||
describe("slugifyIfMissing", () => {
|
||||
it("derives slug from title on create when slug is empty", () => {
|
||||
const result = slugifyIfMissing({
|
||||
data: { title: "Hello World" },
|
||||
operation: "create",
|
||||
});
|
||||
expect(result?.slug).toBe("hello-world");
|
||||
});
|
||||
|
||||
it("does not overwrite an existing slug", () => {
|
||||
const result = slugifyIfMissing({
|
||||
data: { title: "New Title", slug: "kept-slug" },
|
||||
operation: "create",
|
||||
});
|
||||
expect(result?.slug).toBe("kept-slug");
|
||||
});
|
||||
|
||||
it("does nothing on update", () => {
|
||||
const result = slugifyIfMissing({
|
||||
data: { title: "Hello World" },
|
||||
operation: "update",
|
||||
});
|
||||
expect(result?.slug).toBeUndefined();
|
||||
});
|
||||
|
||||
it("strips non-alphanumerics and trims hyphens", () => {
|
||||
const result = slugifyIfMissing({
|
||||
data: { title: " Hello, World!! 2026 " },
|
||||
operation: "create",
|
||||
});
|
||||
expect(result?.slug).toBe("hello-world-2026");
|
||||
});
|
||||
|
||||
it("returns data unchanged when title is missing", () => {
|
||||
const result = slugifyIfMissing({
|
||||
data: {},
|
||||
operation: "create",
|
||||
});
|
||||
expect(result?.slug).toBeUndefined();
|
||||
});
|
||||
});
|
||||
19
packages/core-shared/src/payload/hooks/slugify-if-missing.ts
Normal file
19
packages/core-shared/src/payload/hooks/slugify-if-missing.ts
Normal file
@@ -0,0 +1,19 @@
|
||||
export function slugifyIfMissing({
|
||||
data,
|
||||
operation,
|
||||
}: {
|
||||
data?: { title?: string; slug?: string };
|
||||
operation?: string;
|
||||
}) {
|
||||
if (!data) return data;
|
||||
if (operation !== "create") return data;
|
||||
if (data.slug) return data;
|
||||
if (!data.title) return data;
|
||||
|
||||
data.slug = data.title
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "");
|
||||
|
||||
return data;
|
||||
}
|
||||
Reference in New Issue
Block a user