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

factsory

v4.1.0

Published

A kind of factory and DI patterns library targeted to Typescript (w/o decorators)

Downloads

56

Readme

factsory Version Badge

npm version GitHub package.json version GitHub Workflow Status dependencies minzipped license

A kind of factory and DI patterns library targeted to Typescript (w/o decorators).

Topics

Installation
How to use
License

Installation

To install Factsory, type the following:

  • with NPM:
npm install factsory
  • with YARN:
yarn add factsory

How to use

Factory definition

  • It's possible to define a factory in two ways:
  1. extending the DefaultFactory class:

      class MyFactory extends DefaultFactory<string> {
        instantiate(): string {
          return "value";
        }
      }
  2. implementing the Factory interface:

       class MyFactory implements Factory<string> {
         create(): string {
           return "value";
         }
       }

Container instance

  • To access the Container instance, just call the Container.I static method

  • It's possible to define a customized Container implementation, useful for testing. You just need to implement the ContainerSpec interface as in the following example (based on jest-mock-extended):

    // using jest-mock-extended package
    const mockedSpec = mock<ContainerSpec>();
    Container.impl = mockedSpec;
     
    // To reset to the default implementation, just call reset()
    Container.reset();

Container registration

  • A class or almost any other object can be registered in the Container, which can be done in two ways:
  1. registering a class (e.g. a factory class - see Factory definition section):

    // id = "MyFactory"
    Container.I.register(MyFactory);
       
    // or
    Container.I.register(MyFactory, { id: "MyFactoryCustomId" });
  2. registering a creation function (factory method) using the createFactoryMethod:

    // id will be set to ""
    Container.I.register(createFactoryMethod(() => "value"));
       
    // or
    Container.I.register(createFactoryMethod(() => "value"), { id: "MyFactoryWithValue" });
       
    // or
    Container.I.register(createFactoryMethod((params?: CreationParameters) => params?.args), { id: "MyFactoryWithArgs", args: "value" });
  • It's also possible to define dependencies, which will be injected during the object creation:

     // the dependency
     class MyFactory extends DefaultFactory<string> {
       instantiate(): string {
         return "aValue";
       }
     }
     
     // the target of the dependency injection
     class MyFactoryWithDependencies extends DefaultFactory<string> {
       protected readonly myFactory: MyFactory;
    
       constructor(
         params?: ContainerItemCreationDependencies<{
           MyFactory: MyFactory;
         }>
       ) {
         super();
         if (params?.dependencies) {
           this.myFactory = params.dependencies.MyFactory;
         } else {
           throw new Error("Invalid dependencies");
         }
    
         if (!this.myFactory) {
           throw new Error("Invalid MyFactory dependency");
         }
       }
     
       get dep(): MyFactory {
         return this.myFactory;
       }
    
       instantiate(): string {
         return "MyuFactoryWithDependencies";
       }
     }  
     
     // registering objects
     Container.I.register(MyFactory);
     Container.I.register(MyFactoryWithDependencies, {
       dependencies: [MyFactory],
     });
     
     // will print 'aValue'
     console.log(Container.I.get(MyFactoryWithDependencies)?.dep.create());

Object claim from Container

  • After registering a class or a creation function (factory method), it can also be claimed in two ways:
  1. If it is a class, it can be claimed by the Container.I.get method using the class name as a parameter:

    Container.I.get(MyFactory);
  2. If it is a creation function, it can be claimed by the Container.I.get method using the registered name as a parameter:

    Container.I.get("MyFactory");

Lazy instance

  • It's possible to use the LazyInstance class to lazy initialize an object:

    let value = "";
    
    const lazyInstance = new LazyInstance(() => (value = "initialized"));
    
    console.log(value);          // prints ""
    console.log(lazyInstance.I); // prints "initialized"
    // or 
    console.log(lazyInstance.getI()); // prints "initialized"
    console.log(value);               // prints "initialized"

Async Lazy instance

  • It's possible to use the AsyncLazyInstance class to lazy initialize an object:

    let value = "";
    
    const asyncLazyInstance = new AsyncLazyInstance(async () => (value = "initialized"));
    
    console.log(value);                     // prints ""
    console.log(await asyncLazyInstance.I); // prints "initialized"
    // or 
    console.log(await asyncLazyInstance.getI()); // prints "initialized"
    console.log(value);                          // prints "initialized"
  • It's also possible to use the AsyncLazyInstance class to lazy initialize an object with concurrency lock (mutex-like) control:

    let value = "";
    
    const asyncLazyInstance = new AsyncLazyInstance(
      async () => (value = "initialized"),
      /** 
       * Using async-mutex lib as an example 
       * @see https://www.npmjs.com/package/async-mutex
       */
      { lock: new Mutex() }
    );
    
    console.log(value);                     // prints ""
    console.log(await asyncLazyInstance.I); // prints "initialized"
    // or 
    console.log(await asyncLazyInstance.getI()); // prints "initialized"
    console.log(value);                          // prints "initialized"
    

License

Copyright (c) 2022 Tiago da Costa Peixoto [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.