A simple PubSub factory method exposing a listen-emit pattern

PubSub

This is a generic PubSub Factory exposing a listen and a emit method.

NOTE: Today, only Google Cloud PubSub has been added.

Installation

npm install --save @algoan/pubsub

Usage

Google Cloud PubSub

Run tests

To run tests or to try the PubSubFactory class, you need to have a google account and have installed gcloud sdk.

Then, to install the Google PubSub simulator, run:

gcloud components install pubsub-emulator
gcloud components update

Start tests running:

npm test

It will launch a Google PubSub emulator thanks to the google-pubsub-emulator library.

Example

To create a PubSub instance using Google Cloud:

import { EmittedMessage, GCPubSub, PubSubFactory, Transport } from '@algoan/pubsub'

const pubSub: GCPubSub = PubSubFactory.create({
  transport: Transport.GOOGLE_PUBSUB,
  options: {
    projectId: 'test',
    // And all other Google PubSub properties
  }
});
const topicName: string = 'some_topic';

await pubsub.listen(topicName, {
  autoAck: true,
  onMessage: (data: EmittedMessage<{foo: string}>) => {
    console.log(data.parsedData); // { foo: 'bar', time: {Date.now}, _eventName: 'some_topic' }
    // do whatever you want. The message has already been acknowledged
  },
  onError: (error: Error) => {
    // Handle error as you wish
  }
});

await pubsub.emit(topicName, { foo: 'bar' });

Contribution

This module uses semantic-release, please follow these instructions to contribute to the project or use npm run commit.

API

PubSubFactory.create({ transport, options })

The only static method from the PubSubFactory class. It initiates a new PubSub instance depending on the transport. By default, it connects to Google Cloud PubSub.

  • transport: PubSub technology to use. Only GOOGLE_PUBSUB is available for now.
  • options: Options related to the transport.
    • If transport === Transport.GOOGLE_PUBSUB, then have a look at the Google Cloud PubSub config client.
    • debug: Display logs if it is set to true. It uses a pino logger and pino-pretty if NODE_ENV is not equal to production.
    • pinoOptions: If debug is set to true, set the pino logger options. Default to level: debug and prettyPrint: true if NODE_ENV is not equal to production.
    • topicsPrefix: Add a prefix to all created topics. Example: topicsPrefix: 'my-topic', all topics will begin with my-topic+{your topic name}.
    • subscriptionsPrefix: Add a prefix to all created subscriptions. Example: subscriptionsPrefix: 'my-sub', all topics will begin with my-sub%{your topic name}.
    • namespace: Add a namespace property to Message attributes when publishing on a topic.
    • environment: Add a environment property to Message attributes when publishing on a topic.

pubsub.listen(event, opts)

Listen to a specific event.

NOTE: It only uses the Google Cloud subscription pull delivery for now.

  • event: Name of the event.
  • opts: Options related to the Listener method
    • onMessage: Method called when receiving a message
    • onError: Method called when an error occurs
    • options: Option related to the chosen transport

If the chosen transport is Google Cloud PubSub, then options would be:

  • autoAck: Automatically ACK an event as soon as it is received (default to true)
  • subscriptionOptions: Options related to the created Subscription:
  • topicOptions: Options applied to the created topic (have a look at Topic options)

pubsub.emit(event, payload, opts)

Emit a specific event with a payload. It added attributes in the message if you have added a namespace or an environment when setting the PubSubFactory class. It also adds an _eventName and a time property in the emitted payload.

  • event: Name of the event to emit.
  • payload: Payload to send. It will be buffered by Google, and then parsed by the listen method.
  • opts: Options related to the Emit method
    • metadata: Custom metadata added to the message
    • options: Option related to the chosen transport

If the chosen transport is Google Cloud PubSub, then options would be:

  • topicOptions: Options applied to the created topic (have a look at Topic options)

Download Details:

Author: algoan

Source Code: https://github.com/algoan/pubsub

#nodejs #node #javascript

What is GEEK

Buddha Community

A simple PubSub factory method exposing a listen-emit pattern
Samanta  Moore

Samanta Moore

1623835440

Builder Design Pattern

What is Builder Design Pattern ? Why we should care about it ?

