From 124ccabc5f67946ba9c9c5ea33c8533d4b04ec93 Mon Sep 17 00:00:00 2001 From: Danijel Martinek Date: Mon, 4 May 2026 20:36:45 +0200 Subject: [PATCH] feat(core-shared): add setPublishedAt hook --- .../payload/hooks/set-published-at.test.ts | 34 +++++++++++++++++++ .../src/payload/hooks/set-published-at.ts | 13 +++++++ 2 files changed, 47 insertions(+) create mode 100644 packages/core-shared/src/payload/hooks/set-published-at.test.ts create mode 100644 packages/core-shared/src/payload/hooks/set-published-at.ts diff --git a/packages/core-shared/src/payload/hooks/set-published-at.test.ts b/packages/core-shared/src/payload/hooks/set-published-at.test.ts new file mode 100644 index 0000000..40fdd50 --- /dev/null +++ b/packages/core-shared/src/payload/hooks/set-published-at.test.ts @@ -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(); + }); +}); diff --git a/packages/core-shared/src/payload/hooks/set-published-at.ts b/packages/core-shared/src/payload/hooks/set-published-at.ts new file mode 100644 index 0000000..d7e4093 --- /dev/null +++ b/packages/core-shared/src/payload/hooks/set-published-at.ts @@ -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; +}