UNPKG

3.09 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var collection_1 = require("../util/collection");
4/**
5 * Shopify App Bridge can be extended with hooks, which run when actions are dispatched and updated.
6 * Hooks are middleware functions that can modify or cancel actions.
7 *
8 * The [validation middleware](../validate/README.md) is implemented using hooks.
9 *
10 * @remarks
11 * Here’s an example hook that modifies all Toast show actions to have a duration of five seconds.
12 *
13 * ```ts
14 * import createApp, {LifecycleHook, DispatchActionHook} from '@shopify/app-bridge';
15 * import {Toast} from '@shopify/app-bridge/actions'
16 *
17 * const app = createApp({apiKey: API_KEY, shopOrigin: SHOP_ORIGIN});
18 *
19 * function makeToastsFiveSeconds: DispatchActionHook(next) {
20 * return function(action){
21 * if(action.type === Toast.ActionType.SHOW) {
22 * const modifiedAction = {
23 * ...action,
24 * payload: {
25 * ...action.payload,
26 * duration: 5000,
27 * },
28 * };
29 * return next(modifiedAction);
30 * } else {
31 * // don’t modify non-Toast actions
32 * return next(action);
33 * }
34 * }
35 * }
36 *
37 * app.hooks.set(LifecycleHook.DispatchAction, makeToastsFiveSeconds);
38 * ```
39 *
40 * The hook function `makeToastsFiveSeconds()` takes a `next()` function as its argument.
41 * The hook function returns an anonymous function, which takes the action being dispatched as its argument.
42 *
43 * To modify an action, call `next()` with the modified action, as in the example.
44 * To cancel an action, don’t call `next()`, and the action will not be dispatched.
45 */
46var Hooks = /** @class */ (function () {
47 function Hooks() {
48 this.map = {};
49 }
50 Hooks.prototype.set = function (hook, handler) {
51 if (!this.map.hasOwnProperty(hook)) {
52 this.map[hook] = [];
53 }
54 var value = { handler: handler, remove: function () { } };
55 var remove = collection_1.addAndRemoveFromCollection(this.map[hook], value);
56 value = { handler: handler, remove: remove };
57 return remove;
58 };
59 Hooks.prototype.get = function (hook) {
60 var value = this.map[hook];
61 return value ? value.map(function (val) { return val.handler; }) : undefined;
62 };
63 Hooks.prototype.run = function (hook, final, context) {
64 var initialArgs = [];
65 for (var _i = 3; _i < arguments.length; _i++) {
66 initialArgs[_i - 3] = arguments[_i];
67 }
68 var index = 0;
69 var handlers = this.get(hook) || [];
70 function handler() {
71 var args = [];
72 for (var _i = 0; _i < arguments.length; _i++) {
73 args[_i] = arguments[_i];
74 }
75 var childHandler = handlers[index++];
76 if (childHandler) {
77 return childHandler(handler).apply(context, args);
78 }
79 return final.apply(context, args);
80 }
81 return handler.apply(context, initialArgs);
82 };
83 return Hooks;
84}());
85exports.default = Hooks;