Starting from **Creational Design Pattern, **so wikipedia says “creational design pattern are design pattern that deals with object creation mechanism, trying to create objects in manner that is suitable to the situation”.

The basic form of object creations could result in design problems and result in complex design problems, so to overcome this problem Creational Design Pattern somehow allows you to create the object.

Builder is one of the** Creational Design Pattern**.

When to consider the Builder Design Pattern ?

Builder is useful when you need to do lot of things to build an Object. Let’s imagine DOM (Document Object Model), so if we need to create the DOM, We could have to do lot of things, appending plenty of nodes and attaching attributes to them. We could also imagine about the huge XML Object creation where we will have to do lot of work to create the Object. A Factory is used basically when we could create the entire object in one shot.

As **Joshua Bloch (**He led the Design of the many library Java Collections Framework and many more) – “Builder Pattern is good choice when designing the class whose constructor or static factories would have more than handful of parameters

#java #builder #builder pattern #creational design pattern #design pattern #factory pattern #java design pattern

Joseph  Murray

Joseph Murray

1624442280

Factory design pattern — Java

Definition of the Factory pattern

In class-based programming, the factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a _factory method _— either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes — rather than by calling a constructor.

Where to use the Factory pattern

  • When a class doesn’t know what sub-classes will be required to create
  • When a class wants that its sub-classes specify the objects to be created.
  • When the parent classes choose the creation of objects to its sub-classes.

#factory-design-pattern #code #tutorial #design-patterns #java #factory design pattern — java

A simple PubSub factory method exposing a listen-emit pattern

PubSub

This is a generic PubSub Factory exposing a listen and a emit method.

NOTE: Today, only Google Cloud PubSub has been added.

Installation

npm install --save @algoan/pubsub

Usage

Google Cloud PubSub

Run tests

To run tests or to try the PubSubFactory class, you need to have a google account and have installed gcloud sdk.

Then, to install the Google PubSub simulator, run:

gcloud components install pubsub-emulator
gcloud components update

Start tests running:

npm test

It will launch a Google PubSub emulator thanks to the google-pubsub-emulator library.

Example

To create a PubSub instance using Google Cloud:

import { EmittedMessage, GCPubSub, PubSubFactory, Transport } from '@algoan/pubsub'

const pubSub: GCPubSub = PubSubFactory.create({
  transport: Transport.GOOGLE_PUBSUB,
  options: {
    projectId: 'test',
    // And all other Google PubSub properties
  }
});
const topicName: string = 'some_topic';

await pubsub.listen(topicName, {
  autoAck: true,
  onMessage: (data: EmittedMessage<{foo: string}>) => {
    console.log(data.parsedData); // { foo: 'bar', time: {Date.now}, _eventName: 'some_topic' }
    // do whatever you want. The message has already been acknowledged
  },
  onError: (error: Error) => {
    // Handle error as you wish
  }
});

await pubsub.emit(topicName, { foo: 'bar' });

Contribution

This module uses semantic-release, please follow these instructions to contribute to the project or use npm run commit.

API

PubSubFactory.create({ transport, options })

The only static method from the PubSubFactory class. It initiates a new PubSub instance depending on the transport. By default, it connects to Google Cloud PubSub.

  • transport: PubSub technology to use. Only GOOGLE_PUBSUB is available for now.
  • options: Options related to the transport.
    • If transport === Transport.GOOGLE_PUBSUB, then have a look at the Google Cloud PubSub config client.
    • debug: Display logs if it is set to true. It uses a pino logger and pino-pretty if NODE_ENV is not equal to production.
    • pinoOptions: If debug is set to true, set the pino logger options. Default to level: debug and prettyPrint: true if NODE_ENV is not equal to production.
    • topicsPrefix: Add a prefix to all created topics. Example: topicsPrefix: 'my-topic', all topics will begin with my-topic+{your topic name}.
    • subscriptionsPrefix: Add a prefix to all created subscriptions. Example: subscriptionsPrefix: 'my-sub', all topics will begin with my-sub%{your topic name}.
    • namespace: Add a namespace property to Message attributes when publishing on a topic.
    • environment: Add a environment property to Message attributes when publishing on a topic.

