feat(core-shared): add setPublishedAt hook
This commit is contained in:
@@ -0,0 +1,34 @@
|
|||||||
|
import { describe, expect, it, beforeEach, afterEach, vi } from "vitest";
|
||||||
|
import { setPublishedAt } from "./set-published-at";
|
||||||
|
|
||||||
|
describe("setPublishedAt", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.useFakeTimers();
|
||||||
|
vi.setSystemTime(new Date("2026-05-04T12:00:00.000Z"));
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.useRealTimers();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("sets publishedAt to now when status is published and publishedAt is missing", () => {
|
||||||
|
const result = setPublishedAt({ data: { status: "published" } });
|
||||||
|
expect(result?.publishedAt).toBe("2026-05-04T12:00:00.000Z");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not overwrite an existing publishedAt", () => {
|
||||||
|
const result = setPublishedAt({
|
||||||
|
data: { status: "published", publishedAt: "2025-01-01T00:00:00.000Z" },
|
||||||
|
});
|
||||||
|
expect(result?.publishedAt).toBe("2025-01-01T00:00:00.000Z");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("does not set publishedAt when status is not published", () => {
|
||||||
|
const result = setPublishedAt({ data: { status: "draft" } });
|
||||||
|
expect(result?.publishedAt).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns data unchanged when data is missing", () => {
|
||||||
|
expect(setPublishedAt({})).toBeUndefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
13
packages/core-shared/src/payload/hooks/set-published-at.ts
Normal file
13
packages/core-shared/src/payload/hooks/set-published-at.ts
Normal file
@@ -0,0 +1,13 @@
|
|||||||
|
export function setPublishedAt({
|
||||||
|
data,
|
||||||
|
}: {
|
||||||
|
data?: { status?: string; publishedAt?: string | null };
|
||||||
|
}) {
|
||||||
|
if (!data) return data;
|
||||||
|
|
||||||
|
if (data.status === "published" && !data.publishedAt) {
|
||||||
|
data.publishedAt = new Date().toISOString();
|
||||||
|
}
|
||||||
|
|
||||||
|
return data;
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user