1 | import { HooksInterface, LifecycleHandler, LifecycleHook } from './types';
|
2 | /**
|
3 | * Shopify App Bridge can be extended with hooks, which run when actions are dispatched and updated.
|
4 | * Hooks are middleware functions that can modify or cancel actions.
|
5 | *
|
6 | * The [validation middleware](../validate/README.md) is implemented using hooks.
|
7 | *
|
8 | * @remarks
|
9 | * Here’s an example hook that modifies all Toast show actions to have a duration of five seconds.
|
10 | *
|
11 | * ```ts
|
12 | * import createApp, {LifecycleHook, DispatchActionHook} from '@shopify/app-bridge';
|
13 | * import {Toast} from '@shopify/app-bridge/actions'
|
14 | *
|
15 | * const app = createApp({apiKey: API_KEY, shopOrigin: SHOP_ORIGIN});
|
16 | *
|
17 | * function makeToastsFiveSeconds: DispatchActionHook(next) {
|
18 | * return function(action){
|
19 | * if(action.type === Toast.ActionType.SHOW) {
|
20 | * const modifiedAction = {
|
21 | * ...action,
|
22 | * payload: {
|
23 | * ...action.payload,
|
24 | * duration: 5000,
|
25 | * },
|
26 | * };
|
27 | * return next(modifiedAction);
|
28 | * } else {
|
29 | * // don’t modify non-Toast actions
|
30 | * return next(action);
|
31 | * }
|
32 | * }
|
33 | * }
|
34 | *
|
35 | * app.hooks.set(LifecycleHook.DispatchAction, makeToastsFiveSeconds);
|
36 | * ```
|
37 | *
|
38 | * The hook function `makeToastsFiveSeconds()` takes a `next()` function as its argument.
|
39 | * The hook function returns an anonymous function, which takes the action being dispatched as its argument.
|
40 | *
|
41 | * To modify an action, call `next()` with the modified action, as in the example.
|
42 | * To cancel an action, don’t call `next()`, and the action will not be dispatched.
|
43 | */
|
44 | export default class Hooks implements HooksInterface {
|
45 | private map;
|
46 | set(hook: LifecycleHook, handler: LifecycleHandler): () => boolean;
|
47 | get(hook: LifecycleHook): LifecycleHandler[] | undefined;
|
48 | run<C>(hook: LifecycleHook, final: Function, context: C, ...initialArgs: any[]): any;
|
49 | }
|