Search code examples
hookfeathersjs

Feathersjs auto increment on hook


Is there a simpler way to perform auto increment for the GET api with the use of hook? Trying to implement something like view count, where it auto increment the count after a GET.

const portfoliosHooks = {
  after: {
    all: [],
    find: [],
    get: [],
    create: [],
    update: [],
    patch: [],
    remove: []
  },
}

Solution

  • This should do the job:

    const portfoliosHooks = {
      after: {
        all: [],
        find: [],
        get: [
          hook => hook.service.patch(hook.id, { views: hook.result.views + 1 })
        ],
        create: [],
        update: [],
        patch: [],
        remove: []
      },
    }
    

    hook.service is the service the hook is running on. This assumes you have a POJO result. If not, you'd have to flatten it first (toObject() or toJSON() depending on your db).