feat: calc label field on copy record

This commit is contained in:
Yehoshua Sandler 2025-04-16 16:12:24 -05:00
parent d02a07541b
commit d56e1eb5ea
2 changed files with 53 additions and 2 deletions

View File

@ -1,8 +1,54 @@
import { CollectionConfig } from "payload";
import { CollectionAfterReadHook, CollectionConfig } from "payload";
const afterReadHook: CollectionAfterReadHook = async ({ doc, req }) => {
if (doc.label) return doc;
let bookName;
if (doc.book) {
const relatedBook = await req.payload.findByID({
req,
collection: 'books',
id: doc.book,
depth: 2,
})
bookName = relatedBook.title
} else return doc
let repositoryName;
if (doc.repository) {
const relatedRepo = await req.payload.findByID({
req,
collection: 'repositories',
id: doc.repository,
depth: 2,
})
repositoryName = relatedRepo.abbreviation || relatedRepo.name
} else return doc
return { ...doc, label: `[${repositoryName}] ${bookName}` }
}
export const Copies: CollectionConfig = {
slug: 'copies',
access: {
read: () => true,
update: () => true,
create: () => true,
admin: () => true,
},
admin: {
useAsTitle: 'label',
pagination: {
limits: [10, 20, 50, 100, 250],
},
},
fields: [
{
name: 'label',
type: 'text',
},
{
name: 'condition',
label: 'Condition out of 5',
@ -26,5 +72,8 @@ export const Copies: CollectionConfig = {
name: 'notes',
type: 'richText'
}
]
],
hooks: {
afterRead: [afterReadHook]
},
}

View File

@ -254,6 +254,7 @@ export interface Repository {
*/
export interface Copy {
id: number;
label?: string | null;
condition?: number | null;
book?: (number | null) | Book;
repository?: (number | null) | Repository;
@ -461,6 +462,7 @@ export interface RepositoriesSelect<T extends boolean = true> {
* via the `definition` "copies_select".
*/
export interface CopiesSelect<T extends boolean = true> {
label?: T;
condition?: T;
book?: T;
repository?: T;