npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

loopback-pubsub-component

v0.2.1

Published

LoopBack 4 PubSub Comoonent

Downloads

13

Readme

loopback-pubsub-component

A PubSub component for LoopBack 4, trying to follow GraphQL specs and inspired by graphql-subscriptions

This is a generic component that can wraps "any" PubSub client/broker in your own repository and strategy provider.

Installation

Run the following command to install loopback-pubsub-component:

npm i -s loopback-pubsub-component

Usage

Import component

When the loopback-pubsub-component package is installed, bind it to your application with app.component()

import {RestApplication} from '@loopback/rest';
import {PubSubBindings, PubSubComponent, PubSubStrategyProvider} from 'loopback-pubsub-component';

const app = new RestApplication();

app.bind(PubSubBindings.CONFIG).to({
  eventEmitter: new EventEmitter(),
  // client: mqttClient
});
app.component(PubSubComponent);
app.bind(PubSubBindings.PUBSUB_STRATEGY).toProvider(PubSubStrategyProvider);

Create a repository

Create a repository that implements your client/broker logic, here an example for a simple EventEmitter. You could create several repositories, with MQTT client or other kinds of PubSub clients.

import {inject} from '@loopback/core';
import {
  PubSubEngine,
  PubSubBindings,
  PubSubConfig,
  PubSubAsyncIterator,
} from 'loopback-pubsub-component';
import {EventEmitter} from 'events';

export class PubSubEERepository extends PubSubEngine {
  protected ee: EventEmitter;
  public subscriptions: {[subId: number]: [string, (...args: any[]) => void]};
  public subIdCounter: number;

  constructor(@inject(PubSubBindings.CONFIG) options: PubSubConfig) {
    super();
    if (options.eventEmitter) {
      this.ee = options.eventEmitter;
    } else {
      this.ee = new EventEmitter();
    }
    this.subscriptions = {};
    this.subIdCounter = 0;
  }

  public publish(triggerName: string, payload: any): Promise<void> {
    this.ee.emit(triggerName, payload);
    return Promise.resolve();
  }

  public subscribe(
    triggerName: string,
    onMessage: (...args: any[]) => void,
    options?: Object,
  ): Promise<number> {
    this.ee.addListener(triggerName, onMessage);
    this.subIdCounter = this.subIdCounter + 1;
    this.subscriptions[this.subIdCounter] = [triggerName, onMessage];
    return Promise.resolve(this.subIdCounter);
  }

  public unsubscribe(subIdOrTriggerName: number | string) {
    if (typeof subIdOrTriggerName === 'string') {
      return this.unsubscribeByName(subIdOrTriggerName);
    }
    return this.unsubscribeById(subIdOrTriggerName);
  }

  public asyncIterator<T>(triggers: string | string[]): AsyncIterator<T> {
    return new PubSubAsyncIterator<T>(this, triggers);
  }

  private unsubscribeById(subId: number) {
    const [triggerName, onMessage] = this.subscriptions[subId];
    delete this.subscriptions[subId];
    this.ee.removeListener(triggerName, onMessage);
    return Promise.resolve();
  }

  private unsubscribeByName(triggerName: string) {
    const subIds: number[] = Object.keys(this.subscriptions).map(Number);
    for (const subId of subIds) {
      if (this.subscriptions[subId][0] === triggerName) {
        const onMessage = this.subscriptions[subId][1];
        delete this.subscriptions[subId];
        this.ee.removeListener(triggerName, onMessage);
        break;
      }
    }
    return Promise.resolve();
  }
}

Strategy provider

Create a strategy provider that implements your custom logic. If you have several repositories, inject them and create a function to switch between repositories with trigerName filtering.

import {inject, Provider, ValueOrPromise} from '@loopback/core';
import {repository} from '@loopback/repository';
import {
  PubSubBindings,
  PubSubConfig,
  PubSubStrategy,
  PubSubMetadata,
} from 'loopback-pubsub-component';
import {PubSubEERepository, PubSubMQTTRepository} from '../repositories';

export class PubSubStrategyProvider implements Provider<PubSubStrategy | undefined> {
  private engines: (PubSubEERepository | PubSubMQTTRepository)[];

  constructor(
    @inject(PubSubBindings.METADATA) private metadata: PubSubMetadata,
    @repository(PubSubEERepository) protected pubsubEERepo: PubSubEERepository,
    @repository(PubSubMQTTRepository) protected pubsubMQTTRepo: PubSubMQTTRepository,
  ) {
    this.engines = [this.pubsubEERepo, this.pubsubMQTTRepo];
  }

  selectRepository(triggerNames: string | string[]): PubSubEERepository | PubSubMQTTRepository {
    // filter triggerName or triggerNames[0]
    return this.engines[0];
  }

  value(): ValueOrPromise<PubSubStrategy | undefined> {
    const self = this;

    return {
      setConfig: async (config?: Object) => {
        const pubsubConf: PubSubConfig = {};
        return pubsubConf;
      },

      publish: async (triggerName: string, payload: any) => {
        const engine = this.selectRepository(triggerName);
        await engine.publish(triggerName, JSON.stringify(payload));
      },

      subscribe: (triggerName: string, onMessage: (...args: any[]) => void, options?: Object) => {
        const engine = this.selectRepository(triggerName);
        // return Promise.all([engines.map( engine => engine.subscribe(triggerName, onMessage, options))])
        return engine.subscribe(triggerName, onMessage, options);
      },

      unsubscribe: async (triggerName: string) => {
        const engine = this.selectRepository(triggerName);
        await engine.unsubscribe(triggerName);
      },

      asyncIterator(triggers: string | string[]) {
        const engine = self.selectRepository(triggers);
        return engine.asyncIterator(triggers);
      },

    };
  }
}

Use in a controller

Inject the bindings, to make available PubSubStrategy provider functions.

import {inject} from '@loopback/context';
import {repository} from '@loopback/repository';
import {
  post,
  param,
  get,
  patch,
  put,
  Request,
  requestBody,
  RestBindings,
} from '@loopback/rest';
import {PubSubBindings} from 'loopback-pubsub-component';
import {Device} from '../models';
import {DeviceApi, devicesApiEndPoint} from '../services';
import {getToken} from '../utils';

const security = [
  {
    Authorization: [],
  },
];

export class DeviceController {
  constructor(
    @inject('services.DeviceApi') protected deviceApi: DeviceApi,
    @inject(RestBindings.Http.REQUEST) public request: Request,
    @inject(PubSubBindings.publish) public publish: PubSubPublishFn,
  ) {}

  @post(`/${devicesApiEndPoint}`, {
    operationId: 'createDevice',
    security,
    responses: {
      '200': {
        description: 'Device instance',
        content: {'application/json': {schema: {'x-ts-type': Device}}},
      },
    },
  })
  async create(@requestBody() device: Device): Promise<Device> {
    const token = getToken(this.request);
    const result = await this.deviceApi.create(token, device);
    await this.publish(this.request.path, result)
    return result;
  }

}

TODO

  • Adding decorator to use it like a router in a Controller ( @publish, @subscribe ... ) and control access ( when using broker )

License

LoopBack