ag-common 0.0.124 → 0.0.128

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/dist/api/helpers/openApiHelpers.js +2 -3
  2. package/dist/common/helpers/object.d.ts +20 -0
  3. package/dist/common/helpers/object.js +41 -1
  4. package/dist/ui/components/Chevron/index.d.ts +5 -2
  5. package/dist/ui/components/Chevron/index.js +22 -2
  6. package/dist/ui/components/Icon/index.d.ts +1 -1
  7. package/dist/ui/components/Icon/index.js +3 -3
  8. package/dist/ui/components/Prompt/index.js +1 -1
  9. package/dist/ui/components/Sidebar/index.d.ts +12 -0
  10. package/dist/ui/components/Sidebar/index.js +110 -0
  11. package/dist/ui/components/index.d.ts +1 -0
  12. package/dist/ui/components/index.js +1 -0
  13. package/dist/ui/helpers/callOpenApi/cached.d.ts +28 -0
  14. package/dist/ui/helpers/callOpenApi/cached.js +74 -0
  15. package/dist/ui/helpers/{callOpenApi.d.ts → callOpenApi/direct.d.ts} +2 -2
  16. package/dist/ui/helpers/{callOpenApi.js → callOpenApi/direct.js} +11 -13
  17. package/dist/ui/helpers/{useCallOpenApi.d.ts → callOpenApi/hook.d.ts} +7 -2
  18. package/dist/ui/helpers/{useCallOpenApi.js → callOpenApi/hook.js} +12 -21
  19. package/dist/ui/helpers/callOpenApi/index.d.ts +4 -0
  20. package/dist/ui/helpers/callOpenApi/index.js +16 -0
  21. package/dist/ui/helpers/{types.d.ts → callOpenApi/types.d.ts} +1 -1
  22. package/dist/ui/helpers/{types.js → callOpenApi/types.js} +0 -0
  23. package/dist/ui/helpers/index.d.ts +0 -5
  24. package/dist/ui/helpers/index.js +0 -5
  25. package/dist/ui/helpers/jwt.d.ts +4 -0
  26. package/dist/ui/helpers/routes.d.ts +2 -2
  27. package/dist/ui/helpers/useQueryString.d.ts +21 -6
  28. package/dist/ui/helpers/useQueryString.js +37 -31
  29. package/package.json +1 -1
  30. package/dist/ui/helpers/mutex.d.ts +0 -22
  31. package/dist/ui/helpers/mutex.js +0 -53
  32. package/dist/ui/helpers/mutexData.d.ts +0 -17
  33. package/dist/ui/helpers/mutexData.js +0 -55
  34. package/dist/ui/helpers/useOpenApiStore.d.ts +0 -24
  35. package/dist/ui/helpers/useOpenApiStore.js +0 -147
@@ -3,7 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.openApiImpl = void 0;
4
4
  /* eslint-disable no-new */
5
5
  const aws_cdk_lib_1 = require("aws-cdk-lib");
6
- const __1 = require("../..");
7
6
  const array_1 = require("../../common/helpers/array");
8
7
  const log_1 = require("../../common/helpers/log");
9
8
  // eslint-disable-next-line
