@websolutespa/payload-plugin-bowl
Version:
Bowl PayloadCms plugin of the BOM Repository
80 lines (79 loc) • 2.66 kB
JavaScript
import { deepMerge } from '@websolutespa/payload-utils';
export const beforeValidate = (slug)=>async ({ value, originalDoc, data, req })=>{
// console.log('withOrder.beforeValidate.value', value);
if (parseInt(String(value)).toString() === String(value)) {
return value;
}
const { payload } = req;
const items = await payload.find({
collection: slug,
sort: '-order',
limit: 1,
overrideAccess: true
});
let order = 10;
if (items && items.docs.length > 0) {
const itemOrder = items.docs[0].order;
order = (itemOrder || 0) + 10;
}
// console.log('withOrder.validate.newValue', order, items);
return order;
};
export const OrderDefaults = {
name: 'order',
type: 'number',
// unique: true,
admin: {
step: 1
}
};
export const withOrder = ({ slug, ...options })=>{
const field = deepMerge(OrderDefaults, options);
// field.validate = validate(slug);
// !!! removed before validate
// withFieldHook(field, 'beforeValidate', beforeValidate(slug));
// withFieldHook(field, 'afterRead', beforeValidate(slug));
return field;
};
export const withOrderRequired = ({ slug, ...options })=>{
const field = deepMerge({
...OrderDefaults,
required: true
}, options);
// !!! removed before validate
// withFieldHook(field, 'beforeValidate', beforeValidate(slug));
// withFieldHook(field, 'afterRead', beforeValidate(slug));
return field;
}; /**
*
* !!! validation function should return true or string error message
*/ /*
export const validate: (slug: CollectionSlug) => Validate = (slug: CollectionSlug) => async (value, { data, siblingData, operation, id, payload: validatePayload }) => {
console.log('withOrder.validate.value', value);
if (parseInt(value).toString() === String(value)) {
return value;
}
const fetchItems = async () => {
if (validatePayload) {
return await validatePayload.find({
collection: slug,
sort: '-order',
limit: 1,
});
} else if (window !== undefined) {
const response = await fetch(`${window.location.origin}/api/${slug}?sort=-order&limit=1`);
if (response.ok) {
return await response.json();
}
}
};
const items = await fetchItems();
let order = 10;
if (items && items.docs.length > 0) {
order = (items.docs[0].order || 0) + 10;
}
console.log('withOrder.validate.newValue', order);
return order;
};
*/
//# sourceMappingURL=withOrder.js.map