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

flex-hook

v1.0.10

Published

Flexible hook

Downloads

268

Readme

Maximum Flexible Hook

Adding hook at everywhere, with every type, every interface, run on every mode to your function.

Build Status npm Coverage Status

Example

Assume you have an order

const order = {
  id          : 10000,
  customer_id : 1000,
  user_id     : 2000,
  items : [
    {
      id       : 1000,
      price    : 200,
      quantity : 2
    },
    {
      id       : 2000,
      price    : 500,
      quantity : 2
    }
  ]
};

The following function generates excel rows for each order item, it does nothing except calling hooks

function generateRowsFactory(hook) {
  return async function generateRows(order, summary) {

    const it = { order, summary, result : { rows : [] } };

    await hook('before', [it], 'parallel');

    for (let item of order.items) {

      it.session = { item, row : {} };

      hook('eachItem', [it], 'synchronous');

      it.result.rows.push(it.session.row);
    }

    hook('after', [it], 'synchronous');

    return it.result;
  }
}

const generateRows = Hookable(generateRowsFactory);

Then you can add some hooks

generateRows
  .hook('before', async function fetchUser(it) {
    it.user = await Users.fetch(it.order.user_id);
  })
  .hook('before', async function fetchItems(it) {
    await Promise.all(it.order.items.map(async item => item.detail = await Items.fetch(item.id)));
  })
  .hook('eachItem', function addOrderInfo(it)  {
    const { row } = it.session;
    row.order_id = it.order.id;
    row.user     = it.user.name;
  })
  .hook('eachItem', function addItemInfo(it) {
    const { row, item } = it.session;
    row.title           = item.detail.title;
    row.price           = item.price;
    row.net             = item.detail.price;
    row.quantity        = item.quantity;
    row.total_price     = row.price * row.quantity;
  })
  .hook('after', function calSummary(it) {
    it.summary.total_price = it.result.rows.reduce((sum, row) => sum + row.total_price, 0); 

    it.summary.total_quantity = it.result.rows.reduce((sum, row) => sum + row.quantity, 0); 
  });

Add it works

const summary = { total_price : 0, total_quantity : 0 };

const { rows } = await generateRows(order, summary);

const expectedRows = [
  { order_id : 10000, user : 'Bar', title : 'Nokia N7', price : 200, net : 180, quantity : 2, total_price : 400  },
  { order_id : 10000, user : 'Bar', title : 'Iphone 5', price : 500, net : 400, quantity : 2, total_price : 1000 },
];

const expectedSummary = { total_price : 1400, total_quantity : 4 };

assert.deepEqual(rows, expectedRows);

assert.deepEqual(summary, expectedSummary);

Also, support cloning to reusing and extending

const generateRowsWithCustomer = generateRows.clone();

generateRowsWithCustomer
.hook('before', async function fetchCustomer(it) {
  it.customer = await Customers.fetch(it.order.customer_id);
})
.hook('eachItem', function addCustomerInfo(it) {
  const { row } = it.session;
  row.customer  = it.customer.name;
});

const summary = { total_price : 0, total_quantity : 0 };

const { rows : rowWithCustomer } = await generateRowsWithCustomer(order, summary);

const expectedRowsWithCustomer = [
  { order_id : 10000, customer : 'Foo', user : 'Bar', title : 'Nokia N7', price : 200, net : 180, quantity : 2, total_price : 400  },
  { order_id : 10000, customer : 'Foo', user : 'Bar', title : 'Iphone 5', price : 500, net : 400, quantity : 2, total_price : 1000 },
];

assert.deepEqual(rowWithCustomer, expectedRowsWithCustomer);

And custom hookable interface with extender

const extender = ({ func, hookStore }) => {
  func.pre = (hook) => {
    hookStore.add('before', hook);
    return func;
  }
  func.post = (hook) => {
    hookStore.add('after', hook);
    return func;
  }
  func.each = (hook) => {
    hookStore.add('eachItem', hook);
    return func;
  }
  return func;
}

// or use built-in creator
const extender = Hookable.extender.create({ pre : 'before', post : 'after', each : 'eachItem' });

const generateRowsWithCustomExtender = Hookable(generateRowsFactory, { extender });

generateRowsWithCustomExtender
.pre(async function fetchUser(it) {
  //...
})
.each(function addItemInfo(it) {
  //...
})
.post(function calSummary(it) {
  //...
});

Topics

Allow client choose which hooks will be invoked with ObjectHookStore

const { HookableFactory, HookStores } = require('flex-hook');

const Hookable = HookableFactory({ HookStore : HookStores.ObjectHookStore });

const hookA = { code : 'A', do : it => it.result.push('A') };
const hookB = { code : 'B', do : it => it.result.push('B') };
const hookC = { code : 'C', do : it => it.result.push('C') };

const f = Hookable(hook => (it, { before = '*' }={}) => {

  hook({ before }, [it], 'synchronous');

  return it;
});

f.hook({ before : [hookA, hookB, hookC] });

assert.deepEqual( 
  f({ result : [] }).result, 
  ['A', 'B', 'C']
);

assert.deepEqual( 
  f({ result : [] }, { before : ['A', 'C'] }).result, 
  ['A', 'C']
);

Hope you enjoy it!