@betterinternship/components 1.5.9 → 1.5.11
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.
|
@@ -1,15 +1,27 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { UseQueryResult } from '@tanstack/react-query';
|
|
2
|
+
interface ClientProcess<T> {
|
|
3
|
+
id: string;
|
|
4
|
+
name: string;
|
|
5
|
+
result?: T;
|
|
6
|
+
metadata?: ClientProcessMetadata;
|
|
7
|
+
success?: boolean;
|
|
8
|
+
pending?: boolean;
|
|
9
|
+
error?: string;
|
|
10
|
+
}
|
|
2
11
|
export interface ProcessCallbackDto {
|
|
3
12
|
processId: string;
|
|
4
13
|
processName: string;
|
|
5
14
|
processCallbackUrl: string;
|
|
6
15
|
}
|
|
7
16
|
export interface ClientProcessOptions {
|
|
8
|
-
filter?: string;
|
|
9
17
|
onLoading?: (processId: string, processName: string) => void;
|
|
10
18
|
onSuccess?: <R>(processId: string, processName: string, result: R) => void;
|
|
11
19
|
onFailure?: (processId: string, processName: string, error?: string) => void;
|
|
12
20
|
}
|
|
21
|
+
export interface ClientProcessMetadata {
|
|
22
|
+
filterKey: string;
|
|
23
|
+
metadata?: Record<string, string>;
|
|
24
|
+
}
|
|
13
25
|
export interface ProcessResponse {
|
|
14
26
|
processId: string;
|
|
15
27
|
processName: string;
|
|
@@ -22,7 +34,7 @@ export interface ProcessResponse {
|
|
|
22
34
|
*
|
|
23
35
|
* @context
|
|
24
36
|
*/
|
|
25
|
-
export declare const ClientProcessesProvider: ({ children
|
|
37
|
+
export declare const ClientProcessesProvider: ({ children }: {
|
|
26
38
|
children: React.ReactNode;
|
|
27
39
|
}) => import("react/jsx-runtime").JSX.Element;
|
|
28
40
|
/**
|
|
@@ -38,22 +50,13 @@ export declare function useClientProcess<T>({ caller, filterKey, onLoading, onSu
|
|
|
38
50
|
onSuccess?: <R>(processId: string, processName: string, result: R) => void;
|
|
39
51
|
onFailure?: (processId: string, processName: string, error?: string) => void;
|
|
40
52
|
}): {
|
|
41
|
-
run: (inputs: T) => Promise<{
|
|
53
|
+
run: (inputs: T, metadata?: Record<string, string>) => Promise<{
|
|
42
54
|
id: string;
|
|
43
55
|
success: boolean;
|
|
44
56
|
message: string | undefined;
|
|
45
57
|
}>;
|
|
46
|
-
get: (id: string) =>
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
result?: unknown;
|
|
50
|
-
success: boolean;
|
|
51
|
-
} | null;
|
|
52
|
-
getAll: () => {
|
|
53
|
-
id: string;
|
|
54
|
-
name: string;
|
|
55
|
-
result?: unknown;
|
|
56
|
-
success: boolean;
|
|
57
|
-
}[];
|
|
58
|
-
cp: Query<unknown, Error, unknown, readonly unknown[]>[];
|
|
58
|
+
get: (id: string) => ClientProcess<unknown> | null;
|
|
59
|
+
getAll: () => ClientProcess<unknown>[];
|
|
60
|
+
cp: UseQueryResult[];
|
|
59
61
|
};
|
|
62
|
+
export {};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { j as jsxRuntimeExports } from '../_virtual/jsx-runtime.js';
|
|
3
|
-
import { createContext,
|
|
3
|
+
import { createContext, useRef, useState, useContext } from 'react';
|
|
4
4
|
import { useQueries } from '@tanstack/react-query';
|
|
5
5
|
import { config } from '../config.js';
|
|
6
6
|
|
|
@@ -42,9 +42,9 @@ const clientProcessesContext = createContext({});
|
|
|
42
42
|
*
|
|
43
43
|
* @context
|
|
44
44
|
*/
|
|
45
|
-
const ClientProcessesProvider = ({ children
|
|
46
|
-
const [clientProcessDtos, setClientProcessDtos] = useState({});
|
|
45
|
+
const ClientProcessesProvider = ({ children }) => {
|
|
47
46
|
const clientProcessAttempts = useRef({});
|
|
47
|
+
const [clientProcessDtos, setClientProcessDtos] = useState({});
|
|
48
48
|
const clientProcesses = useQueries({
|
|
49
49
|
queries: Object.entries(clientProcessDtos).map(([processId, { dto, options }]) => ({
|
|
50
50
|
queryKey: ['.__process', processId],
|
|
@@ -69,19 +69,19 @@ const ClientProcessesProvider = ({ children, }) => {
|
|
|
69
69
|
if (process.status === 'pending') {
|
|
70
70
|
console.log(`Running process ${process.name} (${process.id})...`);
|
|
71
71
|
options?.onLoading?.(process.id, process.name);
|
|
72
|
-
return
|
|
72
|
+
return { id: process.id, name: process.name, pending: true };
|
|
73
73
|
}
|
|
74
74
|
else if (process.status === 'failed') {
|
|
75
75
|
console.error(`Failed ${process.name} (${process.id}) - ${process.error}.`);
|
|
76
76
|
return { id: process.id, name: process.name, success: false };
|
|
77
77
|
}
|
|
78
78
|
// Return null since no response
|
|
79
|
-
return
|
|
79
|
+
return { id: process.id, name: process.name, pending: true };
|
|
80
80
|
},
|
|
81
81
|
// Returns the next interval length to use to wait for fetch
|
|
82
82
|
refetchInterval: (query) => {
|
|
83
83
|
const data = query.state.data;
|
|
84
|
-
if (data
|
|
84
|
+
if (!data.pending)
|
|
85
85
|
return false;
|
|
86
86
|
// If not defined, init to 0
|
|
87
87
|
if (!clientProcessAttempts.current[processId])
|
|
@@ -99,10 +99,10 @@ const ClientProcessesProvider = ({ children, }) => {
|
|
|
99
99
|
* @param processCallbackDto
|
|
100
100
|
* @param options
|
|
101
101
|
*/
|
|
102
|
-
const registerProcess = (processId, processCallbackDto, options) => {
|
|
102
|
+
const registerProcess = (processId, processCallbackDto, metadata, options) => {
|
|
103
103
|
setClientProcessDtos({
|
|
104
104
|
...clientProcessDtos,
|
|
105
|
-
[processId]: { dto: processCallbackDto, options },
|
|
105
|
+
[processId]: { dto: processCallbackDto, metadata, options },
|
|
106
106
|
});
|
|
107
107
|
};
|
|
108
108
|
/**
|
|
@@ -112,19 +112,26 @@ const ClientProcessesProvider = ({ children, }) => {
|
|
|
112
112
|
* @returns
|
|
113
113
|
*/
|
|
114
114
|
const getProcess = (processId) => {
|
|
115
|
-
|
|
115
|
+
const clientProcess = clientProcesses.find((clientProcess) => clientProcess.data?.id === processId)?.data ?? null;
|
|
116
|
+
return (clientProcess &&
|
|
117
|
+
{
|
|
118
|
+
...clientProcess,
|
|
119
|
+
metadata: clientProcessDtos[clientProcess.id].metadata,
|
|
120
|
+
});
|
|
116
121
|
};
|
|
117
122
|
/**
|
|
118
123
|
* Filters processes by the provided attribute.
|
|
119
124
|
*
|
|
120
|
-
* @param
|
|
125
|
+
* @param filterKey
|
|
121
126
|
*/
|
|
122
|
-
const filterProcesses = (
|
|
127
|
+
const filterProcesses = (filterKey) => {
|
|
123
128
|
return clientProcesses
|
|
124
|
-
.filter((clientProcess) => clientProcess.data
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
.
|
|
129
|
+
.filter((clientProcess) => !!clientProcess.data && !!clientProcess.data.id)
|
|
130
|
+
.map((clientProcess) => ({
|
|
131
|
+
...clientProcess.data,
|
|
132
|
+
metadata: clientProcessDtos[clientProcess.data.id].metadata,
|
|
133
|
+
}))
|
|
134
|
+
.filter((clientProcessData) => clientProcessData.metadata.filterKey === filterKey);
|
|
128
135
|
};
|
|
129
136
|
return (jsxRuntimeExports.jsx(clientProcessesContext.Provider, { value: {
|
|
130
137
|
registerProcess,
|
|
@@ -144,10 +151,9 @@ function useClientProcess({ caller, filterKey, onLoading, onSuccess, onFailure,
|
|
|
144
151
|
// Note that the exposed function doesn't return process ids
|
|
145
152
|
// Client should be oblivious to those
|
|
146
153
|
// Abstraction BABY!
|
|
147
|
-
const wrappedCaller = async (inputs) => {
|
|
154
|
+
const wrappedCaller = async (inputs, metadata) => {
|
|
148
155
|
const response = await caller(inputs);
|
|
149
|
-
clientProcessesApi.registerProcess(response.processId, response, {
|
|
150
|
-
filter: filterKey,
|
|
156
|
+
clientProcessesApi.registerProcess(response.processId, response, { filterKey, metadata }, {
|
|
151
157
|
onLoading,
|
|
152
158
|
onSuccess,
|
|
153
159
|
onFailure,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"useClientProcess.js","sources":["../../src/hooks/useClientProcess.tsx"],"sourcesContent":["'use client';\r\n\r\nimport { useState, useRef, createContext, useContext } from 'react';\r\nimport { Query, useQueries } from '@tanstack/react-query';\r\nimport { config } from '../config';\r\n\r\ntype ProcessStatus = 'pending' | 'handled' | 'failed';\r\n\r\ninterface Process<T> {\r\n id: string;\r\n name: string;\r\n status: ProcessStatus;\r\n result?: T;\r\n error?: string;\r\n timestamp: string;\r\n}\r\n\r\nexport interface ProcessCallbackDto {\r\n processId: string;\r\n processName: string;\r\n processCallbackUrl: string;\r\n}\r\n\r\nexport interface ClientProcessOptions {\r\n filter?: string;\r\n onLoading?: (processId: string, processName: string) => void;\r\n onSuccess?: <R>(processId: string, processName: string, result: R) => void;\r\n onFailure?: (processId: string, processName: string, error?: string) => void;\r\n}\r\n\r\nexport interface ProcessResponse {\r\n processId: string;\r\n processName: string;\r\n processCallbackUrl: string;\r\n success: boolean;\r\n message?: string;\r\n}\r\n\r\n/**\r\n * The orchestrator service to get the process from.\r\n *\r\n * @param processId\r\n * @returns\r\n */\r\nconst processStatusChecker = <T,>(processId: string) =>\r\n fetch(`${config.orchestratorApi}/${encodeURIComponent(processId)}`, {\r\n method: 'GET',\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n },\r\n }).then((response) => response.json()) as unknown as Promise<{\r\n process: Omit<Process<T>, 'result'>;\r\n }>;\r\n\r\n/**\r\n * This fetches from the callback endpoint.\r\n *\r\n * @param processId\r\n * @returns\r\n */\r\nconst processCallbackResultFetcher = <T,>(\r\n processId: string,\r\n processName: string,\r\n processCallbackUrl?: string,\r\n) =>\r\n fetch(`${processCallbackUrl}`, {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n },\r\n body: JSON.stringify({\r\n processId,\r\n processName,\r\n }),\r\n }).then((response) => response.json()) as unknown as Promise<T>;\r\n\r\ninterface ClientProcesses {\r\n registerProcess: (\r\n processId: string,\r\n dto: ProcessCallbackDto,\r\n options?: ClientProcessOptions,\r\n ) => void;\r\n getProcess: (\r\n processId: string,\r\n ) => { id: string; name: string; result?: unknown; success: boolean } | null;\r\n filterProcesses: (\r\n filter: string,\r\n ) => { id: string; name: string; result?: unknown; success: boolean }[];\r\n cp: Query[];\r\n}\r\n\r\n/**\r\n * We need a context to keep track of all client processes.\r\n * This helps us manage the state of the toasts as well.\r\n */\r\nconst clientProcessesContext = createContext<ClientProcesses>(\r\n {} as ClientProcesses,\r\n);\r\n\r\n/**\r\n * This should be at the root layout.\r\n *\r\n * @context\r\n */\r\nexport const ClientProcessesProvider = ({\r\n children,\r\n}: {\r\n children: React.ReactNode;\r\n}) => {\r\n const [clientProcessDtos, setClientProcessDtos] = useState<\r\n Record<string, { dto: ProcessCallbackDto; options?: ClientProcessOptions }>\r\n >({});\r\n const clientProcessAttempts = useRef<Record<string, number>>({});\r\n const clientProcesses = useQueries({\r\n queries: Object.entries(clientProcessDtos).map(\r\n ([processId, { dto, options }]) => ({\r\n queryKey: ['.__process', processId],\r\n queryFn: async () => {\r\n if (!processId) throw new Error('No processId');\r\n const { process } = await processStatusChecker(processId);\r\n\r\n // Handled! Return the proper response too\r\n if (process.status === 'handled') {\r\n const result = await processCallbackResultFetcher(\r\n process.id,\r\n process.name,\r\n dto.processCallbackUrl,\r\n );\r\n\r\n // Log and call runner\r\n console.warn(`Handled ${process.name} (${process.id})!`);\r\n options?.onSuccess?.(process.id, process.name, result);\r\n\r\n return {\r\n id: process.id,\r\n name: process.name,\r\n success: true,\r\n result,\r\n };\r\n }\r\n\r\n // Pending or failed\r\n if (process.status === 'pending') {\r\n console.log(`Running process ${process.name} (${process.id})...`);\r\n options?.onLoading?.(process.id, process.name);\r\n return null;\r\n } else if (process.status === 'failed') {\r\n console.error(\r\n `Failed ${process.name} (${process.id}) - ${process.error}.`,\r\n );\r\n return { id: process.id, name: process.name, success: false };\r\n }\r\n\r\n // Return null since no response\r\n return null;\r\n },\r\n\r\n // Returns the next interval length to use to wait for fetch\r\n refetchInterval: (query: Query) => {\r\n const data = query.state.data;\r\n if (data !== null) return false;\r\n\r\n // If not defined, init to 0\r\n if (!clientProcessAttempts.current[processId])\r\n clientProcessAttempts.current[processId] = 0;\r\n\r\n const interval = Math.min(\r\n 500 * 2 ** clientProcessAttempts.current[processId],\r\n 10000,\r\n );\r\n\r\n clientProcessAttempts.current[processId] += 1;\r\n return interval;\r\n },\r\n }),\r\n ),\r\n });\r\n\r\n /**\r\n * Registers a new process to handle\r\n *\r\n * @param processId\r\n * @param processCallbackDto\r\n * @param options\r\n */\r\n const registerProcess = (\r\n processId: string,\r\n processCallbackDto: ProcessCallbackDto,\r\n options?: ClientProcessOptions,\r\n ) => {\r\n setClientProcessDtos({\r\n ...clientProcessDtos,\r\n [processId]: { dto: processCallbackDto, options },\r\n });\r\n };\r\n\r\n /**\r\n * Retrieves a process\r\n *\r\n * @param processId\r\n * @returns\r\n */\r\n const getProcess = (processId: string) => {\r\n return (\r\n clientProcesses.find(\r\n (clientProcess) => clientProcess.data?.id === processId,\r\n )?.data ?? null\r\n );\r\n };\r\n\r\n /**\r\n * Filters processes by the provided attribute.\r\n *\r\n * @param filter\r\n */\r\n const filterProcesses = (filter: string) => {\r\n return clientProcesses\r\n .filter(\r\n (clientProcess) =>\r\n clientProcess.data?.id &&\r\n clientProcessDtos[clientProcess.data.id].options?.filter === filter,\r\n )\r\n .map((clientProcess) => clientProcess.data)\r\n .filter((clientProcessData) => !!clientProcessData);\r\n };\r\n\r\n return (\r\n <clientProcessesContext.Provider\r\n value={{\r\n registerProcess,\r\n getProcess,\r\n filterProcesses,\r\n cp: clientProcesses,\r\n }}\r\n >\r\n {children}\r\n </clientProcessesContext.Provider>\r\n );\r\n};\r\n\r\n/**\r\n * A simpler version, where u just pass the async function that returns process data.\r\n *\r\n * @param caller\r\n * @returns\r\n */\r\nexport function useClientProcess<T>({\r\n caller,\r\n filterKey,\r\n onLoading,\r\n onSuccess,\r\n onFailure,\r\n}: {\r\n caller: (inputs: T) => Promise<ProcessResponse>;\r\n filterKey: string;\r\n onLoading?: (processId: string, processName: string) => void;\r\n onSuccess?: <R>(processId: string, processName: string, result: R) => void;\r\n onFailure?: (processId: string, processName: string, error?: string) => void;\r\n}) {\r\n const clientProcessesApi = useContext(clientProcessesContext);\r\n\r\n // Note that the exposed function doesn't return process ids\r\n // Client should be oblivious to those\r\n // Abstraction BABY!\r\n const wrappedCaller = async (inputs: T) => {\r\n const response = await caller(inputs);\r\n clientProcessesApi.registerProcess(response.processId, response, {\r\n filter: filterKey,\r\n onLoading,\r\n onSuccess,\r\n onFailure,\r\n });\r\n\r\n return {\r\n id: response.processId,\r\n success: response.success,\r\n message: response.message,\r\n };\r\n };\r\n\r\n return {\r\n run: wrappedCaller,\r\n get: (id: string) => clientProcessesApi.getProcess(id),\r\n getAll: () => clientProcessesApi.filterProcesses(filterKey),\r\n cp: clientProcessesApi.cp,\r\n };\r\n}"],"names":[],"mappings":";;;;;;AAsCA;;;;;AAKG;AACH;AAEI;AACA;AACE;AACD;AACF;AAIH;;;;;AAKG;AACH;AAMI;AACA;AACE;AACD;AACD;;;;AAID;AAiBH;;;AAGG;AACH;AAIA;;;;AAIG;;;AASD;;;AAIM;;AAEE;AAAgB;;;AAIhB;AACE;;AAOA;AACA;;;;AAKE;;;;;AAMJ;AACE;AACA;AACA;;AACK;AACL;AAGA;;;AAIF;;;AAIF;AACE;;AACmB;;AAGnB;AACE;AAEF;AAKA;AACA;;AAEH;AAEJ;AAED;;;;;;AAMG;;AAMD;AACE;;AAED;AACH;AAEA;;;;;AAKG;AACH;;AAMA;AAEA;;;;AAIG;AACH;AACE;;AAIM;;;AAIR;AAEA;;;;AAMM;;AAMR;AAEA;;;;;AAKG;AACG;AAaJ;;;;AAKA;AACE;;AAEE;;;;AAID;;;;;;AAOH;;AAGE;;;;;AAKJ;;"}
|
|
1
|
+
{"version":3,"file":"useClientProcess.js","sources":["../../src/hooks/useClientProcess.tsx"],"sourcesContent":["'use client';\r\n\r\nimport { useState, useRef, createContext, useContext } from 'react';\r\nimport { Query, useQueries, UseQueryResult } from '@tanstack/react-query';\r\nimport { config } from '../config';\r\n\r\ntype ProcessStatus = 'pending' | 'handled' | 'failed';\r\n\r\ninterface Process<T> {\r\n id: string;\r\n name: string;\r\n status: ProcessStatus;\r\n result?: T;\r\n error?: string;\r\n timestamp: string;\r\n}\r\n\r\ninterface ClientProcess<T> {\r\n id: string;\r\n name: string;\r\n result?: T;\r\n metadata?: ClientProcessMetadata;\r\n success?: boolean;\r\n pending?: boolean;\r\n error?: string;\r\n}\r\n\r\nexport interface ProcessCallbackDto {\r\n processId: string;\r\n processName: string;\r\n processCallbackUrl: string;\r\n}\r\n\r\nexport interface ClientProcessOptions {\r\n onLoading?: (processId: string, processName: string) => void;\r\n onSuccess?: <R>(processId: string, processName: string, result: R) => void;\r\n onFailure?: (processId: string, processName: string, error?: string) => void;\r\n}\r\n\r\nexport interface ClientProcessMetadata {\r\n filterKey: string;\r\n metadata?: Record<string, string>;\r\n}\r\n\r\nexport interface ProcessResponse {\r\n processId: string;\r\n processName: string;\r\n processCallbackUrl: string;\r\n success: boolean;\r\n message?: string;\r\n}\r\n\r\n/**\r\n * The orchestrator service to get the process from.\r\n *\r\n * @param processId\r\n * @returns\r\n */\r\nconst processStatusChecker = <T,>(processId: string) =>\r\n fetch(`${config.orchestratorApi}/${encodeURIComponent(processId)}`, {\r\n method: 'GET',\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n },\r\n }).then((response) => response.json()) as unknown as Promise<{\r\n process: Omit<Process<T>, 'result'>;\r\n }>;\r\n\r\n/**\r\n * This fetches from the callback endpoint.\r\n *\r\n * @param processId\r\n * @returns\r\n */\r\nconst processCallbackResultFetcher = <T,>(\r\n processId: string,\r\n processName: string,\r\n processCallbackUrl?: string,\r\n) =>\r\n fetch(`${processCallbackUrl}`, {\r\n method: 'POST',\r\n headers: {\r\n 'Content-Type': 'application/json',\r\n },\r\n body: JSON.stringify({\r\n processId,\r\n processName,\r\n }),\r\n }).then((response) => response.json()) as unknown as Promise<T>;\r\n\r\ninterface ClientProcesses {\r\n registerProcess: (\r\n processId: string,\r\n dto: ProcessCallbackDto,\r\n metadata: ClientProcessMetadata,\r\n options?: ClientProcessOptions,\r\n ) => void;\r\n getProcess: <T>(processId: string) => ClientProcess<T> | null;\r\n filterProcesses: <T>(filter: string) => ClientProcess<T>[];\r\n cp: UseQueryResult[];\r\n}\r\n\r\n/**\r\n * We need a context to keep track of all client processes.\r\n * This helps us manage the state of the toasts as well.\r\n */\r\nconst clientProcessesContext = createContext<ClientProcesses>(\r\n {} as ClientProcesses,\r\n);\r\n\r\n/**\r\n * This should be at the root layout.\r\n *\r\n * @context\r\n */\r\nexport const ClientProcessesProvider = ({ children }: { children: React.ReactNode }) => {\r\n const clientProcessAttempts = useRef<Record<string, number>>({});\r\n const [clientProcessDtos, setClientProcessDtos] = useState<\r\n Record<\r\n string,\r\n {\r\n dto: ProcessCallbackDto;\r\n metadata: ClientProcessMetadata;\r\n options?: ClientProcessOptions;\r\n }\r\n >\r\n >({});\r\n\r\n const clientProcesses = useQueries({\r\n queries: Object.entries(clientProcessDtos).map(\r\n ([processId, { dto, options }]) => ({\r\n queryKey: ['.__process', processId],\r\n queryFn: async () => {\r\n if (!processId) throw new Error('No processId');\r\n const { process } = await processStatusChecker(processId);\r\n\r\n // Handled! Return the proper response too\r\n if (process.status === 'handled') {\r\n const result = await processCallbackResultFetcher(\r\n process.id,\r\n process.name,\r\n dto.processCallbackUrl,\r\n );\r\n\r\n // Log and call runner\r\n console.warn(`Handled ${process.name} (${process.id})!`);\r\n options?.onSuccess?.(process.id, process.name, result);\r\n\r\n return {\r\n id: process.id,\r\n name: process.name,\r\n success: true,\r\n result,\r\n };\r\n }\r\n\r\n // Pending or failed\r\n if (process.status === 'pending') {\r\n console.log(`Running process ${process.name} (${process.id})...`);\r\n options?.onLoading?.(process.id, process.name);\r\n return { id: process.id, name: process.name, pending: true };\r\n } else if (process.status === 'failed') {\r\n console.error(\r\n `Failed ${process.name} (${process.id}) - ${process.error}.`,\r\n );\r\n return { id: process.id, name: process.name, success: false };\r\n }\r\n\r\n // Return null since no response\r\n return { id: process.id, name: process.name, pending: true };\r\n },\r\n\r\n // Returns the next interval length to use to wait for fetch\r\n refetchInterval: <T,>(query: Query) => {\r\n const data = query.state.data as ClientProcess<T>;\r\n if (!data.pending) return false;\r\n\r\n // If not defined, init to 0\r\n if (!clientProcessAttempts.current[processId])\r\n clientProcessAttempts.current[processId] = 0;\r\n\r\n const interval = Math.min(\r\n 500 * 2 ** clientProcessAttempts.current[processId],\r\n 10000,\r\n );\r\n\r\n clientProcessAttempts.current[processId] += 1;\r\n return interval;\r\n },\r\n }),\r\n ),\r\n });\r\n\r\n /**\r\n * Registers a new process to handle\r\n *\r\n * @param processId\r\n * @param processCallbackDto\r\n * @param options\r\n */\r\n const registerProcess = (\r\n processId: string,\r\n processCallbackDto: ProcessCallbackDto,\r\n metadata: ClientProcessMetadata,\r\n options?: ClientProcessOptions,\r\n ) => {\r\n setClientProcessDtos({\r\n ...clientProcessDtos,\r\n [processId]: { dto: processCallbackDto, metadata, options },\r\n });\r\n };\r\n\r\n /**\r\n * Retrieves a process\r\n *\r\n * @param processId\r\n * @returns\r\n */\r\n const getProcess = <T,>(processId: string) => {\r\n const clientProcess =\r\n clientProcesses.find(\r\n (clientProcess) => clientProcess.data?.id === processId,\r\n )?.data ?? null;\r\n\r\n return (\r\n clientProcess &&\r\n ({\r\n ...clientProcess,\r\n metadata: clientProcessDtos[clientProcess.id].metadata,\r\n } as ClientProcess<T>)\r\n );\r\n };\r\n\r\n /**\r\n * Filters processes by the provided attribute.\r\n *\r\n * @param filterKey\r\n */\r\n const filterProcesses = <T,>(filterKey: string) => {\r\n return clientProcesses\r\n .filter(\r\n (clientProcess) => !!clientProcess.data && !!clientProcess.data.id,\r\n )\r\n .map((clientProcess) => ({\r\n ...clientProcess.data!,\r\n metadata: clientProcessDtos[clientProcess.data!.id].metadata,\r\n }))\r\n .filter(\r\n (clientProcessData) =>\r\n clientProcessData.metadata.filterKey === filterKey,\r\n ) as ClientProcess<T>[];\r\n };\r\n\r\n return (\r\n <clientProcessesContext.Provider\r\n value={{\r\n registerProcess,\r\n getProcess,\r\n filterProcesses,\r\n cp: clientProcesses,\r\n }}\r\n >\r\n {children}\r\n </clientProcessesContext.Provider>\r\n );\r\n};;;;\r\n\r\n/**\r\n * A simpler version, where u just pass the async function that returns process data.\r\n *\r\n * @param caller\r\n * @returns\r\n */\r\nexport function useClientProcess<T>({\r\n caller,\r\n filterKey,\r\n onLoading,\r\n onSuccess,\r\n onFailure,\r\n}: {\r\n caller: (inputs: T) => Promise<ProcessResponse>;\r\n filterKey: string;\r\n onLoading?: (processId: string, processName: string) => void;\r\n onSuccess?: <R>(processId: string, processName: string, result: R) => void;\r\n onFailure?: (processId: string, processName: string, error?: string) => void;\r\n}) {\r\n const clientProcessesApi = useContext(clientProcessesContext);\r\n\r\n // Note that the exposed function doesn't return process ids\r\n // Client should be oblivious to those\r\n // Abstraction BABY!\r\n const wrappedCaller = async (\r\n inputs: T,\r\n metadata?: Record<string, string>,\r\n ) => {\r\n const response = await caller(inputs);\r\n clientProcessesApi.registerProcess(\r\n response.processId,\r\n response,\r\n { filterKey, metadata },\r\n {\r\n onLoading,\r\n onSuccess,\r\n onFailure,\r\n },\r\n );\r\n\r\n return {\r\n id: response.processId,\r\n success: response.success,\r\n message: response.message,\r\n };\r\n };\r\n\r\n return {\r\n run: wrappedCaller,\r\n get: (id: string) => clientProcessesApi.getProcess(id),\r\n getAll: () => clientProcessesApi.filterProcesses(filterKey),\r\n cp: clientProcessesApi.cp,\r\n };\r\n}"],"names":[],"mappings":";;;;;;AAoDA;;;;;AAKG;AACH;AAEI;AACA;AACE;AACD;AACF;AAIH;;;;;AAKG;AACH;AAMI;AACA;AACE;AACD;AACD;;;;AAID;AAcH;;;AAGG;AACH;AAIA;;;;AAIG;;AAED;;;;AAeM;;AAEE;AAAgB;;;AAIhB;AACE;;AAOA;AACA;;;;AAKE;;;;;AAMJ;AACE;AACA;AACA;;AACK;AACL;AAGA;;;AAIF;;;AAIF;AACE;;AACmB;;AAGnB;AACE;AAEF;AAKA;AACA;;AAEH;AAEJ;AAED;;;;;;AAMG;;AAOD;AACE;;AAED;AACH;AAEA;;;;;AAKG;AACH;;AAME;AAEG;AACC;;AAEoB;AAE1B;AAEA;;;;AAIG;AACH;AACE;AACG;AAGA;;;AAGA;AACA;AAIL;AAEA;;;;AAMM;;AAMR;AAEA;;;;;AAKG;AACG;AAaJ;;;;;AASE;AACA;;;;AAQG;;;;;;AAQL;;AAGE;;;;;AAKJ;;"}
|