Skip to content

LuxChanLu/moleculer-faktory

Repository files navigation

moleculer-faktory

Build Status Coverage Status Codacy Badge Maintainability David Known Vulnerabilities

Downloads FOSSA Status

How to use it

Worker (Service with your jobes)

const { WorkerMixin } = require('moleculer-faktory')

module.exports = {
  name: 'images',
  mixins: [WorkerMixin],
  settings: {
    faktory: {
      /** @type {String} Faktory url (tcp://:passqueue@localhost:7419/) also FAKTORY_URL can be use. */
      url: 'tcp://:passqueue@localhost:7419',
      /** @type {Object?} Additional options for `new Worker()` */
      options: {
        concurrency: 5,
        timeout: 25 * 1000
      },
      /** @type {Array?} Middlewares for faktory */
      middlewares: [],
      /** @type {Boolean?} Enable hooks middleware */
      hooks: true
    }
  },
  actions: {
    resize: {
      queue: true,
      async handler(ctx) {
        const { image, size } = ctx.params
        const { user } = ctx.meta
        // Do the magic here !
      }
    }
  }
}

Client (Service launching jobs)

const { ClientMixin } = require('moleculer-faktory')

module.exports = {
  name: 'web',
  mixins: [ClientMixin],
  settings: {
    faktory: {
      /** @type {String} Faktory url (tcp://:passqueue@localhost:7419/) also FAKTORY_URL can be use. */
      url: 'tcp://:passqueue@localhost:7419',
      /** @type {Object?} Additional options for `new Client()` */
      options: {
        labels: ['test'],
      }
    }
  },
  actions: {
    async 'image.upload'(ctx) {
      ctx.meta.user = {} // Meta will be passed to the job handler
      await this.queue(ctx, 'images.resize', { image: ctx.params.image, size: 'landscape.large' })
      return 'In progress...'
    }
  }
}

You can also use hooks (No native from faktory, middleware in this module : See src/worker.js#72)

const { ClientMixin } = require('moleculer-faktory')

module.exports = {
  name: 'web',
  mixins: [ClientMixin],
  settings: {
    faktory: {
      /** @type {String} Faktory url (tcp://:passqueue@localhost:7419/) also FAKTORY_URL can be use. */
      url: 'tcp://:passqueue@localhost:7419',
      /** @type {Object?} Additional options for `new Client()` */
      options: {
        labels: ['test'],
      }
    }
  },
  actions: {
    async 'image.upload'(ctx) {
      const { image } = ctx.params
      ctx.meta.user = {} // Meta will be passed to the job handler and also the hooks
      await this.queue(ctx, 'images.resize', { image: ctx.params.image, size: 'landscape.large' }, {
        start: { handler: 'web.image.start' },
        end: { handler: 'web.image.end', params: { image } }
      })
      return 'In progress...'
    },
    'image.start'() {
      // Automagicaly send to the client notification ?
    },
    'image.end'(ctx) {
      const { image } = ctx.params
      const { user } = ctx.meta
      // Automagicaly send to the client notification ?
    }
  }
}