pubsub.listen(event, opts)

Listen to a specific event.

NOTE: It only uses the Google Cloud subscription pull delivery for now.

  • event: Name of the event.
  • opts: Options related to the Listener method
    • onMessage: Method called when receiving a message
    • onError: Method called when an error occurs
    • options: Option related to the chosen transport

If the chosen transport is Google Cloud PubSub, then options would be:

  • autoAck: Automatically ACK an event as soon as it is received (default to true)
  • subscriptionOptions: Options related to the created Subscription:
  • topicOptions: Options applied to the created topic (have a look at Topic options)

pubsub.emit(event, payload, opts)

Emit a specific event with a payload. It added attributes in the message if you have added a namespace or an environment when setting the PubSubFactory class. It also adds an _eventName and a time property in the emitted payload.

  • event: Name of the event to emit.
  • payload: Payload to send. It will be buffered by Google, and then parsed by the listen method.
  • opts: Options related to the Emit method
    • metadata: Custom metadata added to the message
    • options: Option related to the chosen transport

If the chosen transport is Google Cloud PubSub, then options would be:

  • topicOptions: Options applied to the created topic (have a look at Topic options)

Download Details:

Author: algoan

Source Code: https://github.com/algoan/pubsub

#nodejs #node #javascript

Autumn  Blick

Autumn Blick

1602771720

Learn The Factory Pattern In A Clean Simple Animal Application

To understand what the factory pattern is and why it is useful, I will use a simile. Imagine you are a dealership and want to order some cars for your dealership. you have two options…

  1. Contact a different factory for each type of car you want to get (Audi, Ford, Honda, Ferrari etc…) and tell each one how many cars you want them to create.
  2. Contact a single factory but tell them what type of car you want as well as how many you want

The first option is akin to the old way of instantiating objects (i.e. a class for Audi(), Honda(), BMW(), etc…). The second option is the factory pattern, it would be achieved by a call such as this Audi myAudi = CarFactory.getCar(“audi”).

Clearly, option two is less cluttered and allows us to have a single point of entry to get any car.

What will we build?

The Factory Pattern requires: an overarching interface, concrete classes that implement the interface, and a class to access and create the concrete classes.

We will create an Animal Factory which will be able to provide us with humans, dogs, and birds

Here is a diagram of our code structure

Image for post

#programming #design-patterns #java #factory-pattern #tutorial

How to implement simple Factory Pattern in Node.js » grokonez

https://grokonez.com/design-pattern/implement-simple-factory-method-pattern-node-js-example

How to implement simple Factory Pattern in Node.js

Instead of using class constructors or new keyword to create an object of a class, we can abstract this process. So, we can determine the type of object at run-time, by the time of generating that class object. The implementation seems like Factory Method, but simpler than Factory Method. This simple Factory is not treated as a standard GoF design pattern, but the approach is common to any place where we want to separate the code that varies a lot from the code that does not vary.

In this tutorial, grokonez shows you how to do it in NodeJs.

Nodejs simple Factory Pattern example

Overview

In this example, we have 3 types of cars: Audi, BMW, Mercedes. The car generating process depends on the input string "Audi" or "BMW" or "Mercedes".

CarFactory is the Factory class. In the client, we won’t use new keyword but create() method to create a new car:


const BMW = CarFactory.create('BMW');

Sample Structure

nodejs-simple-factory-pattern-example-sample-structure

Implement simple Factory Pattern in Nodejs

Create default class

This Car class is a parent class for Audi, BMW, Mercedes class that we're gonna create in the next steps.

default_car.js


class Car {
    constructor(name) {
        this.name = name + '-' + Math.random().toString(36).substring(2, 15);
    }

    showInfo() {
        console.log(`I'm ${this.name}`)
    }
}

module.exports = Car;

This class has constructor method that assign a generated id to the car’s name and a showInfo() method to show the name field.

Create subclasses of default class

Now we create 3 classes: Audi, BMW, Mercedes that extends default Car class above.

More at:

https://grokonez.com/design-pattern/implement-simple-factory-method-pattern-node-js-example

How to implement simple Factory Pattern in Node.js

#nodejs #factory #pattern