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

@alexlafroscia/service-locator

v1.2.0

Published

Serice locator pattern for ES6 classes

Downloads

7

Readme

@alexlafroscia/service-locator

A JS implementation of the Service Locator pattern for ES6 classes.

Features

  • Store commonly-needed values in a single place, allowing easy access to shared state
  • Inject registry access into any ES6 class through a mixin, or extend the provided ES6 class
  • Easily provide stubs for objects in the registry to simplify testing

A quick example

Imagine we have a component that should check if the user is logged in and either prompt for login, or greet the user. We have two parts: fetching the user data, and the component itself.

If you were to use this package, here is how the code might be set up (note that I'm using a fake Component implementation that is something similar to React or Preact):

import { registry, RegistryAccess } from '@alexlafroscia/service-locator';

class UserService {
  fetchUserInfo() {
    return fetch('...').then(res => res.json());
  }

  async isLoggedIn() {
    const { isLoggedIn } = await this.fetch('...');

    return isLoggedin;
  }
};

registry.register('userService', new UserService());

export default class LoggedInComponent extends RegistryAccess.Mixin(Component) {
  async getInitialState() {
    const isLoggedIn = this.userService.isLoggedIn();
    this.setState({ isLoggedIn });
  }

  render({ isLoggedIn }) {
    return isLoggedIn ? 'Hello!' : 'Please log in!';
  }
}

What's the benefit here? For one, we've separated out the thing that fetches the data from the thing that displays it, which is always a good idea. Additionally, we made it easy to stub the data fetching in a test:

test('shows the right thing when the user is logged in', () => {
  registry.stub('userService', {
    async fetchUserInfo() {
      return { isLoggedIn: true };
    }
  });

  const result = render(<Component />);
  expect(result).to.contain('Hello!');
});

test('shows the right thing when the user is not logged in', () => {
  registry.stub('userService', {
    async fetch() {
      return { isLoggedIn: false };
    }
  });

  const result = render(<Component />);
  expect(result).to.contain('Please log in!');
});

Could you make this easier?

In fact, you can. I love the syntax that Ember provides for injecting services, and wanted to emulate that as closely as possible. Through the power of decorators I was able to do it. The downside is that you need a Babel transform for it, but with that in place, we can clean up the implementation a whole lot. Rather than repeating an extended example, check out the examples in the tests.

Why?

I've struggled with making a complex set of components using Skate.js where all components needed access to some state. I didn't want to have pass the properties to every component explicitly, and wished I had an easy way of using service injection the way that I'm used to with Ember.js. So, I started messing around with this.

Should I use this?

Maybe. In reality, it's not that different than just accessing everything off the window, and we all know that's a bad idea (although this works in a Node environment where window isn't available, and is built for use with JavaScript modules where there isn't a shared global context).

Compatibility Notes

This package is meant to be consumed in an ES6 environment. It relies on Proxy and is built with ES6 classes in mind. Make sure your environment can handle this.

Prior Art