3.0.2 • Published 2 years ago

before-after-hook v3.0.2

Weekly downloads
3,416,725
License
Apache-2.0
Repository
github
Last release
2 years ago

before-after-hook

asynchronous hooks for internal functionality

npm downloads Test

Usage

<script type="module">
  import Hook from "https://cdn.skypack.dev/before-after-hook";
</script>

Install with npm install before-after-hook

import Hook from "before-after-hook";

Singular hook

// instantiate singular hook API
const hook = new Hook.Singular();

// Create a hook
async function getData(options) {
  try {
    const result = await hook(fetchFromDatabase, options);
    return handleData(result);
  } catch (error) {
    return handleGetError(error);
  }
}

// register before/error/after hooks.
// The methods can be async or return a promise
hook.before(beforeHook);
hook.error(errorHook);
hook.after(afterHook);

getData({ id: 123 });

Hook collection

// instantiate hook collection API
const hookCollection = new Hook.Collection();

// Create a hook
async function getData(options) {
  try {
    const result = await hookCollection("get", fetchFromDatabase, options);
    return handleData(result);
  } catch (error) {
    return handleGetError(error);
  }
}

// register before/error/after hooks.
// The methods can be async or return a promise
hookCollection.before("get", beforeHook);
hookCollection.error("get", errorHook);
hookCollection.after("get", afterHook);

getData({ id: 123 });

Hook.Singular vs Hook.Collection

There's no fundamental difference between the Hook.Singular and Hook.Collection hooks except for the fact that a hook from a collection requires you to pass along the name. Therefore the following explanation applies to both code snippets as described above.

The methods are executed in the following order

  1. beforeHook
  2. fetchFromDatabase
  3. afterHook
  4. handleData

beforeHook can mutate options before it’s passed to fetchFromDatabase.

If an error is thrown in beforeHook or fetchFromDatabase then errorHook is called next.

If afterHook throws an error then handleGetError is called instead of handleData.

If errorHook throws an error then handleGetError is called next, otherwise afterHook and handleData.

You can also use hook.wrap to achieve the same thing as shown above (collection example):

hookCollection.wrap("get", async (getData, options) => {
  await beforeHook(options);

  try {
    const result = getData(options);
  } catch (error) {
    await errorHook(error, options);
  }

  await afterHook(result, options);
});

API

Singular hook API

Singular constructor

The Hook.Singular constructor has no options and returns a hook instance with the methods below:

const hook = new Hook.Singular();

Using the singular hook is recommended for TypeScript

Singular API

The singular hook is a reference to a single hook. This means that there's no need to pass along any identifier (such as a name as can be seen in the Hook.Collection API).

The API of a singular hook is exactly the same as a collection hook and we therefore suggest you read the Hook.Collection API and leave out any use of the name argument. Just skip it like described in this example:

const hook = new Hook.Singular();

// good
hook.before(beforeHook);
hook.after(afterHook);
hook(fetchFromDatabase, options);

// bad
hook.before("get", beforeHook);
hook.after("get", afterHook);
hook("get", fetchFromDatabase, options);

Hook collection API

Collection constructor

The Hook.Collection constructor has no options and returns a hookCollection instance with the methods below

const hookCollection = new Hook.Collection();

hookCollection.api

Use the api property to return the public API:

That way you don’t need to expose the hookCollection() method to consumers of your library

hookCollection()

Invoke before and after hooks. Returns a promise.

hookCollection(nameOrNames, method /*, options */);

Resolves with whatever method returns or resolves with. Rejects with error that is thrown or rejected with by

  1. Any of the before hooks, whichever rejects / throws first
  2. method
  3. Any of the after hooks, whichever rejects / throws first

Simple Example

hookCollection(
  "save",
  (record) => {
    return store.save(record);
  },
  record
);
// shorter:  hookCollection('save', store.save, record)

hookCollection.before("save", function addTimestamps(record) {
  const now = new Date().toISOString();
  if (record.createdAt) {
    record.updatedAt = now;
  } else {
    record.createdAt = now;
  }
});

Example defining multiple hooks at once.

hookCollection(
  ["add", "save"],
  (record) => {
    return store.save(record);
  },
  record
);

hookCollection.before("add", function addTimestamps(record) {
  if (!record.type) {
    throw new Error("type property is required");
  }
});

hookCollection.before("save", function addTimestamps(record) {
  if (!record.type) {
    throw new Error("type property is required");
  }
});

Defining multiple hooks is helpful if you have similar methods for which you want to define separate hooks, but also an additional hook that gets called for all at once. The example above is equal to this:

hookCollection(
  "add",
  (record) => {
    return hookCollection(
      "save",
      (record) => {
        return store.save(record);
      },
      record
    );
  },
  record
);

hookCollection.before()

Add before hook for given name.

hookCollection.before(name, method);

Example

hookCollection.before("save", function validate(record) {
  if (!record.name) {
    throw new Error("name property is required");
  }
});

hookCollection.error()

Add error hook for given name.

hookCollection.error(name, method);

Example

hookCollection.error("save", (error, options) => {
  if (error.ignore) return;
  throw error;
});

hookCollection.after()

Add after hook for given name.

hookCollection.after(name, method);

Example

hookCollection.after("save", (result, options) => {
  if (result.updatedAt) {
    app.emit("update", result);
  } else {
    app.emit("create", result);
  }
});

hookCollection.wrap()

Add wrap hook for given name.

hookCollection.wrap(name, method);

Example

hookCollection.wrap("save", async (saveInDatabase, options) => {
  if (!record.name) {
    throw new Error("name property is required");
  }

  try {
    const result = await saveInDatabase(options);

    if (result.updatedAt) {
      app.emit("update", result);
    } else {
      app.emit("create", result);
    }

    return result;
  } catch (error) {
    if (error.ignore) return;
    throw error;
  }
});

See also: Test mock example

hookCollection.remove()

Removes hook for given name.

hookCollection.remove(name, hookMethod);

Example

hookCollection.remove("save", validateRecord);

TypeScript

This library contains type definitions for TypeScript.

Type support for Singular:

import Hook from "before-after-hook";

type TOptions = { foo: string }; // type for options
type TResult = { bar: number }; // type for result
type TError = Error; // type for error

const hook = new Hook.Singular<TOptions, TResult, TError>();

hook.before((options) => {
  // `options.foo` has `string` type

  // not allowed
  options.foo = 42;

  // allowed
  options.foo = "Forty-Two";
});

const hookedMethod = hook(
  (options) => {
    // `options.foo` has `string` type

    // not allowed, because it does not satisfy the `R` type
    return { foo: 42 };

    // allowed
    return { bar: 42 };
  },
  { foo: "Forty-Two" }
);

You can choose not to pass the types for options, result or error. So, these are completely valid:

const hook = new Hook.Singular<O, R>();
const hook = new Hook.Singular<O>();
const hook = new Hook.Singular();

In these cases, the omitted types will implicitly be any.

Type support for Collection:

Collection also has strict type support. You can use it like this:

import { Hook } from "before-after-hook";

type HooksType = {
  add: {
    Options: { type: string };
    Result: { id: number };
    Error: Error;
  };
  save: {
    Options: { type: string };
    Result: { id: number };
  };
  read: {
    Options: { id: number; foo: number };
  };
  destroy: {
    Options: { id: number; foo: string };
  };
};

const hooks = new Hook.Collection<HooksType>();

hooks.before("destroy", (options) => {
  // `options.id` has `number` type
});

hooks.error("add", (err, options) => {
  // `options.type` has `string` type
  // `err` is `instanceof Error`
});

hooks.error("save", (err, options) => {
  // `options.type` has `string` type
  // `err` has type `any`
});

hooks.after("save", (result, options) => {
  // `options.type` has `string` type
  // `result.id` has `number` type
});

You can choose not to pass the types altogether. In that case, everything will implicitly be any:

const hook = new Hook.Collection();

Alternative imports:

import { Singular, Collection } from "before-after-hook";

const hook = new Singular();
const hooks = new Collection();

Upgrading to 1.4

Since version 1.4 the Hook constructor has been deprecated in favor of returning Hook.Singular in an upcoming breaking release.

Version 1.4 is still 100% backwards-compatible, but if you want to continue using hook collections, we recommend using the Hook.Collection constructor instead before the next release.

For even more details, check out the PR.

See also

If before-after-hook is not for you, have a look at one of these alternatives:

License

Apache 2.0

@octokit/corearchetype-libraryeasy-select-rnreact-native-bluetooth2killi8n-react-native-fast-imageairscanairscan-examplenickvanw-octokit-restreact-native-esc-pos-sahaab@borisovart/atol-kkt-module@frxf/frxfdeneme323112@ntt_app/react-native-custom-notificationreact-native-covid-sdkreact-native-printer-brothersreact-native-shekhar-bridge-testcogoportutils@oiti/documentoscopy-react-native@mink-opn/build-tokensquoc-testluminos-ui-core@everything-registry/sub-chunk-1225jawwy-sdkjawwy_gamification_releasereact-native-sphereuisphereuijawwy_libraryreact-native-credit-card-pkg@rabailriaz/hisaab-web-portalreact-native-jawwy_sampledate-to-block-eth@deriv-com/translationsdemo-test-scrn@doyokit/core@drupal-kit/corefawaterak-online-paymentfawatrak-online-paymentfixed_form_builderfluent.adflow.reactnativesdkfluent.adflow.reactnativesdk-alphafmsldogandev-simple-toastexpo-renavigate@hbglobal/react-native-actions-shortcuts@hawkingnetwork/react-native-tab-view@gr2m/octokit-rest-browser-experimental@geeky-apo/react-native-advanced-clipboard@hoodie/account-client@hoodie/admin-clientnpm-all-packages@hemith/react-native-tnk@hieuquang2212/formnpm_qwertyjamuskalimnpm_one_1_2_3npm_one_2_2npm_one_12_34_1_@blusalt-sdk/react-native-blusalt-document-verificationgriffin-ui-library@enkeledi/react-native-week-month-date-pickergh-monoproject-climiguelcostero-ng2-toastygogencygogency-test-2@felipesimmi/react-native-datalogic-modulenative-apple-loginnative-date-picker-module@extrieve_technologies/quickcapture_react_nativegamification-integration-newgenerator-bootstrap-boilerplate-templateframework_test_library_sixdeeframework_test_library_sixdee_newframework_test_library_sixdee_new_newgenerator-webdesign-boilerplategenz-native-elementsgaurav-react-native-loopgit-branching-workflowgit-repo-initnative-kakao-loginnative-modal-damage-vehiclenative-google-loginnew-awesome-4321hong1-utils@innoswap/default-token-listjrennsoh88-react-native-scroll-indicatorjshawl-octokit-rest-no-at-sign@innodata/vue-v3-ya-metrikajordy-frijters-test-lib@idas1/ui-component-lib@jasonetco/action-record@jellywelly/iterare@kalkanisys/vue-selectl2forlernapnm-yph-react-native-custom-components@jfilipe-sparta/react-native-module_2khaled-salem-custom-componentspayutestingjawwy_library_newjawy_library_v1gamification-jawwy-library
3.0.2

2 years ago

3.0.1

2 years ago

3.0.0

2 years ago

2.2.3

2 years ago

2.2.2

3 years ago

2.2.1

3 years ago

2.2.0

3 years ago

2.1.1

3 years ago

2.1.0

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.4.0

5 years ago

1.3.2

5 years ago

1.3.1

5 years ago

1.3.0

5 years ago

1.2.0

5 years ago

1.1.0

6 years ago

1.0.2

6 years ago

1.0.1

7 years ago

1.0.0

7 years ago