-
Notifications
You must be signed in to change notification settings - Fork 151
/
Copy pathfactory.ts
114 lines (100 loc) · 2.43 KB
/
factory.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
import {
PlaidLinkOptions,
PlaidHandler,
PlaidHandlerSubmissionData,
CommonPlaidLinkOptions,
} from './types';
export interface PlaidFactory {
open: (() => void) | Function;
submit: ((data: PlaidHandlerSubmissionData) => void)| Function;
exit: ((exitOptions: any, callback: () => void) => void) | Function;
destroy: (() => void) | Function;
}
interface FactoryInternalState {
plaid: PlaidHandler | null;
open: boolean;
onExitCallback: (() => void) | null | Function;
}
const renameKeyInObject = (
o: { [index: string]: any },
oldKey: string,
newKey: string
): object => {
const newObject = {};
delete Object.assign(newObject, o, { [newKey]: o[oldKey] })[oldKey];
return newObject;
};
/**
* Wrap link handler creation and instance to clean up iframe via destroy() method
*/
const createPlaidHandler = <T extends CommonPlaidLinkOptions<{}>>(
config: T,
creator: (config: T) => PlaidHandler
) => {
const state: FactoryInternalState = {
plaid: null,
open: false,
onExitCallback: null,
};
// If Plaid is not available, throw an Error
if (typeof window === 'undefined' || !window.Plaid) {
throw new Error('Plaid not loaded');
}
state.plaid = creator({
...config,
onExit: (error, metadata) => {
state.open = false;
config.onExit && config.onExit(error, metadata);
state.onExitCallback && state.onExitCallback();
},
});
const open = () => {
if (!state.plaid) {
return;
}
state.open = true;
state.onExitCallback = null;
state.plaid.open();
};
const submit = (data: PlaidHandlerSubmissionData) => {
if (!state.plaid) {
return;
}
state.plaid.submit(data)
}
const exit = (exitOptions: any, callback: (() => void) | Function) => {
if (!state.open || !state.plaid) {
callback && callback();
return;
}
state.onExitCallback = callback;
state.plaid.exit(exitOptions);
if (exitOptions && exitOptions.force) {
state.open = false;
}
};
const destroy = () => {
if (!state.plaid) {
return;
}
state.plaid.destroy();
state.plaid = null;
};
return {
open,
submit,
exit,
destroy,
};
};
export const createPlaid = (
options: PlaidLinkOptions,
creator: (options: PlaidLinkOptions) => PlaidHandler
) => {
const config = renameKeyInObject(
options,
'publicKey',
'key'
) as PlaidLinkOptions;
return createPlaidHandler(config, creator);
};