How to use the @webiny/commodo.withHooks function in @webiny/commodo

To help you get started, we’ve selected a few @webiny/commodo examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github webiny / webiny-js / packages / api-security / src / plugins / models / securityUser.model.js View on Github external
export default ({
    createBase,
    SecurityRole,
    SecurityRoles2Models,
    SecurityGroup,
    SecurityGroups2Models,
    context
}) => {
    const SecurityUser = flow(
        withName("SecurityUser"),
        withHooks(),
        withFields(instance => ({
            email: onSet(value => {
                if (value === instance.email) {
                    return value;
                }

                value = value.toLowerCase().trim();
                instance.registerHookCallback("beforeSave", async () => {
                    console.log("TODO: setOnce"); // eslint-disable-line

                    const existingUser = await SecurityUser.findOne({
                        query: { email: value }
                    });
                    if (existingUser) {
                        throw Error("User with given e-mail already exists.");
                    }
github webiny / webiny-js / packages / api-page-builder / src / plugins / models / pbPage.model.js View on Github external
return new Promise(async resolve => {
                    const settings = await PbSettings.load();
                    resolve(settings.data.pages.notFound === this.parent);
                }).catch(() => false);
            },
            get revisions() {
                return new Promise(async resolve => {
                    const revisions = await PbPage.find({
                        query: { parent: this.parent },
                        sort: { version: -1 }
                    });
                    resolve(revisions);
                });
            }
        }),
        withHooks({
            async beforeCreate() {
                if (!this.id) {
                    this.id = mdbid();
                }

                if (!this.parent) {
                    this.parent = this.id;
                }

                if (!this.title) {
                    this.title = "Untitled";
                }

                if (!this.url) {
                    this.url = (await this.category).url + "untitled-" + this.id;
                }
github webiny / webiny-js / packages / api-i18n / src / plugins / models / i18nLocale.model.js View on Github external
return value;
            })(boolean()),
            code: string({
                validation: value => {
                    if (!value) {
                        throw Error("Locale code is required.");
                    }

                    if (localesList.includes(value)) {
                        return;
                    }
                    throw Error(`Value ${value} is not a valid locale code.`);
                }
            })
        })),
        withHooks({
            async beforeCreate() {
                const existingLocale = await I18NLocale.findOne({ query: { code: this.code } });
                if (existingLocale) {
                    throw Error(`Locale with key "${this.code}" already exists.`);
                }
            },
            async beforeDelete() {
                if (this.default) {
                    throw Error(
                        "Cannot delete default locale, please set another locale as default first."
                    );
                }

                const remainingLocalesCount = await I18NLocale.count({
                    query: { id: { $ne: this.id } }
                });
github webiny / webiny-js / packages / api-page-builder / src / plugins / models / pbMenu.model.js View on Github external
export default ({ createBase }) => {
    const PbMenu = flow(
        withName("PbMenu"),
        withFields({
            title: string({ validation: validation.create("required") }),
            slug: setOnce()(string({ validation: validation.create("required") })),
            description: string(),
            items: object()
        }),
        withHooks({
            async beforeCreate() {
                const existingMenu = await PbMenu.findOne({ query: { slug: this.slug } });
                if (existingMenu) {
                    throw Error(`Menu with slug "${this.slug}" already exists.`);
                }
            }
        })
    )(createBase());

    return PbMenu;
};
github webiny / webiny-js / packages / api-security / src / withUser.js View on Github external
export default context => baseFn => {
    return flow(
        withProps({
            getUser() {
                return context.user;
            },
            getUserId() {
                return context.user ? context.user.id : null;
            }
        }),
        withFields({
            createdBy: skipOnPopulate()(id()),
            updatedBy: skipOnPopulate()(id()),
            deletedBy: skipOnPopulate()(id())
        }),
        withHooks({
            beforeCreate() {
                this.createdBy = this.getUserId();
            },
            beforeUpdate() {
                this.updatedBy = this.getUserId();
            },
            beforeDelete() {
                this.deletedBy = this.getUserId();
            }
        })
    )(baseFn);
};
github webiny / webiny-js / packages / api-forms / src / plugins / models / form.model.js View on Github external
version: number(),
            parent: string(),
            publishedOn: date(),
            published: onSet(value => {
                if (value) {
                    instance.publishedOn = new Date();
                    if (!instance.locked) {
                        instance.locked = true;
                    }
                }

                return value;
            })(boolean()),
            locked: skipOnPopulate()(boolean({ value: false }))
        })),
        withHooks({
            async beforeCreate() {
                if (!this.id) {
                    this.id = mdbid();
                }

                if (!this.parent) {
                    this.parent = this.id;
                }

                if (!this.name) {
                    this.name = "Untitled";
                }

                if (!this.slug) {
                    this.slug = [slugify(this.name), uniqueId()].join("-").toLowerCase();
                }
github webiny / webiny-js / packages / api-security / src / plugins / models / securityGroup.model.js View on Github external
export default ({ createBase, SecurityRole, SecurityRoles2Models }) => {
    const SecurityGroup = flow(
        withName("SecurityGroup"),
        withFields(() => ({
            description: string(),
            name: string(),
            slug: string(),
            system: boolean(),
            roles: ref({
                list: true,
                instanceOf: [SecurityRole, "model"],
                using: [SecurityRoles2Models, "role"]
            })
        })),
        withHooks({
            async beforeCreate() {
                const existingGroup = await SecurityGroup.findOne({
                    query: { slug: this.slug }
                });
                if (existingGroup) {
                    throw Error(`Group with slug "${this.slug}" already exists.`);
                }
            },
            async beforeDelete() {
                if (this.system) {
                    throw Error(`Cannot delete system group.`);
                }
            }
        })
    )(createBase());
github webiny / webiny-js / packages / api-security / src / plugins / models / securityRole.model.js View on Github external
export default ({ createBase }) => {
    const SecurityRole = flow(
        withName("SecurityRole"),
        withFields({
            name: string(),
            slug: string(),
            description: string(),
            system: boolean(),
            scopes: string({ list: true })
        }),
        withHooks({
            async beforeCreate() {
                const existingRole = await SecurityRole.findOne({
                    query: { slug: this.slug }
                });
                if (existingRole) {
                    throw Error(`Role with slug "${this.slug}" already exists.`);
                }
            },
            async beforeDelete() {
                if (this.system) {
                    throw Error(`Cannot delete system role.`);
                }
            }
        })
    )(createBase());
github webiny / webiny-js / packages / api-forms / src / plugins / models / formSubmission.model.js View on Github external
})()
            }),
            logs: fields({
                list: true,
                value: [],
                instanceOf: withFields({
                    type: string({
                        validation: validation.create("required,in:error:warning:info:success"),
                        message: string(),
                        data: object(),
                        createdOn: date({ value: new Date() })
                    })
                })()
            })
        })),
        withHooks({
            beforeCreate() {
                this.meta.submittedOn = new Date();
            }
        }),
        withProps({
            addLog(log) {
                if (!Array.isArray(this.logs)) {
                    this.logs = [];
                }

                this.logs = [...this.logs, log];
            }
        })
    )(createBase());
};