21 lines
840 B
TypeScript
21 lines
840 B
TypeScript
import type { CollectionBeforeChangeHook } from 'payload'
|
|
|
|
/**
|
|
* Sets `publishedAt` to now the first time a document transitions to published,
|
|
* if it isn't already set. Saves editors from filling the date manually and
|
|
* keeps blog/article dates accurate for Article JSON-LD and sitemaps.
|
|
*
|
|
* Attach to collections with drafts enabled (blog, articles):
|
|
* hooks: { beforeChange: [setPublishedAtHook] }
|
|
*
|
|
* Only sets on the published transition; never overwrites an existing date
|
|
* (an editor can still backdate manually).
|
|
*/
|
|
export const setPublishedAtHook: CollectionBeforeChangeHook = ({ data, originalDoc }) => {
|
|
const becomingPublished = data._status === 'published' && originalDoc?._status !== 'published'
|
|
if (becomingPublished && !data.publishedAt) {
|
|
data.publishedAt = new Date().toISOString()
|
|
}
|
|
return data
|
|
}
|