@@ -51,8 +50,8 @@ const setupLambda = ({ lambdaConfig, pathV, verb, seenPermissions, }) => {
51
50
  //
52
51
  const readTables = (0, array_1.distinctBy)([...(((_a = def === null || def === void 0 ? void 0 : def.dynamo) === null || _a === void 0 ? void 0 : _a.reads) || []), ...(((_b = lp === null || lp === void 0 ? void 0 : lp.dynamo) === null || _b === void 0 ? void 0 : _b.reads) || [])], (s) => s.shortName);
53
52
  const writeTables = (0, array_1.distinctBy)([...(((_c = def === null || def === void 0 ? void 0 : def.dynamo) === null || _c === void 0 ? void 0 : _c.writes) || []), ...(((_d = lp === null || lp === void 0 ? void 0 : lp.dynamo) === null || _d === void 0 ? void 0 : _d.writes) || [])], (s) => s.shortName);
54
- const policies = [...(def.policies || []), ...((lp === null || lp === void 0 ? void 0 : lp.policies) || [])].filter(__1.notEmpty);
55
- const layers = [...(def.layers || []), ...((lp === null || lp === void 0 ? void 0 : lp.layers) || [])].filter(__1.notEmpty);
53
+ const policies = [...(def.policies || []), ...((lp === null || lp === void 0 ? void 0 : lp.policies) || [])].filter(array_1.notEmpty);
54
+ const layers = [...(def.layers || []), ...((lp === null || lp === void 0 ? void 0 : lp.layers) || [])].filter(array_1.notEmpty);
56
55
  const env = Object.assign(Object.assign({}, (def.env || {})), ((lp === null || lp === void 0 ? void 0 : lp.env) || {}));
57
56
  const tables = [...readTables, ...writeTables];
58
57
  const environment = env;
@@ -15,4 +15,24 @@ export interface IArrayType<T> {
15
15
  export declare function objectToArray<T>(obj: {
16
16
  [a: string]: T;
17
17
  }): IArrayType<T>[];
18
+ /**
19
+ * Recursively alphabetically sort an object
20
+ * @param object
21
+ * @param depthLeft
22
+ * @returns
23
+ */
18
24
  export declare const objectAlphaSort: (object: any, depthLeft?: number) => object;
25
+ /**
26
+ * Convert a random object type to a record<string,string>
27
+ * @param entries Could be URLSearchParams
28
+ * @returns
29
+ */
30
+ export declare function paramsToObject(entries: any): Record<string, string>;
31
+ /**
32
+ * stringify an object of key values. Could be used to stringify a querystring url
33
+ * @param obj
34
+ * @param joinKeyValue
35
+ * @param joinKeys
36
+ * @returns
37
+ */
38
+ export declare function objectToString(obj: Record<string, string>, joinKeyValue: string, joinKeys: string): string;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.objectAlphaSort = exports.objectToArray = exports.getObjectKeysAsNumber = exports.objectKeysToLowerCase = exports.isJson = exports.tryJsonParse = void 0;
3
+ exports.objectToString = exports.paramsToObject = exports.objectAlphaSort = exports.objectToArray = exports.getObjectKeysAsNumber = exports.objectKeysToLowerCase = exports.isJson = exports.tryJsonParse = void 0;
4
+ const _1 = require(".");
4
5
  const tryJsonParse = (str, defaultValue) => {
5
6
  if (!str) {
6
7
  return null;
@@ -52,6 +53,12 @@ function objectToArray(obj) {
52
53
  return ret;
53
54
  }
54
55
  exports.objectToArray = objectToArray;
56
+ /**
57
+ * Recursively alphabetically sort an object
58
+ * @param object
59
+ * @param depthLeft
60
+ * @returns
61
+ */
55
62
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
56
63
  const objectAlphaSort = (object, depthLeft = -1) => {
57
64
  if (depthLeft === 0) {
@@ -74,3 +81,36 @@ const objectAlphaSort = (object, depthLeft = -1) => {
74
81
  }
75
82
  };
76
83
  exports.objectAlphaSort = objectAlphaSort;
84
+ /**
85
+ * Convert a random object type to a record<string,string>
86
+ * @param entries Could be URLSearchParams
87
+ * @returns
88
+ */
89
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
90
+ function paramsToObject(entries) {
91
+ const result = {};
92
+ for (const [key, value] of entries) {
93
+ result[key] = value;
94
+ }
95
+ return result;
96
+ }
97
+ exports.paramsToObject = paramsToObject;
98
+ /**
99
+ * stringify an object of key values. Could be used to stringify a querystring url
100
+ * @param obj
101
+ * @param joinKeyValue
102
+ * @param joinKeys
103
+ * @returns
104
+ */
105
+ function objectToString(obj, joinKeyValue, joinKeys) {
106
+ let ret = '';
107
+ if (!obj || Object.keys(obj).length === 0) {
108
+ return ret;
109
+ }
110
+ Object.entries(obj).forEach(([key, value]) => {
111
+ ret += `${joinKeys}${key}${joinKeyValue}${value}`;
112
+ });
113
+ ret = (0, _1.trim)(ret, joinKeyValue);
114
+ return ret;
115
+ }
116
+ exports.objectToString = objectToString;
@@ -1,7 +1,10 @@
1
- export declare const Chevron: ({ down, width, className, colour, onToggle, }: {
1
+ export declare const Chevron: ({ width, className, colour, onToggle, point, }: {
2
+ /**
3
+ * default right
4
+ */
5
+ point: 'up' | 'down' | 'left' | 'right';
2
6
  colour?: string | undefined;
3
7
  className?: string | undefined;
4
8
  width?: string | undefined;
5
- down: boolean;
6
9
  onToggle?: (() => void) | undefined;
7
10
  }) => JSX.Element;
@@ -20,6 +20,26 @@ const IconStyled = (0, styled_components_1.default)(Icon_1.Icon) `
20
20
  `;
21
21
  const ChevronIcon = (react_1.default.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", viewBox: "0 -256 1792 1792" },
22
22
  react_1.default.createElement("path", { d: "M1679.339 301.56q0 53-37 90l-651 651q-38 38-91 38-54 0-90-38l-651-651q-38-36-38-90 0-53 38-91l74-75q39-37 91-37 53 0 90 37l486 486 486-486q37-37 90-37 52 0 91 37l75 75q37 39 37 91z" })));
23
- const Chevron = ({ down, width = '1.2rem', className, colour = 'black', onToggle, }) => (react_1.default.createElement(SChevron, { className: className, onClick: () => onToggle === null || onToggle === void 0 ? void 0 : onToggle(), onTouchStart: () => onToggle === null || onToggle === void 0 ? void 0 : onToggle(), onKeyPress: (e) => e.key === 'Enter' && (onToggle === null || onToggle === void 0 ? void 0 : onToggle()) },
24
- react_1.default.createElement(IconStyled, { flip: down, fill: colour, width: width, height: width }, ChevronIcon)));
23
+ const Chevron = ({ width = '1.2rem', className, colour = 'black', onToggle, point = 'right', }) => {
24
+ let rotate = 0;
25
+ switch (point) {
26
+ case 'down': {
27
+ rotate = 180;
28
+ break;
29
+ }
30
+ case 'left': {
31
+ rotate = 270;
32
+ break;
33
+ }
34
+ case 'up': {
35
+ rotate = 0;
36
+ break;
37
+ }
38
+ case 'right': {
39
+ rotate = 90;
40
+ }
41
+ }
42
+ return (react_1.default.createElement(SChevron, { className: className, onClick: () => onToggle === null || onToggle === void 0 ? void 0 : onToggle(), onTouchStart: () => onToggle === null || onToggle === void 0 ? void 0 : onToggle(), onKeyPress: (e) => e.key === 'Enter' && (onToggle === null || onToggle === void 0 ? void 0 : onToggle()) },
43
+ react_1.default.createElement(IconStyled, { rotate: rotate, fill: colour, width: width, height: width }, ChevronIcon)));
44
+ };
25
45
  exports.Chevron = Chevron;
@@ -5,7 +5,7 @@ interface IIcon {
5
5
  outline?: string;
6
6
  width?: string;
7
7
  height?: string;
8
- flip?: boolean;
8
+ rotate?: number;
9
9
  canHover?: boolean;
10
10
  margin?: string;
11
11
  padding?: string;
@@ -27,12 +27,12 @@ const react_1 = __importDefault(require("react"));
27
27
  const styled_components_1 = __importStar(require("styled-components"));
28
28
  const common_1 = require("../../styles/common");
29
29
  exports.IconF = styled_components_1.default.span `
30
+ transition: all 200ms;
30
31
  display: flex;
31
32
  justify-content: center;
32
33
  align-items: center;
33
34
  font-size: 2rem;
34
35
  padding: ${({ padding }) => padding || '0'};
35
- transition: background-color 200ms;
36
36
  margin: ${({ margin }) => (!margin ? 'unset' : margin)};
37
37
  cursor: ${({ disabled, canHover }) => disabled || !canHover ? 'inherit' : 'pointer'};
38
38
  > svg {
@@ -69,9 +69,9 @@ exports.IconF = styled_components_1.default.span `
69
69
 
70
70
  width: ${({ width }) => width || '100%'};
71
71
  height: ${({ height }) => height || '100%'};
72
- ${({ flip }) => flip &&
72
+ ${({ rotate }) => rotate &&
73
73
  (0, styled_components_1.css) `
74
- transform: rotate(180deg);
74
+ transform: rotate(${rotate}deg);
75
75
  `};
76
76
 
77
77
  svg {
@@ -85,7 +85,7 @@ const PromptModal = ({ wrapper, res, bottomText, topText, okText = 'OK', cancelT
85
85
  react_1.default.createElement(Content, null,
86
86
  topText && react_1.default.createElement(TopText, null, topText),
87
87
  react_1.default.createElement(BottomText, null, bottomText),
88
- react_1.default.createElement(TextInput_1.TextInput, { value: text, onChange: (c) => setText(c), placeholder: placeholder, focus: true }),
88
+ react_1.default.createElement(TextInput_1.TextInput, { value: text, onChange: (c) => setText(c), placeholder: placeholder, focus: true, onKeyPress: (e) => e.key === 'Enter' && ret(text) }),
89
89
  react_1.default.createElement(Bottom, { noGrow: true },
90
90
  react_1.default.createElement(Button_1.Button, { onClick: () => ret(text) }, okText),
91
91
  react_1.default.createElement(Button_1.Button, { invert: true, onClick: () => ret(undefined) }, cancelText))))));
@@ -0,0 +1,12 @@
1
+ export declare const Sidebar: ({ children, className, key, cookieDocument, }: {
2
+ children: any;
3
+ className?: string | undefined;
4
+ /**
5
+ * used for localstorage. default 'sidebar'
6
+ */
7
+ key?: string | undefined;
8
+ /**
9
+ * pass in SSR cookiedocument
10
+ */
11
+ cookieDocument?: string | undefined;
12
+ }) => JSX.Element;
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.Sidebar = void 0;
7
+ const react_1 = __importDefault(require("react"));
8
+ const styled_components_1 = __importDefault(require("styled-components"));
9
+ const cookie_1 = require("../../helpers/cookie");
10
+ const common_1 = require("../../styles/common");
11
+ const Chevron_1 = require("../Chevron");
12
+ const Base = styled_components_1.default.div `
13
+ position: relative;
14
+ transition: all 200ms;
15
+ width: 15rem;
16
+ border-right: solid 1px #ccc;
17
+ margin-right: 1rem;
18
+ padding-left: 0.5rem;
19
+
20
+ &[data-open='false'] {
21
+ width: 0.5rem;
22
+ background-color: rgba(0, 0, 0, 0.1);
23
+ cursor: pointer;
24
+ &:hover,
25
+ &:hover [data-hover='true'] {
26
+ background-color: #ccc;
27
+ }
28
+ &:hover {
29
+ border-right: solid 1px #999;
30
+ }
31
+ }
32
+ ${common_1.NoTextSelect};
33
+
34
+ &:hover {
35
+ [data-content] {
36
+ left: 1rem;
37
+ }
38
+ }
39
+ `;
40
+ const ContentBlock = styled_components_1.default.div `
41
+ left: -18rem;
42
+ transition left 200ms;
43
+ &[data-open='false'] {
44
+ position: absolute;
45
+ top: 0;
46
+ z-index: 1;
47
+ width: 15rem;
48
+ }
49
+ `;
50
+ const Content = styled_components_1.default.div `
51
+ display: flex;
52
+ flex-flow: column;
53
+ width: 100%;
54
+ height: 100%;
55
+ margin-top: 2rem;
56
+
57
+ &[data-open='false'] {
58
+ padding: 1rem;
59
+ background-color: white;
60
+ ${(0, common_1.Shadow)()};
61
+ border-radius: 1rem;
62
+ }
63
+ `;
64
+ const Hamburger = styled_components_1.default.div `
65
+ position: absolute;
66
+ transition: all 200ms;
67
+ &[data-open='false'] {
68
+ top: 0.5rem;
69
+ left: 0.25rem;
70
+ }
71
+ &[data-open='true'] {
72
+ top: 0.5rem;
73
+ right: -0.75rem;
74
+ }
75
+ display: flex;
76
+ justify-content: center;
77
+ align-items: center;
78
+ width: 1.5rem;
79
+ height: 1.5rem;
80
+ background-color: rgba(255, 255, 255, 0.9);
81
+ &:hover {
82
+ background-color: rgba(0, 0, 0, 0.1);
83
+ }
84
+ border-radius: 50%;
85
+ border: solid 1px rgba(0, 0, 0, 0.5);
86
+
87
+ cursor: pointer;
88
+ `;
89
+ const ChevronStyled = (0, styled_components_1.default)(Chevron_1.Chevron) `
90
+ svg {
91
+ fill: #555;
92
+ }
93
+ `;
94
+ const Sidebar = ({ children, className, key = 'sidebar', cookieDocument, }) => {
95
+ const [openRaw, setOpenRaw] = (0, cookie_1.useCookie)({
96
+ key,
97
+ defaultValue: 'false',
98
+ cookieDocument: cookieDocument,
99
+ });
100
+ const open = openRaw === 'true';
101
+ const setOpen = (o) => setOpenRaw(o.toString());
102
+ return (react_1.default.createElement(Base, { className: className, "data-open": open, onClick: () => !open && setOpen(true), "data-hover": true },
103
+ react_1.default.createElement(Hamburger, { "data-open": open, onClick: () => setOpen(!open), "data-hover": true },
104
+ react_1.default.createElement(ChevronStyled, { point: open ? 'right' : 'left', width: "100%" })),
105
+ react_1.default.createElement(ContentBlock, { "data-content": true, "data-open": open },
106
+ react_1.default.createElement(Content, { "data-open": open, onClick: (e) => {
107
+ e.stopPropagation();
108
+ } }, children))));
109
+ };
110
+ exports.Sidebar = Sidebar;
@@ -15,6 +15,7 @@ export * from './LogoutButton';
15
15
  export * from './Modal';
16
16
  export * from './Prompt';
17
17
  export * from './RowOrColumn';
18
+ export * from './Sidebar';
18
19
  export * from './Table';
19
20
  export * from './TextEdit';
20
21
  export * from './TextInput';
@@ -27,6 +27,7 @@ __exportStar(require("./LogoutButton"), exports);
27
27
  __exportStar(require("./Modal"), exports);
28
28
  __exportStar(require("./Prompt"), exports);
29
29
  __exportStar(require("./RowOrColumn"), exports);
30
+ __exportStar(require("./Sidebar"), exports);
30
31
  __exportStar(require("./Table"), exports);
31
32
  __exportStar(require("./TextEdit"), exports);
32
33
  __exportStar(require("./TextInput"), exports);
@@ -0,0 +1,28 @@
1
+ import { ICallOpenApi } from './types';
2
+ import { CacheItems } from '../routes';
3
+ import { AxiosWrapperLite } from '../jwt';
4
+ export declare type TCallOpenApiCached<T, TDefaultApi> = ICallOpenApi<T, TDefaultApi> & {
5
+ /**
6
+ * if falsey, will run callOpenApi directly
7
+ */
8
+ cacheKey: string;
9
+ /**
10
+ * will shortcut and return the appropriate axioswrapper data if cachekey is found
11
+ */
12
+ ssrCacheItems?: CacheItems;
13
+ /**
14
+ * default ttl in seconds for cache - default 120s
15
+ */
16
+ cacheTtl?: number;
17
+ /**
18
+ * (ssr) if true, wont run callopenapi if data is not cached
19
+ */
20
+ onlyCached?: boolean;
21
+ };
22
+ /**
23
+ * sync call to callOpenApiCache.
24
+ * @param p
25
+ * @returns undefined if no cache item
26
+ */
27
+ export declare const callOpenApiCachedRaw: <T, TDefaultApi>(p: TCallOpenApiCached<T, TDefaultApi>) => AxiosWrapperLite<T> | undefined;
28
+ export declare const callOpenApiCached: <T, TDefaultApi>(p: TCallOpenApiCached<T, TDefaultApi>) => Promise<AxiosWrapperLite<T>>;
@@ -0,0 +1,74 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.callOpenApiCached = exports.callOpenApiCachedRaw = void 0;
16
+ const cookie_1 = require("../cookie");
17
+ const node_cache_1 = __importDefault(require("node-cache"));
18
+ const direct_1 = require("./direct");
19
+ const string_1 = require("../../../common/helpers/string");
20
+ let callOpenApiCache;
21
+ function getCacheKey({ cacheKey, overrideAuth, }) {
22
+ const authkeyPrefix = (overrideAuth === null || overrideAuth === void 0 ? void 0 : overrideAuth.id_token) || (0, cookie_1.getCookieWrapper)({ cname: 'id_token' });
23
+ let cacheKeyRet;
24
+ if (cacheKey) {
25
+ const pref = !authkeyPrefix ? '' : (0, string_1.toBase64)(authkeyPrefix);
26
+ cacheKeyRet = cacheKey + '||' + pref;
27
+ }
28
+ return cacheKeyRet;
29
+ }
30
+ /**
31
+ * sync call to callOpenApiCache.
32
+ * @param p
33
+ * @returns undefined if no cache item
34
+ */
35
+ const callOpenApiCachedRaw = (p) => {
36
+ var _a, _b, _c;
37
+ const userPrefixedCacheKey = getCacheKey(p);
38
+ if (!userPrefixedCacheKey) {
39
+ return undefined;
40
+ }
41
+ if (!callOpenApiCache) {
42
+ callOpenApiCache = new node_cache_1.default({ stdTTL: p.cacheTtl || 120 });
43
+ }
44
+ //get ssr cache value
45
+ const ssrCached = (_c = (_b = (_a = p.ssrCacheItems) === null || _a === void 0 ? void 0 : _a.find((s) => s.cacheKey === p.cacheKey)) === null || _b === void 0 ? void 0 : _b.prefillData) === null || _c === void 0 ? void 0 : _c.data;
46
+ //if we have ssr cache and there is no existing cache then set
47
+ if (!callOpenApiCache.get(userPrefixedCacheKey) && ssrCached) {
48
+ callOpenApiCache.set(userPrefixedCacheKey, ssrCached);
49
+ }
50
+ //return cached data, or ssr data if that has already expired (ttl <=0)
51
+ const data = callOpenApiCache.get(userPrefixedCacheKey) || ssrCached;
52
+ if (!data) {
53
+ return undefined;
54
+ }
55
+ return { data };
56
+ };
57
+ exports.callOpenApiCachedRaw = callOpenApiCachedRaw;
58
+ const callOpenApiCached = (p) => __awaiter(void 0, void 0, void 0, function* () {
59
+ const raw = (0, exports.callOpenApiCachedRaw)(p);
60
+ if (raw) {
61
+ return raw;
62
+ }
63
+ const resp = yield (0, direct_1.callOpenApi)(p);
64
+ if (resp.error) {
65
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
66
+ return { error: resp.error, data: undefined };
67
+ }
68
+ const userPrefixedCacheKey = getCacheKey(p);
69
+ if (callOpenApiCache && userPrefixedCacheKey) {
70
+ callOpenApiCache.set(userPrefixedCacheKey, resp.data);
71
+ }
72
+ return resp;
73
+ });
74
+ exports.callOpenApiCached = callOpenApiCached;
@@ -1,3 +1,3 @@
1
- import { AxiosWrapper } from './jwt';
2
1
  import { ICallOpenApi } from './types';
3
- export declare const callOpenApi: <T, TDefaultApi>({ func, apiUrl, overrideAuth, refreshToken, logout, newDefaultApi, headers, }: ICallOpenApi<T, TDefaultApi>) => Promise<AxiosWrapper<T>>;
2
+ import { AxiosWrapperLite } from '../jwt';
3
+ export declare const callOpenApi: <T, TDefaultApi>({ func, apiUrl, overrideAuth, refreshToken, logout, newDefaultApi, headers, }: ICallOpenApi<T, TDefaultApi>) => Promise<AxiosWrapperLite<T>>;
@@ -10,9 +10,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
10
10
  };
11
11
  Object.defineProperty(exports, "__esModule", { value: true });
12
12
  exports.callOpenApi = void 0;
13
- const cookie_1 = require("./cookie");
14
- const sleep_1 = require("../../common/helpers/sleep");
15
- const array_1 = require("../../common/helpers/array");
13
+ const cookie_1 = require("../cookie");
14
+ const sleep_1 = require("../../../common/helpers/sleep");
15
+ const array_1 = require("../../../common/helpers/array");
16
16
  const callOpenApi = ({ func, apiUrl, overrideAuth, refreshToken, logout, newDefaultApi, headers, }) => __awaiter(void 0, void 0, void 0, function* () {
17
17
  var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
18
18
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
@@ -22,14 +22,16 @@ const callOpenApi = ({ func, apiUrl, overrideAuth, refreshToken, logout, newDefa
22
22
  basePath: apiUrl,
23
23
  baseOptions: { headers: Object.assign({ authorization: '' }, (headers || {})) },
24
24
  };
25
- const isAuthed = !!(0, cookie_1.getCookieWrapper)({ cname: 'id_token' });
26
25
  if (overrideAuth === null || overrideAuth === void 0 ? void 0 : overrideAuth.id_token) {
27
26
  config.baseOptions.headers.authorization = `Bearer ${overrideAuth === null || overrideAuth === void 0 ? void 0 : overrideAuth.id_token}`;
28
27
  }
29
- else if (isAuthed) {
30
- const updated = yield refreshToken();
31
- if ((_a = updated === null || updated === void 0 ? void 0 : updated.jwt) === null || _a === void 0 ? void 0 : _a.id_token) {
32
- config.baseOptions.headers.authorization = `Bearer ${(_b = updated === null || updated === void 0 ? void 0 : updated.jwt) === null || _b === void 0 ? void 0 : _b.id_token}`;
28
+ else {
29
+ const isAuthed = !!(0, cookie_1.getCookieWrapper)({ cname: 'id_token' });
30
+ if (isAuthed) {
31
+ const updated = yield refreshToken();
32
+ if ((_a = updated === null || updated === void 0 ? void 0 : updated.jwt) === null || _a === void 0 ? void 0 : _a.id_token) {
33
+ config.baseOptions.headers.authorization = `Bearer ${(_b = updated === null || updated === void 0 ? void 0 : updated.jwt) === null || _b === void 0 ? void 0 : _b.id_token}`;
34
+ }
33
35
  }
34
36
  }
35
37
  const cl = newDefaultApi(config);
@@ -65,10 +67,6 @@ const callOpenApi = ({ func, apiUrl, overrideAuth, refreshToken, logout, newDefa
65
67
  return {
66
68
  error: ae,
67
69
  data: undefined,
68
- datetime: new Date().getTime(),
69
- loading: false,
70
- reFetch: () => __awaiter(void 0, void 0, void 0, function* () { }),
71
- url: func.toString(),
72
70
  };
73
71
  }
74
72
  if (status !== 500 || errorCount === errorMax) {
@@ -79,6 +77,6 @@ const callOpenApi = ({ func, apiUrl, overrideAuth, refreshToken, logout, newDefa
79
77
  // eslint-disable-next-line no-await-in-loop
80
78
  yield (0, sleep_1.sleep)(2000);
81
79
  }
82
- return Object.assign(Object.assign({ data }, (error && { error })), { loading: false, reFetch: () => __awaiter(void 0, void 0, void 0, function* () { return func(cl); }), url: func.toString(), datetime: new Date().getTime() });
80
+ return Object.assign({ data }, (error && { error }));
83
81
  });
84
82
  exports.callOpenApi = callOpenApi;
@@ -1,10 +1,15 @@
1
- import { AxiosWrapper } from './jwt';
1
+ import { AxiosWrapper } from '../jwt';
2
2
  import { ICallOpenApi } from './types';
3
- import { CacheItems } from './routes';
3
+ import { CacheItems } from '../routes';
4
4
  declare type AxiosWrapperWrap<T> = AxiosWrapper<T | undefined> & {
5
5
  loaded: boolean;
6
6
  loadcount: number;
7
7
  };
8
+ /**
9
+ * hooks+cached call to callOpenApi
10
+ * @param p
11
+ * @returns
12
+ */
8
13
  export declare const useCallOpenApi: <T, TDefaultApi>(p: ICallOpenApi<T, TDefaultApi> & {
9
14
  cacheKey: string;
10
15
  /**
@@ -8,24 +8,18 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
8
8
  step((generator = generator.apply(thisArg, _arguments || [])).next());
9
9
  });
10
10
  };
11
- var __importDefault = (this && this.__importDefault) || function (mod) {
12
- return (mod && mod.__esModule) ? mod : { "default": mod };
13
- };
14
11
  Object.defineProperty(exports, "__esModule", { value: true });
15
12
  exports.useCallOpenApi = void 0;
16
13
  const react_1 = require("react");
17
- const callOpenApi_1 = require("./callOpenApi");
18
- const node_cache_1 = __importDefault(require("node-cache"));
19
- let useCallOpenApiCache;
14
+ const cached_1 = require("./cached");
15
+ const direct_1 = require("./direct");
16
+ /**
17
+ * hooks+cached call to callOpenApi
18
+ * @param p
19
+ * @returns
20
+ */
20
21
  const useCallOpenApi = (p) => {
21
22
  var _a;
22
- if (!useCallOpenApiCache) {
23
- useCallOpenApiCache = new node_cache_1.default({ stdTTL: p.cacheTtl || 120 });
24
- }
25
- const ssrCached = (_a = p.ssrCacheItems) === null || _a === void 0 ? void 0 : _a.find((s) => s.cacheKey === p.cacheKey);
26
- if (!useCallOpenApiCache.get(p.cacheKey) && ssrCached) {
27
- useCallOpenApiCache.set(p.cacheKey, ssrCached);
28
- }
29
23
  const defv = {
30
24
  data: undefined,
31
25
  url: '',
@@ -35,16 +29,13 @@ const useCallOpenApi = (p) => {
35
29
  loaded: false,
36
30
  reFetch: () => __awaiter(void 0, void 0, void 0, function* () { }),
37
31
  };
38
- const cached = useCallOpenApiCache.get(p.cacheKey);
39
- const [data, setData] = (0, react_1.useState)(Object.assign(Object.assign({}, defv), { data: cached, loaded: !!cached }));
32
+ const cachedData = (_a = (0, cached_1.callOpenApiCachedRaw)(Object.assign(Object.assign({}, p), { onlyCached: true }))) === null || _a === void 0 ? void 0 : _a.data;
33
+ const [data, setData] = (0, react_1.useState)(Object.assign(Object.assign(Object.assign({}, defv), (cachedData && { data: cachedData })), { loaded: !!cachedData }));
40
34
  (0, react_1.useEffect)(() => {
41
35
  function run() {
42
36
  return __awaiter(this, void 0, void 0, function* () {
43
- const resp = yield (0, callOpenApi_1.callOpenApi)(p);
44
- if (useCallOpenApiCache) {
45
- useCallOpenApiCache.set(p.cacheKey, resp.data);
46
- }
47
- setData((d) => (Object.assign(Object.assign({}, resp), { loaded: true, loading: false, loadcount: d.loadcount + 1 })));
37
+ const resp = yield (0, direct_1.callOpenApi)(p);
38
+ setData((d) => (Object.assign(Object.assign({}, resp), { loaded: true, loading: false, loadcount: d.loadcount + 1, reFetch: () => __awaiter(this, void 0, void 0, function* () { }), url: '', datetime: new Date().getTime() })));
48
39
  });
49
40
  }
50
41
  const { error, loaded, loading, loadcount } = data;
@@ -54,7 +45,7 @@ const useCallOpenApi = (p) => {
54
45
  }
55
46
  setData((d) => (Object.assign(Object.assign({}, d), { loading: true })));
56
47
  void run();
57
- }, [cached, data, p, setData]);
48
+ }, [data, p, setData]);
58
49
  return Object.assign(Object.assign({}, data), { reFetch: () => __awaiter(void 0, void 0, void 0, function* () {
59
50
  setData(defv);
60
51
  }) });
@@ -0,0 +1,4 @@
1
+ export * from './direct';
2
+ export * from './cached';
3
+ export * from './hook';
4
+ export * from './types';
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
+ }) : (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ o[k2] = m[k];
8
+ }));
9
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
+ };
12
+ Object.defineProperty(exports, "__esModule", { value: true });
13
+ __exportStar(require("./direct"), exports);
14
+ __exportStar(require("./cached"), exports);
15
+ __exportStar(require("./hook"), exports);
16
+ __exportStar(require("./types"), exports);
@@ -1,5 +1,5 @@
1
1
  import { AxiosResponse } from 'axios';
2
- import { User } from './jwt';
2
+ import { User } from '../jwt';
3
3
  export interface OverrideAuth {
4
4
  id_token?: string;
5
5
  }
@@ -9,17 +9,12 @@ export * from './dom';
9
9
  export * from './extractAttributes';
10
10
  export * from './jwt';
11
11
  export * from './lang';
12
- export * from './mutex';
13
- export * from './mutexData';
14
12
  export * from './plural';
15
13
  export * from './routes';
16
- export * from './types';
17
- export * from './useCallOpenApi';
18
14
  export * from './useContextMenu';
19
15
  export * from './useLocalStorage';
20
16
  export * from './useLockBodyScroll';
21
17
  export * from './useOnClickOutside';
22
18
  export * from './useOnScroll';
23
- export * from './useOpenApiStore';
24
19
  export * from './useQueryString';
25
20
  export * from './useResize';
@@ -21,17 +21,12 @@ __exportStar(require("./dom"), exports);
21
21
  __exportStar(require("./extractAttributes"), exports);
22
22
  __exportStar(require("./jwt"), exports);
23
23
  __exportStar(require("./lang"), exports);
24
- __exportStar(require("./mutex"), exports);
25
- __exportStar(require("./mutexData"), exports);
26
24
  __exportStar(require("./plural"), exports);
27
25
  __exportStar(require("./routes"), exports);
28
- __exportStar(require("./types"), exports);
29
- __exportStar(require("./useCallOpenApi"), exports);
30
26
  __exportStar(require("./useContextMenu"), exports);
31
27
  __exportStar(require("./useLocalStorage"), exports);
32
28
  __exportStar(require("./useLockBodyScroll"), exports);
33
29
  __exportStar(require("./useOnClickOutside"), exports);
34
30
  __exportStar(require("./useOnScroll"), exports);
35
- __exportStar(require("./useOpenApiStore"), exports);
36
31
  __exportStar(require("./useQueryString"), exports);
37
32
  __exportStar(require("./useResize"), exports);
@@ -57,6 +57,10 @@ export interface AxiosWrapper<T> {
57
57
  url: string;
58
58
  datetime: number;
59
59
  }
60
+ export interface AxiosWrapperLite<T> {
61
+ data: T;
62
+ error?: AxiosError;
63
+ }
60
64
  export interface AuthedUserContext {
61
65
  loading: boolean;
62
66
  isAuthenticated: boolean;
@@ -1,6 +1,6 @@
1
1
  import { TLang } from '../../common/helpers/i18n';
2
2
  import { ICognitoAuth } from './cognito';
3
- import { AxiosWrapper } from './jwt';
3
+ import { AxiosWrapperLite } from './jwt';
4
4
  export interface LocationSubset {
5
5
  pathname: string;
6
6
  hash: string;
@@ -11,7 +11,7 @@ export interface LocationSubset {
11
11
  export declare type CacheItems = CacheItem<any>[];
12
12
  export interface CacheItem<T> {
13
13
  cacheKey: string;
14
- prefillData: AxiosWrapper<T>;
14
+ prefillData: AxiosWrapperLite<T>;
15
15
  ttlSeconds: number;
16
16
  }
17
17
  export interface IInitialStateCommon {
@@ -1,18 +1,33 @@
1
1
  export declare const isServer: boolean;
2
- export declare const useQueryStringRaw: <T>({ name, searchOverride, defaultValue, stringify, parse, }: {
2
+ /**
3
+ * hook for query string value
4
+ * @param param0 can provide for SSR - queryValues will default to window if available
5
+ * @returns
6
+ */
7
+ export declare const useQueryStringRaw: <T>({ name, queryValues, defaultValue, stringify, parse, }: {
3
8
  name: string;
4
- searchOverride?: string | undefined;
9
+ queryValues?: Record<string, string> | undefined;
5
10
  defaultValue: T;
6
11
  stringify: (v: T) => string | undefined;
7
12
  parse: (v: string | undefined) => T;
8
13
  }) => [T, (v: T) => void];
9
- export declare const useQueryStringArray: ({ name, searchOverride, defaultValue, }: {
14
+ /**
15
+ * hook for query string value - string array type
16
+ * @param param0 can provide for SSR - queryValues will default to window if available
17
+ * @returns
18
+ */
19
+ export declare const useQueryStringArray: ({ name, queryValues, defaultValue, }: {
10
20
  name: string;
11
- searchOverride?: string | undefined;
21
+ queryValues?: Record<string, string> | undefined;
12
22
  defaultValue: string[];
13
23
  }) => [string[], (v: string[]) => void];
14
- export declare const useQueryStringSingle: ({ name, searchOverride, defaultValue, }: {
24
+ /**
25
+ * hook for query string value - single value
26
+ * @param param0 can provide for SSR - queryValues will default to window if available
27
+ * @returns
28
+ */
29
+ export declare const useQueryStringSingle: ({ name, queryValues, defaultValue, }: {
15
30
  name: string;
16
- searchOverride?: string | undefined;
31
+ queryValues?: Record<string, string> | undefined;
17
32
  defaultValue: string | undefined;
18
33
  }) => [string | undefined, (v: string | undefined) => void];
@@ -2,60 +2,66 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.useQueryStringSingle = exports.useQueryStringArray = exports.useQueryStringRaw = exports.isServer = void 0;
4
4
  const react_1 = require("react");
5
+ const object_1 = require("../../common/helpers/object");
5
6
  exports.isServer = typeof window === 'undefined';
6
- const useQueryStringRaw = ({ name, searchOverride, defaultValue, stringify, parse, }) => {
7
- const raw = exports.isServer ? searchOverride : window.location.search;
8
- const [state, setStateRaw] = (0, react_1.useState)(() => {
9
- if (!raw) {
10
- return defaultValue;
11
- }
12
- const parsed = new URLSearchParams(raw);
13
- const g = parsed.get(name);
14
- if (!g) {
15
- return defaultValue;
16
- }
17
- return parse(g) || defaultValue;
18
- });
7
+ /**
8
+ * hook for query string value
9
+ * @param param0 can provide for SSR - queryValues will default to window if available
10
+ * @returns
11
+ */
12
+ const useQueryStringRaw = ({ name, queryValues, defaultValue, stringify, parse, }) => {
13
+ // eslint-disable-next-line react-hooks/exhaustive-deps
14
+ const qv = exports.isServer
15
+ ? queryValues || {}
16
+ : // eslint-disable-next-line @typescript-eslint/no-explicit-any
17
+ (0, object_1.paramsToObject)(new URLSearchParams(window.location.search));
18
+ const qsv = parse(qv[name]) || defaultValue;
19
+ const [state, setStateRaw] = (0, react_1.useState)(qsv);
20
+ //
19
21
  const setState = (v) => {
20
- const searchParams = new URLSearchParams(window.location.search);
21
22
  const sv = !v ? undefined : stringify(v);
22
23
  if (sv) {
23
- searchParams.set(name, sv);
24
+ qv[name] = sv;
24
25
  }
25
26
  else {
26
- searchParams.delete(name);
27
- }
28
- let qs = '';
29
- if (Array.from(searchParams).length !== 0) {
30
- qs = '?' + searchParams.toString();
27
+ delete qv[name];
31
28
  }
32
- const loc = `${location.pathname}${qs}${window.location.hash}`;
29
+ const qs = '?' + (0, object_1.objectToString)(qv, '=', '&');
30
+ const loc = location.pathname + qs + window.location.hash;
33
31
  window.history.replaceState({}, '', loc);
34
32
  setStateRaw(v);
35
33
  };
34
+ //
36
35
  (0, react_1.useEffect)(() => {
37
- const parsed = new URLSearchParams(raw);
38
- const g = parsed.get(name);
39
- const newv = g ? parse(g) : defaultValue;
40
- if (JSON.stringify(state) !== JSON.stringify(newv)) {
41
- setStateRaw(newv);
36
+ if (JSON.stringify(state) !== JSON.stringify(qsv)) {
37
+ setStateRaw(qsv);
42
38
  }
43
- }, [defaultValue, name, parse, raw, state]);
39
+ }, [name, parse, qsv, state]);
44
40
  return [state, setState];
45
41
  };
46
42
  exports.useQueryStringRaw = useQueryStringRaw;
47
- const useQueryStringArray = ({ name, searchOverride, defaultValue, }) => (0, exports.useQueryStringRaw)({
43
+ /**
44
+ * hook for query string value - string array type
45
+ * @param param0 can provide for SSR - queryValues will default to window if available
46
+ * @returns
47
+ */
48
+ const useQueryStringArray = ({ name, queryValues, defaultValue, }) => (0, exports.useQueryStringRaw)({
48
49
  name,
49
50
  defaultValue,
50
- searchOverride,
51
+ queryValues,
51
52
  stringify: (v) => (v.length === 0 ? undefined : v.join(',')),
52
53
  parse: (v) => (!v ? defaultValue : v.split(',')),
53
54
  });
54
55
  exports.useQueryStringArray = useQueryStringArray;
55
- const useQueryStringSingle = ({ name, searchOverride, defaultValue, }) => (0, exports.useQueryStringRaw)({
56
+ /**
57
+ * hook for query string value - single value
58
+ * @param param0 can provide for SSR - queryValues will default to window if available
59
+ * @returns
60
+ */
61
+ const useQueryStringSingle = ({ name, queryValues, defaultValue, }) => (0, exports.useQueryStringRaw)({
56
62
  name,
57
63
  defaultValue,
58
- searchOverride,
64
+ queryValues,
59
65
  stringify: (v) => v,
60
66
  parse: (v) => (!v ? defaultValue : v),
61
67
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ag-common",
3
- "version": "0.0.124",
3
+ "version": "0.0.128",
4
4
  "main": "./dist/index.js",
5
5
  "types": "./dist/index.d.ts",
6
6
  "author": "Andrei Gec <@andreigec> (https://gec.dev/)",
@@ -1,22 +0,0 @@
1
- export interface IMutex {
2
- capture(key: string): Promise<() => void>;
3
- isLocked: (key: string) => boolean;
4
- }
5
- export interface IMutexOptions {
6
- intervalMs?: number;
7
- autoUnlockTimeoutMs?: number;
8
- Promise?: PromiseConstructor;
9
- }
10
- declare type TResolve = (value: (() => void) | PromiseLike<() => void>) => void;
11
- declare type TReject = (reason?: string) => void;
12
- export declare class Mutex implements IMutex {
13
- static defaultIntervalMs: number;
14
- static defaultAutoUnlockTimeoutMs: number;
15
- protected storage: Record<string, number>;
16
- protected options: IMutexOptions;
17
- constructor(options?: IMutexOptions);
18
- capture(key: string): Promise<() => void>;
19
- isLocked: (key: string) => boolean;
20
- protected checkMutexAndLock(key: string, resolve: TResolve, reject: TReject): void;
21
- }
22
- export {};
@@ -1,53 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Mutex = void 0;
4
- let setTimeout;
5
- let clearTimeout;
6
- if (typeof global !== 'undefined') {
7
- setTimeout = global.setTimeout;
8
- clearTimeout = global.clearTimeout;
9
- }
10
- else {
11
- setTimeout = window.setTimeout;
12
- clearTimeout = window.clearTimeout;
13
- }
14
- class Mutex {
15
- constructor(options = {}) {
16
- this.storage = {};
17
- this.options = {};
18
- this.isLocked = (key) => !!this.storage[key];
19
- this.options = {
20
- Promise: options.Promise || Promise,
21
- intervalMs: (options && options.intervalMs) || Mutex.defaultIntervalMs,
22
- autoUnlockTimeoutMs: (options && options.autoUnlockTimeoutMs) ||
23
- Mutex.defaultAutoUnlockTimeoutMs,
24
- };
25
- }
26
- capture(key) {
27
- const P = this.options.Promise || Promise;
28
- return new P((resolve, reject) => {
29
- this.checkMutexAndLock(key, resolve, reject);
30
- });
31
- }
32
- checkMutexAndLock(key, resolve, reject) {
33
- if (!this.storage[key]) {
34
- const value = Date.now();
35
- this.storage[key] = value;
36
- const timeout = setTimeout(() => {
37
- delete this.storage[key];
38
- }, this.options.autoUnlockTimeoutMs);
39
- resolve(() => {
40
- clearTimeout(timeout);
41
- if (this.storage[key] === value) {
42
- delete this.storage[key];
43
- }
44
- });
45
- }
46
- else {
47
- setTimeout(this.checkMutexAndLock.bind(this, key, resolve, reject), this.options.intervalMs);
48
- }
49
- }
50
- }
51
- exports.Mutex = Mutex;
52
- Mutex.defaultIntervalMs = 50;
53
- Mutex.defaultAutoUnlockTimeoutMs = 3000;
@@ -1,17 +0,0 @@
1
- export declare class MutexData<T> {
2
- subscriptions: {
3
- [a: string]: {
4
- [subId: string]: (ts: number) => void;
5
- };
6
- };
7
- subscribe(key: string, subId: string, func: (ts: number) => void): void;
8
- unsubscribe(key: string, subId: string): void;
9
- getData(key: string): T;
10
- pingSubscribers(key: string): void;
11
- setData({ ttlSeconds, key, data, }: {
12
- key: string;
13
- data: T;
14
- ttlSeconds?: number;
15
- }): void;
16
- delete(key: string, updateSubscribers?: boolean): void;
17
- }
@@ -1,55 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MutexData = void 0;
4
- /* eslint-disable class-methods-use-this */
5
- const _1 = require(".");
6
- const log_1 = require("../../common/helpers/log");
7
- const useLocalStorage_1 = require("./useLocalStorage");
8
- class MutexData {
9
- constructor() {
10
- this.subscriptions = {};
11
- }
12
- subscribe(key, subId, func) {
13
- if (!this.subscriptions[key]) {
14
- this.subscriptions[key] = { [subId]: func };
15
- }
16
- this.subscriptions[key][subId] = func;
17
- }
18
- unsubscribe(key, subId) {
19
- delete this.subscriptions[key][subId];
20
- }
21
- getData(key) {
22
- return (0, useLocalStorage_1.getLocalStorageItem)(`mutex-${key}`, undefined, 3600);
23
- }
24
- pingSubscribers(key) {
25
- if (!this.subscriptions[key]) {
26
- (0, log_1.debug)('no subscribers');
27
- return;
28
- }
29
- Object.keys(this.subscriptions[key]).forEach((subKey) => {
30
- const ts = new Date().getTime();
31
- if (!this.subscriptions[key][subKey] ||
32
- typeof this.subscriptions[key][subKey] !== 'function') {
33
- this.unsubscribe(key, subKey);
34
- }
35
- else {
36
- this.subscriptions[key][subKey](ts);
37
- }
38
- });
39
- }
40
- setData({ ttlSeconds = 3600, key, data, }) {
41
- (0, useLocalStorage_1.setLocalStorageItem)(`mutex-${key}`, data, ttlSeconds);
42
- if (Object.keys(this.subscriptions).length > 0) {
43
- this.pingSubscribers(key);
44
- }
45
- }
46
- delete(key, updateSubscribers = false) {
47
- (0, _1.clearLocalStorageItem)(`mutex-${key}`);
48
- if (updateSubscribers) {
49
- if (Object.keys(this.subscriptions).length > 0) {
50
- this.pingSubscribers(key);
51
- }
52
- }
53
- }
54
- }
55
- exports.MutexData = MutexData;
@@ -1,24 +0,0 @@
1
- import { CacheItems } from './routes';
2
- import { AxiosWrapper } from './jwt';
3
- import { ICallOpenApi } from './types';
4
- export declare const deleteMutexData: (key: string) => void;
5
- export declare const setMutexData: ({ key, data, ttlSeconds, }: {
6
- key: string;
7
- data: any;
8
- ttlSeconds: number;
9
- }) => void;
10
- export declare const getMutexData: <T>(key: string) => AxiosWrapper<T>;
11
- /**
12
- *
13
- * @param overrideAuth - auth automatically picked up from id_token cookie, can override value here, but not required
14
- * @returns
15
- */
16
- export declare const useOpenApiStore: <T, TDefaultApi>(p: ICallOpenApi<T, TDefaultApi> & {
17
- ttlSeconds?: number | undefined;
18
- cacheKey: string;
19
- /**
20
- * will shortcut and return the appropriate axioswrapper data if cachekey is found
21
- */
22
- ssrCacheItems?: CacheItems | undefined;
23
- }) => AxiosWrapper<T>;
24
- export declare const setOpenApiCache: (items: CacheItems) => void;
@@ -1,147 +0,0 @@
1
- "use strict";
2
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
- return new (P || (P = Promise))(function (resolve, reject) {
5
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
- step((generator = generator.apply(thisArg, _arguments || [])).next());
9
- });
10
- };
11
- Object.defineProperty(exports, "__esModule", { value: true });
12
- exports.setOpenApiCache = exports.useOpenApiStore = exports.getMutexData = exports.setMutexData = exports.deleteMutexData = void 0;
13
- const react_1 = require("react");
14
- const mutex_1 = require("./mutex");
15
- const mutexData_1 = require("./mutexData");
16
- const callOpenApi_1 = require("./callOpenApi");
17
- const log_1 = require("../../common/helpers/log");
18
- const mutex = new mutex_1.Mutex({
19
- autoUnlockTimeoutMs: 10000,
20
- intervalMs: 100,
21
- Promise: Promise,
22
- });
23
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
24
- const mutexData = new mutexData_1.MutexData();
25
- const deleteMutexData = (key) => mutexData.delete(key);
26
- exports.deleteMutexData = deleteMutexData;
27
- const setMutexData = ({ key, data, ttlSeconds = 3600, }) => {
28
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
29
- const wrap = {
30
- data,
31
- loading: false,
32
- reFetch: () => __awaiter(void 0, void 0, void 0, function* () {
33
- (0, log_1.info)('mocked');
34
- }),
35
- datetime: new Date().getTime(),
36
- error: undefined,
37
- url: '',
38
- };
39
- mutexData.setData({ key, data: wrap, ttlSeconds });
40
- };
41
- exports.setMutexData = setMutexData;
42
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
43
- const getMutexData = (key) => mutexData.getData(key);
44
- exports.getMutexData = getMutexData;
45
- function mLock(p) {
46
- return __awaiter(this, void 0, void 0, function* () {
47
- let unlock;
48
- try {
49
- unlock = yield mutex.capture(p.key);
50
- if (mutexData.getData(p.key)) {
51
- return;
52
- }
53
- const newData = yield (0, callOpenApi_1.callOpenApi)(p);
54
- if (!newData) {
55
- return;
56
- }
57
- if (newData.error) {
58
- (0, log_1.error)('api error:', newData.error);
59
- }
60
- else {
61
- mutexData.setData({
62
- key: p.key,
63
- data: newData,
64
- ttlSeconds: p.ttlSeconds,
65
- });
66
- }
67
- mutexData.pingSubscribers(p.key);
68
- }
69
- catch (e) {
70
- (0, log_1.error)('mutex error:', e);
71
- }
72
- finally {
73
- // eslint-disable-next-line @typescript-eslint/ban-ts-comment
74
- // @ts-ignore
75
- if (unlock) {
76
- unlock();
77
- }
78
- }
79
- });
80
- }
81
- const getTs = () => new Date().getTime();
82
- /**
83
- *
84
- * @param overrideAuth - auth automatically picked up from id_token cookie, can override value here, but not required
85
- * @returns
86
- */
87
- const useOpenApiStore = (p) => {
88
- var _a;
89
- const { cacheKey, disabled } = p;
90
- if (!cacheKey) {
91
- throw new Error('no cache key');
92
- }
93
- const [key, setKey] = (0, react_1.useState)(cacheKey);
94
- (0, react_1.useEffect)(() => {
95
- setKey(cacheKey);
96
- }, [cacheKey]);
97
- const [, setTs] = (0, react_1.useState)(0);
98
- (0, react_1.useEffect)(() => {
99
- const myHash = getTs().toString();
100
- mutexData.subscribe(key, myHash, setTs);
101
- return () => mutexData.unsubscribe(key, myHash);
102
- }, [key]);
103
- (0, react_1.useEffect)(() => {
104
- if (!disabled && !mutexData.getData(key)) {
105
- // eslint-disable-next-line @typescript-eslint/no-floating-promises
106
- mLock(Object.assign({ key }, p));
107
- }
108
- }, [disabled, key, p]);
109
- if (disabled) {
110
- return {
111
- loading: false,
112
- error: undefined,
113
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
114
- data: undefined,
115
- datetime: new Date().getTime(),
116
- reFetch: () => __awaiter(void 0, void 0, void 0, function* () { }),
117
- url: '',
118
- };
119
- }
120
- const ssrCached = (_a = p.ssrCacheItems) === null || _a === void 0 ? void 0 : _a.find((s) => s.cacheKey === cacheKey);
121
- if (typeof window === 'undefined' && ssrCached) {
122
- return ssrCached.prefillData;
123
- }
124
- const current = mutexData.getData(key);
125
- if (!current) {
126
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
127
- return { loading: true };
128
- }
129
- return Object.assign(Object.assign({}, current), { reFetch: () => __awaiter(void 0, void 0, void 0, function* () {
130
- mutexData.setData({
131
- key,
132
- data: Object.assign(Object.assign({}, current), { loading: true }),
133
- ttlSeconds: p.ttlSeconds,
134
- });
135
- mutexData.pingSubscribers(key);
136
- const newData = yield (0, callOpenApi_1.callOpenApi)(p);
137
- mutexData.setData({ key, data: newData, ttlSeconds: p.ttlSeconds });
138
- mutexData.pingSubscribers(key);
139
- }) });
140
- };
141
- exports.useOpenApiStore = useOpenApiStore;
142
- const setOpenApiCache = (items) => {
143
- items.forEach(({ cacheKey, prefillData, ttlSeconds }) => {
144
- mutexData.setData({ key: cacheKey, data: prefillData, ttlSeconds });
145
- });
146
- };
147
- exports.setOpenApiCache = setOpenApiCache;