Skip to content

Custom hooks #5

@icebob

Description

@icebob
  • Start Date: 2020-03-08
  • Target Version: 0.14
  • Reference Issues: -
  • Implementation PR: -

Summary

We should extend the current Action Hooks feature. It is used by the ActionHook middleware and it can be defined only before, after & error hooks for actions.

For some major components, it would be good if the user can define custom hooks for the custom functions, e.g. define a beforeTransform or afterPopulate hook in moleculer-db.

Basic example

module.exports = {
    name: "posts",
    mixins: [DbService],
    hooks: {
        // It will be called before transforming
        beforeTransform(ctx, params, doc) {
            doc.id = encrypt(doc._id);
            delete doc._id;
        },

        // It will be called after populating
        afterPopulate(ctx, populate, doc) {
            if (doc.author) {
                delete doc.authorID;
            }
        }
    },
};
function transformDocuments(ctx, params, doc) {
  // Call beforeTransform hook
  if (this.hooks.beforeTransform) {
    await this.hooks.beforeTransform(ctx, params, doc);
  }

  //  Do transforming

  // Call afterTransform hook
  if (this.hooks.afterTransform) {
    await this.hooks.afterTransform(ctx, params, doc);
  }
}

Motivation

Detailed design

Drawbacks

Alternatives

Adoption strategy

Unresolved questions

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions