once-loader

1.0.1 • Public • Published

once-loader

A set of classes for TypeScript to fetch content asynchronously in one go.

The component has zero dependencies and can be installed as simple as:

npm install --save once-loader

The following classes are included to make your life easier.

OnceLoader

A class to invoke loader thunk just once no matter how many times the fetch function was called.

There are two ways to initialize the loader - either as an object or as a function.

// initialize as an object
const loader = new OnceLoader(
    async () => 'any data here'
);

// loader thunk will be called just once, but the data will be returned for every promise
Promise.all(
  [
    loader.fetch(),
    loader.fetch(),
    loader.fetch(),
  ]
);

or

// initialize as a function
const loadData = OnceLoader.callable(
    async () => 'any data here'
);

// loader thunk will be called just once, but the data will be returned for every promise
Promise.all(
  [
    loadData(),
    loadData(),
    loadData(),
  ]
);

OnceLoaderMap

A class to create pre-charged functions for a content that would be loaded just once.

// initialize the loader
const loader = new OnceLoaderMap(
    async () => {
      return new Map(
        [
          [ 'setting1', 'value1' ],
          [ 'setting2', 'value2' ],
        ]
      );
    }
 );

// you may for sure fetch values directly with providing an optional default value as a fallback
const firstValue = await loader.fetch('setting1');

// however, the primary feature is to let you create bound functions that would invoke loader thunk just once when the first of the functions is called
const getFirstSetting = loader.callable('setting1');
const getSecondSetting = loader.callable('setting2');
const getThirdSetting = loader.callable('non-existent', 'my-default-value-here');
 
// all settings will be loaded at once when the first setting is requested
// you may request them simultaneously or one by one
console.log(await getFirstSetting());  // output: value1
console.log(await getSecondSetting());  // output: value2
console.log(await getThirdSetting());  // output: my-default-value-here

RecordLoader

A class to fetch data for all keys in one go with respect to arguments. This is an alternative to DataLoader with by-arguments grouping feature.

Same way as OnceLoader you may use it either as an object or as a bound function.

// initialize as a function
const loadFriendsOfUser = RecordLoader.callable(
  async (userIds: string[], ageFrom: number = 0, ageTo: number = 99) => {
    const rows = [
      { id: '1', friendOf: '3' },
      { id: '2', friendOf: '3' },
      { id: '3', friendOf: '1' },
      { id: '4', friendOf: '2' },
    ];
    return userIds.map(
      (userId) => rows.filter(
        (row) => row.friendOf === userId
      )
    );
  }
);

// mock simultaneous requests for multiple keys
Promise.all(
  [
    // first two calls will invoke the loader once for keys 1 and 2 with arguments 18 and 25
    loadFriendsOfUser('1', 18, 25),
    loadFriendsOfUser('2', 18, 25),
    // the other two calls will invoke the loader once for keys 3 and 4 with arguments 0 and 99 (defaults)
    loadFriendsOfUser('3'),
    loadFriendsOfUser('4'),
  ]
);

Regardless of the way you initialize (as an object or as a bound function), you may pass a delay parameter as well as a keyGenerator function. Key generator function is used to group calls with the same arguments together.

The default key generator function takes best effort to distinguish between different set of parameters by creating JSON.strigify()-ed version of arguments object. Please note, if your custom key generator returns same keys for different arguments, the arguments of the first fetch() call will take precedence and are to be passed as a loader function parameters.

// initialize as an object
const loadFriendsOfUser = new RecordLoader(
  async (userIds: string[], ageFrom: number = 0, ageTo: number = 99) => {
    const rows = [
      { id: '1', friendOf: '3' },
      { id: '2', friendOf: '3' },
      { id: '3', friendOf: '1' },
      { id: '4', friendOf: '2' },
    ];
    return userIds.map(
      (userId) => rows.filter(
        (row) => row.friendOf === userId
      )
    );
  },
  100,  // delay in ms to wait for more keys to be requsted before calling the loader function
  (ageFrom: number = 0, ageTo: number = 99) => `${ageFrom}-${ageTo}`  // custom key generator function
);

// mock simultaneous requests for multiple keys
Promise.all(
  [
    // first two calls will invoke the loader once for keys 1 and 2 with arguments 18 and 25
    loadFriendsOfUser('1', 18, 25),  // group key: `18-25`
    loadFriendsOfUser('2', 18, 25),  // group key: `18-25`
    // the other two calls will invoke the loader once for keys 3 and 4 with arguments 0 and 99 (defaults)
    loadFriendsOfUser('3'),  // group key: `0-99`
    loadFriendsOfUser('4'),  // group key: `0-99`
  ]
);

Important notes:

  • Loader function MUST return an array of values of the same size and in the same order as input keys array
  • Using consecutive await statements or await statements in a loop won't allow grouping optimization to happen
  • It's recommended to keep your arguments relatively simple (no large BLOBs) to avoid perfomance issues on keys generation

Enjoy!

Package Sidebar

Install

npm i once-loader

Weekly Downloads

4

Version

1.0.1

License

ISC

Unpacked Size

27.6 kB

Total Files

11

Last publish

Collaborators

  • odian