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

@poppinss/manager

v5.0.2

Published

The builder (Manager) pattern implementation

Downloads

81,311

Readme

Manager Pattern

Implementation of the Manager pattern used by AdonisJS

gh-workflow-image typescript-image npm-image license-image synk-image

Manager pattern is a way to ease the construction of objects of similar nature. To understand it better, we will follow an imaginary example through out this document.

Table of contents

Scanerio

Let's imagine we are creating a mailing library and it supports multiple drivers like: SMTP, Mailgun, PostMark and so on. Also, we want the users of our library to use each driver for multiple times using different configuration. For example:

Using the Mailgun driver with different accounts. Maybe one account for sending promotional emails and another account for sending transactional emails.

Basic implementation

The simplest way to expose the drivers, is to export them directly and let the consumer construct instances of them. For example:

import { Mailgun } from 'my-mailer-library'

const promotional = new Mailgun(configForPromtional)
const transactional = new Mailgun(configForTransactional)

promotional.send()
transactional.send()

The above approach works perfect, but has few drawbacks

  • If the construction of the drivers needs more than one constructor arguments, then it will become cumbersome for the consumer to satisfy all those dependencies.
  • They will have to manually manage the lifecycle of the constructed objects. Ie promotional and transactional in this case.

Using a Manager Class

What we really need is a Manager to manage and construct these objects in the most ergonomic way.

Step1: Define a sample config object.

First step is to move the mappings to a configuration file. The config mimics the same behavior we were trying to achieve earlier (in the Basic example), but defines it declaratively this time.

const mailersConfig = {
  default: 'transactional',

  list: {
    transactional: {
      driver: 'mailgun',
    },

    promotional: {
      driver: 'mailgun',
    },
  },
}

Step 2: Create manager class and accept mappings config

import { Manager } from '@poppinss/manager'

class MailManager implements Manager {
  protected singleton = true

  constructor(private config) {
    super({})
  }
}

Step 3: Using the config to constructor drivers

The Base Manager class will do all the heavy lifting for you. However, you will have to define certain methods to resolve the values from the config file.

import { Manager } from '@poppinss/manager'

class MailManager implements Manager {
  protected singleton = true

  protected getDefaultMappingName() {
    return this.config.default
  }

  protected getMappingConfig(mappingName: string) {
    return this.config.list[mappingName]
  }

  protected getMappingDriver(mappingName: string) {
    return this.config.list[mappingName].driver
  }

  constructor(private config) {
    super({})
  }
}

Step 4: Move drivers construction into the manager class

The final step is to write the code for constructing drivers. The Base Manager uses a convention for this. Anytime the consumer will ask for the mailgun driver, it will invoke createMailgun method. So the convention here is to prefix create followed by the camelCase driver name.

import { Manager } from '@poppinss/manager'

class MailManager implements Manager {
  // ... The existing code

  public createMailgun(mappingName, config) {
    return new Mailgun(config)
  }

  public createSmtp(mappingName, config) {
    return new Smtp(config)
  }
}

Usage

Once done, the consumer of the Mailer class just needs to define the mappings config and they are good to go.

const mailersConfig = {
  default: 'transactional',

  list: {
    transactional: {
      driver: 'mailgun',
    },

    promotional: {
      driver: 'mailgun',
    },
  },
}

const mailer = new MailManager(mailersConfig)

mailer.use('transactional').send()
mailer.use('promotional').send()
  • The lifecycle of the mailers is now encapsulated within the manager class. The consumer can call mailer.use() as many times as they want, without worrying about creating too many un-used objects.
  • They just need to define the mailers config once and get rid of any custom code required to construct individual drivers.

Extending from outside-in

The Base Manager class comes with first class support for adding custom drivers from outside-in using the extend method.

const mailer = new MailManager(mailersConfig)

mailer.extend('postmark', (manager, mappingName, config) => {
  return new PostMark(config)
})

The extend method receives a total of three arguments:

  • The manager object is the reference to the mailer object.
  • The name of the mapping inside the config file.
  • The actual configuration object.
  • The callback should return an instance of the Driver.

Driver Interface

The Manager class can also leverage static Typescript types to have better intellisense support and also ensure that the drivers added using the extend method adhere to a given interface.

Defining Drivers Interface

Following is a dummy interface, we expect all drivers to adhere too

interface DriverContract {
  send(): Promise<void>
}

Passing interface to Manager

import { Manager } from '@poppinss/manager'
import { DriverContract } from './Contracts'

class MailManager implements Manager<DriverContract> {}

Mappings Type

The mappings config currently has any type and hence, the mailer.use method cannot infer correct return types.

In order to improve intellisense for the use method. You will have to define a type for the mappings too.

type MailerMappings = {
  transactional: Mailgun
  promotional: Mailgun
}

type MailerConfig = {
  default: keyof MailerMappings
  list: {
    [K in keyof MailerMappings]: any
  }
}

const mailerConfig: MailerConfig = {
  default: 'transactional',

  list: {
    transactional: {
      driver: 'mailgun',
      // ...
    },

    promotional: {
      driver: 'mailgun',
      // ...
    },
  },
}

Finally, pass the MailerMappings to the Base Manager class

import { DriverContract, MailerMappings } from './Contracts'

class MailManager implements Manager<DriverContract, DriverContract, MailerMappings> {}

Once mailer mappings have been defined, the use method will have proper return types.

Mapping suggestions

Return type