Skip to content

The Gateway

Marcus edited this page Mar 27, 2018 · 1 revision

Moleculer-ws is designed to be a gateway similar to moleculer-web it supports the same features in terms of routing, authorization and pre/post action calls.

Example of a service (Typescript & decorators)

import moleculer = require('moleculer');
import { Service, Action, Method } from 'moleculer-decorators';
import { WSGateway, Settings, route, Request, BaseClass } from 'moleculer-ws';
import Bluebird = require('bluebird');

@Service({
  mixins: [WSGateway],
  settings: {
    port: 3000,
    path: '/',
    routes: [
      <route>{
        name: 'SomeName',
        aliases: {
          test: 'SomeService.test'
        },
        whitelist: ['SomeService.*'],
        mappingPolicy: 'strict',

        onBeforeCall(ctx: moleculer.Context, req: Request) {
          return new Bluebird((resolve, reject) => {
            return resolve({
              ctx, // to modify context
              params: {}, // to modify params
              props: {}, // to modify client props
            });
          });
        },

        onAfterCall(ctx: moleculer.Context, req: Request, res: object) {
          return new Bluebird((resolve, reject) => {
            return resolve({ // Any data that resolves will be the new response.
              foo: 'bar'
            })
          });
        }
      }
    ]
  }
})
class Gateway extends BaseClass {
  created() {
    // Listen for an event and respond to it
    this.on('someEvent', (data, client, respond) => {
      respond(null, 'Right on!');
    });
  }

  @Method
  authorize(client, params) {
    if (params.username == 'test' && params.password == 'test') {
      client.props.username = 'test'; // set client prop
      return Bluebird.Promise.resolve();
    }

    return Bluebird.Promise.reject('Invalid login');
  }
}
Clone this wiki locally