Skip to content

Conversation

@boutell
Copy link
Member

@boutell boutell commented Aug 19, 2024

This PR on one of our basic starter kits demonstrates how to forbid certain slugs by generating an error on the server side. A beforeSave handler on @apostrophecms/doc-type, the base class of all doc type modules, is used to achieve the effect.

@linear
Copy link

linear bot commented Aug 19, 2024

@@ -0,0 +1,26 @@
module.exports = {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Placing this file in modules/@apostrophecms/doc-type/index.js causes Apostrophe to load it as additional configuration for @apostrophecms/doc-type, the base class of all modules.

module.exports = {
options: {
forbiddenSlugs: [
'/evil-page',
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Change this list to suit your needs.

handlers(self) {
return {
beforeSave: {
checkForbiddenSlugs(req, doc) {
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Each beforeSave handler must have a descriptive, unique name.

checkForbiddenSlugs(req, doc) {
if (self.options.forbiddenSlugs.includes(doc.slug)) {
const e = self.apos.error('invalid', 'That slug is reserved.');
e.path = 'slug';
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Tag the error with its path in the schema (the name of the field concerned).

e.path = 'slug';
throw self.apos.error('invalid', {
errors: [
e
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Including it in an errors array in the final error object causes the Apostrophe UI to loop through and find it and display it in the right place, along with any errors you wish to report on other fields.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants