Update packages, change to node16

This commit is contained in:
Lucas Costi
2022-04-05 10:05:12 +10:00
parent ab59b778e5
commit a8dd2c1169
542 changed files with 66325 additions and 65198 deletions

View File

@@ -11,47 +11,46 @@
### Singular hook
Recommended for [TypeScript](#typescript)
```js
// instantiate singular hook API
const hook = new Hook.Singular()
const hook = new Hook.Singular();
// Create a hook
function getData (options) {
function getData(options) {
return hook(fetchFromDatabase, options)
.then(handleData)
.catch(handleGetError)
.catch(handleGetError);
}
// register before/error/after hooks.
// The methods can be async or return a promise
hook.before(beforeHook)
hook.error(errorHook)
hook.after(afterHook)
hook.before(beforeHook);
hook.error(errorHook);
hook.after(afterHook);
getData({id: 123})
getData({ id: 123 });
```
### Hook collection
```js
// instantiate hook collection API
const hookCollection = new Hook.Collection()
const hookCollection = new Hook.Collection();
// Create a hook
function getData (options) {
return hookCollection('get', fetchFromDatabase, options)
function getData(options) {
return hookCollection("get", fetchFromDatabase, options)
.then(handleData)
.catch(handleGetError)
.catch(handleGetError);
}
// 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)
hookCollection.before("get", beforeHook);
hookCollection.error("get", errorHook);
hookCollection.after("get", afterHook);
getData({id: 123})
getData({ id: 123 });
```
### Hook.Singular vs Hook.Collection
@@ -63,7 +62,7 @@ The methods are executed in the following order
1. `beforeHook`
2. `fetchFromDatabase`
3. `afterHook`
4. `getData`
4. `handleData`
`beforeHook` can mutate `options` before its passed to `fetchFromDatabase`.
@@ -71,25 +70,25 @@ 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 `getData`.
of `handleData`.
If `errorHook` throws an error then `handleGetError` is called next, otherwise
`afterHook` and `getData`.
`afterHook` and `handleData`.
You can also use `hook.wrap` to achieve the same thing as shown above (collection example):
```js
hookCollection.wrap('get', async (getData, options) => {
await beforeHook(options)
hookCollection.wrap("get", async (getData, options) => {
await beforeHook(options);
try {
const result = getData(options)
const result = getData(options);
} catch (error) {
await errorHook(error, options)
await errorHook(error, options);
}
await afterHook(result, options)
})
await afterHook(result, options);
});
```
## Install
@@ -122,8 +121,9 @@ The `Hook.Singular` constructor has no options and returns a `hook` instance wit
methods below:
```js
const hook = new Hook.Singular()
const hook = new Hook.Singular();
```
Using the singular hook is recommended for [TypeScript](#typescript)
### Singular API
@@ -131,30 +131,31 @@ Using the singular hook is recommended for [TypeScript](#typescript)
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](#hookcollectionapi)).
The API of a singular hook is exactly the same as a collection hook and we therefore suggest you read the [Hook.Collection API](#hookcollectionapi) and leave out any use of the `name` argument. Just skip it like described in this example:
```js
const hook = new Hook.Singular()
const hook = new Hook.Singular();
// good
hook.before(beforeHook)
hook.after(afterHook)
hook(fetchFromDatabase, options)
hook.before(beforeHook);
hook.after(afterHook);
hook(fetchFromDatabase, options);
// bad
hook.before('get', beforeHook)
hook.after('get', afterHook)
hook('get', fetchFromDatabase, options)
hook.before("get", beforeHook);
hook.after("get", afterHook);
hook("get", fetchFromDatabase, options);
```
## Hook collection API
- [Collection constructor](#collection-constructor)
- [collection.api](#collectionapi)
- [collection()](#collection)
- [collection.before()](#collectionbefore)
- [collection.error()](#collectionerror)
- [collection.after()](#collectionafter)
- [collection.wrap()](#collectionwrap)
- [collection.remove()](#collectionremove)
- [hookCollection.api](#hookcollectionapi)
- [hookCollection()](#hookcollection)
- [hookCollection.before()](#hookcollectionbefore)
- [hookCollection.error()](#hookcollectionerror)
- [hookCollection.after()](#hookcollectionafter)
- [hookCollection.wrap()](#hookcollectionwrap)
- [hookCollection.remove()](#hookcollectionremove)
### Collection constructor
@@ -162,7 +163,7 @@ The `Hook.Collection` constructor has no options and returns a `hookCollection`
methods below
```js
const hookCollection = new Hook.Collection()
const hookCollection = new Hook.Collection();
```
### hookCollection.api
@@ -182,7 +183,7 @@ That way you dont need to expose the [hookCollection()](#hookcollection) meth
Invoke before and after hooks. Returns a promise.
```js
hookCollection(nameOrNames, method /*, options */)
hookCollection(nameOrNames, method /*, options */);
```
<table>
@@ -224,49 +225,65 @@ Rejects with error that is thrown or rejected with by
Simple Example
```js
hookCollection('save', function (record) {
return store.save(record)
}, record)
hookCollection(
"save",
function (record) {
return store.save(record);
},
record
);
// shorter: hookCollection('save', store.save, record)
hookCollection.before('save', function addTimestamps (record) {
const now = new Date().toISOString()
hookCollection.before("save", function addTimestamps(record) {
const now = new Date().toISOString();
if (record.createdAt) {
record.updatedAt = now
record.updatedAt = now;
} else {
record.createdAt = now
record.createdAt = now;
}
})
});
```
Example defining multiple hooks at once.
```js
hookCollection(['add', 'save'], function (record) {
return store.save(record)
}, record)
hookCollection(
["add", "save"],
function (record) {
return store.save(record);
},
record
);
hookCollection.before('add', function addTimestamps (record) {
hookCollection.before("add", function addTimestamps(record) {
if (!record.type) {
throw new Error('type property is required')
throw new Error("type property is required");
}
})
});
hookCollection.before('save', function addTimestamps (record) {
hookCollection.before("save", function addTimestamps(record) {
if (!record.type) {
throw new Error('type property is required')
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:
```js
hookCollection('add', function (record) {
return hookCollection('save', function (record) {
return store.save(record)
}, record)
}, record)
hookCollection(
"add",
function (record) {
return hookCollection(
"save",
function (record) {
return store.save(record);
},
record
);
},
record
);
```
### hookCollection.before()
@@ -274,7 +291,7 @@ hookCollection('add', function (record) {
Add before hook for given name.
```js
hookCollection.before(name, method)
hookCollection.before(name, method);
```
<table>
@@ -307,11 +324,11 @@ hookCollection.before(name, method)
Example
```js
hookCollection.before('save', function validate (record) {
hookCollection.before("save", function validate(record) {
if (!record.name) {
throw new Error('name property is required')
throw new Error("name property is required");
}
})
});
```
### hookCollection.error()
@@ -319,7 +336,7 @@ hookCollection.before('save', function validate (record) {
Add error hook for given name.
```js
hookCollection.error(name, method)
hookCollection.error(name, method);
```
<table>
@@ -354,10 +371,10 @@ hookCollection.error(name, method)
Example
```js
hookCollection.error('save', function (error, options) {
if (error.ignore) return
throw error
})
hookCollection.error("save", function (error, options) {
if (error.ignore) return;
throw error;
});
```
### hookCollection.after()
@@ -365,7 +382,7 @@ hookCollection.error('save', function (error, options) {
Add after hook for given name.
```js
hookCollection.after(name, method)
hookCollection.after(name, method);
```
<table>
@@ -397,13 +414,13 @@ hookCollection.after(name, method)
Example
```js
hookCollection.after('save', function (result, options) {
hookCollection.after("save", function (result, options) {
if (result.updatedAt) {
app.emit('update', result)
app.emit("update", result);
} else {
app.emit('create', result)
app.emit("create", result);
}
})
});
```
### hookCollection.wrap()
@@ -411,7 +428,7 @@ hookCollection.after('save', function (result, options) {
Add wrap hook for given name.
```js
hookCollection.wrap(name, method)
hookCollection.wrap(name, method);
```
<table>
@@ -442,26 +459,26 @@ hookCollection.wrap(name, method)
Example
```js
hookCollection.wrap('save', async function (saveInDatabase, options) {
hookCollection.wrap("save", async function (saveInDatabase, options) {
if (!record.name) {
throw new Error('name property is required')
throw new Error("name property is required");
}
try {
const result = await saveInDatabase(options)
const result = await saveInDatabase(options);
if (result.updatedAt) {
app.emit('update', result)
app.emit("update", result);
} else {
app.emit('create', result)
app.emit("create", result);
}
return result
return result;
} catch (error) {
if (error.ignore) return
throw error
if (error.ignore) return;
throw error;
}
})
});
```
See also: [Test mock example](examples/test-mock-example.md)
@@ -471,7 +488,7 @@ See also: [Test mock example](examples/test-mock-example.md)
Removes hook for given name.
```js
hookCollection.remove(name, hookMethod)
hookCollection.remove(name, hookMethod);
```
<table>
@@ -502,59 +519,123 @@ hookCollection.remove(name, hookMethod)
Example
```js
hookCollection.remove('save', validateRecord)
hookCollection.remove("save", validateRecord);
```
## TypeScript
This library contains type definitions for TypeScript. When you use TypeScript we highly recommend using the `Hook.Singular` constructor for your hooks as this allows you to pass along type information for the options object. For example:
This library contains type definitions for TypeScript.
### Type support for `Singular`:
```ts
import { Hook } from "before-after-hook";
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
interface Foo {
bar: string
num: number;
}
const hook = new Hook.Singular<TOptions, TResult, TError>();
const hook = new Hook.Singular<Foo>();
hook.before((options) => {
// `options.foo` has `string` type
hook.before(function (foo) {
// not allowed
options.foo = 42;
// typescript will complain about the following mutation attempts
foo.hello = 'world'
foo.bar = 123
// allowed
options.foo = "Forty-Two";
});
// yet this is valid
foo.bar = 'other-string'
foo.num = 123
})
const hookedMethod = hook(
(options) => {
// `options.foo` has `string` type
const foo = hook(function(foo) {
// handle `foo`
foo.bar = 'another-string'
}, {bar: 'random-string'})
// not allowed, because it does not satisfy the `R` type
return { foo: 42 };
// foo outputs
{
bar: 'another-string',
num: 123
}
// allowed
return { bar: 42 };
},
{ foo: "Forty-Two" }
);
```
An alternative import:
You can choose not to pass the types for options, result or error. So, these are completely valid:
```ts
import {Singular, Collection} from 'before-after-hook'
const hook = new Hook.Singular<O, R>();
const hook = new Hook.Singular<O>();
const hook = new Hook.Singular();
```
const hook = new Singular<{foo: string}>();
const hookCollection = new Collection();
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:
```ts
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`:
```ts
const hook = new Hook.Collection();
```
Alternative imports:
```ts
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.
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.

View File

@@ -1,82 +1,172 @@
type HookMethod<O, R> = (options: O) => R | Promise<R>
type HookMethod<Options, Result> = (
options: Options
) => Result | Promise<Result>
type BeforeHook<O> = (options: O) => void
type ErrorHook<O, E> = (error: E, options: O) => void
type AfterHook<O, R> = (result: R, options: O) => void
type WrapHook<O, R> = (
hookMethod: HookMethod<O, R>,
options: O
) => R | Promise<R>
type BeforeHook<Options> = (options: Options) => void | Promise<void>
type ErrorHook<Options, Error> = (
error: Error,
options: Options
) => void | Promise<void>
type AfterHook<Options, Result> = (
result: Result,
options: Options
) => void | Promise<void>
type WrapHook<Options, Result> = (
hookMethod: HookMethod<Options, Result>,
options: Options
) => Result | Promise<Result>
type AnyHook<O, R, E> =
| BeforeHook<O>
| ErrorHook<O, E>
| AfterHook<O, R>
| WrapHook<O, R>
type AnyHook<Options, Result, Error> =
| BeforeHook<Options>
| ErrorHook<Options, Error>
| AfterHook<Options, Result>
| WrapHook<Options, Result>
export interface HookCollection {
type TypeStoreKeyLong = 'Options' | 'Result' | 'Error'
type TypeStoreKeyShort = 'O' | 'R' | 'E'
type TypeStore =
| ({ [key in TypeStoreKeyLong]?: any } &
{ [key in TypeStoreKeyShort]?: never })
| ({ [key in TypeStoreKeyLong]?: never } &
{ [key in TypeStoreKeyShort]?: any })
type GetType<
Store extends TypeStore,
LongKey extends TypeStoreKeyLong,
ShortKey extends TypeStoreKeyShort
> = LongKey extends keyof Store
? Store[LongKey]
: ShortKey extends keyof Store
? Store[ShortKey]
: any
export interface HookCollection<
HooksType extends Record<string, TypeStore> = Record<
string,
{ Options: any; Result: any; Error: any }
>,
HookName extends keyof HooksType = keyof HooksType
> {
/**
* Invoke before and after hooks
*/
(
name: string | string[],
hookMethod: HookMethod<any, any>,
options?: any
): Promise<any>
<Name extends HookName>(
name: Name | Name[],
hookMethod: HookMethod<
GetType<HooksType[Name], 'Options', 'O'>,
GetType<HooksType[Name], 'Result', 'R'>
>,
options?: GetType<HooksType[Name], 'Options', 'O'>
): Promise<GetType<HooksType[Name], 'Result', 'R'>>
/**
* Add `before` hook for given `name`
*/
before(name: string, beforeHook: BeforeHook<any>): void
before<Name extends HookName>(
name: Name,
beforeHook: BeforeHook<GetType<HooksType[Name], 'Options', 'O'>>
): void
/**
* Add `error` hook for given `name`
*/
error(name: string, errorHook: ErrorHook<any, any>): void
error<Name extends HookName>(
name: Name,
errorHook: ErrorHook<
GetType<HooksType[Name], 'Options', 'O'>,
GetType<HooksType[Name], 'Error', 'E'>
>
): void
/**
* Add `after` hook for given `name`
*/
after(name: string, afterHook: AfterHook<any, any>): void
after<Name extends HookName>(
name: Name,
afterHook: AfterHook<
GetType<HooksType[Name], 'Options', 'O'>,
GetType<HooksType[Name], 'Result', 'R'>
>
): void
/**
* Add `wrap` hook for given `name`
*/
wrap(name: string, wrapHook: WrapHook<any, any>): void
wrap<Name extends HookName>(
name: Name,
wrapHook: WrapHook<
GetType<HooksType[Name], 'Options', 'O'>,
GetType<HooksType[Name], 'Result', 'R'>
>
): void
/**
* Remove added hook for given `name`
*/
remove(name: string, hook: AnyHook<any, any, any>): void
remove<Name extends HookName>(
name: Name,
hook: AnyHook<
GetType<HooksType[Name], 'Options', 'O'>,
GetType<HooksType[Name], 'Result', 'R'>,
GetType<HooksType[Name], 'Error', 'E'>
>
): void
/**
* Public API
*/
api: Pick<
HookCollection<HooksType>,
'before' | 'error' | 'after' | 'wrap' | 'remove'
>
}
export interface HookSingular<O, R, E> {
export interface HookSingular<Options, Result, Error> {
/**
* Invoke before and after hooks
*/
(hookMethod: HookMethod<O, R>, options?: O): Promise<R>
(hookMethod: HookMethod<Options, Result>, options?: Options): Promise<Result>
/**
* Add `before` hook
*/
before(beforeHook: BeforeHook<O>): void
before(beforeHook: BeforeHook<Options>): void
/**
* Add `error` hook
*/
error(errorHook: ErrorHook<O, E>): void
error(errorHook: ErrorHook<Options, Error>): void
/**
* Add `after` hook
*/
after(afterHook: AfterHook<O, R>): void
after(afterHook: AfterHook<Options, Result>): void
/**
* Add `wrap` hook
*/
wrap(wrapHook: WrapHook<O, R>): void
wrap(wrapHook: WrapHook<Options, Result>): void
/**
* Remove added hook
*/
remove(hook: AnyHook<O, R, E>): void
remove(hook: AnyHook<Options, Result, Error>): void
/**
* Public API
*/
api: Pick<
HookSingular<Options, Result, Error>,
'before' | 'error' | 'after' | 'wrap' | 'remove'
>
}
type Collection = new () => HookCollection
type Singular = new <O = any, R = any, E = any>() => HookSingular<O, R, E>
type Collection = new <
HooksType extends Record<string, TypeStore> = Record<
string,
{ Options: any; Result: any; Error: any }
>
>() => HookCollection<HooksType>
type Singular = new <
Options = any,
Result = any,
Error = any
>() => HookSingular<Options, Result, Error>
interface Hook {
new (): HookCollection
new <
HooksType extends Record<string, TypeStore> = Record<
string,
{ Options: any; Result: any; Error: any }
>
>(): HookCollection<HooksType>
/**
* Creates a collection of hooks

View File

@@ -1,46 +1,46 @@
module.exports = addHook
module.exports = addHook;
function addHook (state, kind, name, hook) {
var orig = hook
function addHook(state, kind, name, hook) {
var orig = hook;
if (!state.registry[name]) {
state.registry[name] = []
state.registry[name] = [];
}
if (kind === 'before') {
if (kind === "before") {
hook = function (method, options) {
return Promise.resolve()
.then(orig.bind(null, options))
.then(method.bind(null, options))
}
.then(method.bind(null, options));
};
}
if (kind === 'after') {
if (kind === "after") {
hook = function (method, options) {
var result
var result;
return Promise.resolve()
.then(method.bind(null, options))
.then(function (result_) {
result = result_
return orig(result, options)
result = result_;
return orig(result, options);
})
.then(function () {
return result
})
}
return result;
});
};
}
if (kind === 'error') {
if (kind === "error") {
hook = function (method, options) {
return Promise.resolve()
.then(method.bind(null, options))
.catch(function (error) {
return orig(error, options)
})
}
return orig(error, options);
});
};
}
state.registry[name].push({
hook: hook,
orig: orig
})
orig: orig,
});
}

View File

@@ -1,28 +1,27 @@
module.exports = register
module.exports = register;
function register (state, name, method, options) {
if (typeof method !== 'function') {
throw new Error('method for before hook must be a function')
function register(state, name, method, options) {
if (typeof method !== "function") {
throw new Error("method for before hook must be a function");
}
if (!options) {
options = {}
options = {};
}
if (Array.isArray(name)) {
return name.reverse().reduce(function (callback, name) {
return register.bind(null, state, name, callback, options)
}, method)()
return register.bind(null, state, name, callback, options);
}, method)();
}
return Promise.resolve()
.then(function () {
if (!state.registry[name]) {
return method(options)
}
return Promise.resolve().then(function () {
if (!state.registry[name]) {
return method(options);
}
return (state.registry[name]).reduce(function (method, registered) {
return registered.hook.bind(null, method, options)
}, method)()
})
return state.registry[name].reduce(function (method, registered) {
return registered.hook.bind(null, method, options);
}, method)();
});
}

View File

@@ -1,17 +1,19 @@
module.exports = removeHook
module.exports = removeHook;
function removeHook (state, name, method) {
function removeHook(state, name, method) {
if (!state.registry[name]) {
return
return;
}
var index = state.registry[name]
.map(function (registered) { return registered.orig })
.indexOf(method)
.map(function (registered) {
return registered.orig;
})
.indexOf(method);
if (index === -1) {
return
return;
}
state.registry[name].splice(index, 1)
state.registry[name].splice(index, 1);
}

View File

@@ -1,7 +1,8 @@
{
"name": "before-after-hook",
"version": "2.1.0",
"version": "2.2.2",
"description": "asynchronous before/error/after hooks for internal functionality",
"main": "index.js",
"files": [
"index.js",
"index.d.ts",
@@ -12,7 +13,9 @@
"prebuild": "rimraf dist && mkdirp dist",
"build": "browserify index.js --standalone=Hook > dist/before-after-hook.js",
"postbuild": "uglifyjs dist/before-after-hook.js -mc > dist/before-after-hook.min.js",
"pretest": "standard",
"lint": "prettier --check '{lib,test,examples}/**/*' README.md package.json",
"lint:fix": "prettier --write '{lib,test,examples}/**/*' README.md package.json",
"pretest": "npm run -s lint",
"test": "npm run -s test:node | tap-spec",
"posttest": "npm run validate:ts",
"test:node": "node test",
@@ -24,10 +27,7 @@
"presemantic-release": "npm run build",
"semantic-release": "semantic-release"
},
"repository": {
"type": "git",
"url": "https://github.com/gr2m/before-after-hook.git"
},
"repository": "github:gr2m/before-after-hook",
"keywords": [
"hook",
"hooks",
@@ -35,26 +35,22 @@
],
"author": "Gregor Martynus",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/gr2m/before-after-hook/issues"
},
"homepage": "https://github.com/gr2m/before-after-hook#readme",
"dependencies": {},
"devDependencies": {
"browserify": "^16.0.0",
"gaze-cli": "^0.2.0",
"istanbul": "^0.4.0",
"istanbul-coveralls": "^1.0.3",
"mkdirp": "^0.5.1",
"rimraf": "^2.4.4",
"semantic-release": "^15.0.0",
"mkdirp": "^1.0.3",
"prettier": "^2.0.0",
"rimraf": "^3.0.0",
"semantic-release": "^17.0.0",
"simple-mock": "^0.8.0",
"standard": "^13.0.1",
"tap-min": "^2.0.0",
"tap-spec": "^5.0.0",
"tape": "^4.2.2",
"tape": "^5.0.0",
"typescript": "^3.5.3",
"uglify-js": "^3.0.0"
"uglify-js": "^3.9.0"
},
"release": {
"publish": [
@@ -67,8 +63,4 @@
}
]
}
,"_resolved": "https://registry.npmjs.org/before-after-hook/-/before-after-hook-2.1.0.tgz"
,"_integrity": "sha512-IWIbu7pMqyw3EAJHzzHbWa85b6oud/yfKYg5rqB5hNE8CeMi3nX+2C2sj0HswfblST86hpVEOAb9x34NZd6P7A=="
,"_from": "before-after-hook@2.1.0"
}
}