@betterinternship/components 1.5.8 → 1.5.10
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,14 +1,18 @@
|
|
|
1
|
+
import { UseQueryResult } from '@tanstack/react-query';
|
|
1
2
|
export interface ProcessCallbackDto {
|
|
2
3
|
processId: string;
|
|
3
4
|
processName: string;
|
|
4
5
|
processCallbackUrl: string;
|
|
5
6
|
}
|
|
6
7
|
export interface ClientProcessOptions {
|
|
7
|
-
filter?: string;
|
|
8
8
|
onLoading?: (processId: string, processName: string) => void;
|
|
9
9
|
onSuccess?: <R>(processId: string, processName: string, result: R) => void;
|
|
10
10
|
onFailure?: (processId: string, processName: string, error?: string) => void;
|
|
11
11
|
}
|
|
12
|
+
export interface ClientProcessMetadata {
|
|
13
|
+
filterKey: string;
|
|
14
|
+
metadata?: Record<string, string>;
|
|
15
|
+
}
|
|
12
16
|
export interface ProcessResponse {
|
|
13
17
|
processId: string;
|
|
14
18
|
processName: string;
|
|
@@ -21,7 +25,7 @@ export interface ProcessResponse {
|
|
|
21
25
|
*
|
|
22
26
|
* @context
|
|
23
27
|
*/
|
|
24
|
-
export declare const ClientProcessesProvider: ({ children
|
|
28
|
+
export declare const ClientProcessesProvider: ({ children }: {
|
|
25
29
|
children: React.ReactNode;
|
|
26
30
|
}) => import("react/jsx-runtime").JSX.Element;
|
|
27
31
|
/**
|
|
@@ -37,7 +41,7 @@ export declare function useClientProcess<T>({ caller, filterKey, onLoading, onSu
|
|
|
37
41
|
onSuccess?: <R>(processId: string, processName: string, result: R) => void;
|
|
38
42
|
onFailure?: (processId: string, processName: string, error?: string) => void;
|
|
39
43
|
}): {
|
|
40
|
-
run: (inputs: T) => Promise<{
|
|
44
|
+
run: (inputs: T, metadata?: Record<string, string>) => Promise<{
|
|
41
45
|
id: string;
|
|
42
46
|
success: boolean;
|
|
43
47
|
message: string | undefined;
|
|
@@ -46,12 +50,17 @@ export declare function useClientProcess<T>({ caller, filterKey, onLoading, onSu
|
|
|
46
50
|
id: string;
|
|
47
51
|
name: string;
|
|
48
52
|
result?: unknown;
|
|
49
|
-
success
|
|
53
|
+
success?: boolean;
|
|
54
|
+
pending?: boolean;
|
|
55
|
+
error?: string;
|
|
50
56
|
} | null;
|
|
51
57
|
getAll: () => {
|
|
52
58
|
id: string;
|
|
53
59
|
name: string;
|
|
54
60
|
result?: unknown;
|
|
55
|
-
success
|
|
61
|
+
success?: boolean;
|
|
62
|
+
pending?: boolean;
|
|
63
|
+
error?: string;
|
|
56
64
|
}[];
|
|
65
|
+
cp: UseQueryResult[];
|
|
57
66
|
};
|
|
@@ -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,14 +69,14 @@ 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) => {
|
|
@@ -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,24 +112,31 @@ 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
|
+
...clientProcess,
|
|
118
|
+
metadata: clientProcessDtos[clientProcess.id].metadata,
|
|
119
|
+
});
|
|
116
120
|
};
|
|
117
121
|
/**
|
|
118
122
|
* Filters processes by the provided attribute.
|
|
119
123
|
*
|
|
120
|
-
* @param
|
|
124
|
+
* @param filterKey
|
|
121
125
|
*/
|
|
122
|
-
const filterProcesses = (
|
|
126
|
+
const filterProcesses = (filterKey) => {
|
|
123
127
|
return clientProcesses
|
|
124
|
-
.filter((clientProcess) => clientProcess.data
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
+
.filter((clientProcess) => !!clientProcess.data && !!clientProcess.data.id)
|
|
129
|
+
.map((clientProcess) => ({
|
|
130
|
+
...clientProcess.data,
|
|
131
|
+
metadata: clientProcessDtos[clientProcess.data.id].metadata,
|
|
132
|
+
}))
|
|
133
|
+
.filter((clientProcessData) => clientProcessData.metadata.filterKey === filterKey);
|
|
128
134
|
};
|
|
129
135
|
return (jsxRuntimeExports.jsx(clientProcessesContext.Provider, { value: {
|
|
130
136
|
registerProcess,
|
|
131
137
|
getProcess,
|
|
132
138
|
filterProcesses,
|
|
139
|
+
cp: clientProcesses,
|
|
133
140
|
}, children: children }));
|
|
134
141
|
};
|
|
135
142
|
/**
|
|
@@ -143,10 +150,9 @@ function useClientProcess({ caller, filterKey, onLoading, onSuccess, onFailure,
|
|
|
143
150
|
// Note that the exposed function doesn't return process ids
|
|
144
151
|
// Client should be oblivious to those
|
|
145
152
|
// Abstraction BABY!
|
|
146
|
-
const wrappedCaller = async (inputs) => {
|
|
153
|
+
const wrappedCaller = async (inputs, metadata) => {
|
|
147
154
|
const response = await caller(inputs);
|
|
148
|
-
clientProcessesApi.registerProcess(response.processId, response, {
|
|
149
|
-
filter: filterKey,
|
|
155
|
+
clientProcessesApi.registerProcess(response.processId, response, { filterKey, metadata }, {
|
|
150
156
|
onLoading,
|
|
151
157
|
onSuccess,
|
|
152
158
|
onFailure,
|
|
@@ -161,6 +167,7 @@ function useClientProcess({ caller, filterKey, onLoading, onSuccess, onFailure,
|
|
|
161
167
|
run: wrappedCaller,
|
|
162
168
|
get: (id) => clientProcessesApi.getProcess(id),
|
|
163
169
|
getAll: () => clientProcessesApi.filterProcesses(filterKey),
|
|
170
|
+
cp: clientProcessesApi.cp,
|
|
164
171
|
};
|
|
165
172
|
}
|
|
166
173
|
|
|
@@ -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
|
|
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\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: (processId: string) => {\r\n id: string;\r\n name: string;\r\n result?: unknown;\r\n success?: boolean;\r\n pending?: boolean;\r\n error?: string;\r\n } | null;\r\n filterProcesses: (filter: string) => {\r\n id: string;\r\n name: string;\r\n result?: unknown;\r\n success?: boolean;\r\n pending?: boolean;\r\n error?: string;\r\n }[];\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: (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 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 = (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 ...clientProcess,\r\n metadata: clientProcessDtos[clientProcess.id].metadata,\r\n }\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 = (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 );\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":";;;;;;AA0CA;;;;;AAKG;AACH;AAEI;AACA;AACE;AACD;AACF;AAIH;;;;;AAKG;AACH;AAMI;AACA;AACE;AACD;AACD;;;;AAID;AA4BH;;;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;;;AAQM;;AAED;AAEL;AAEA;;;;AAIG;AACH;AACE;AACG;AAGA;;;AAGA;AACA;AAIL;AAEA;;;;AAMM;;AAMR;AAEA;;;;;AAKG;AACG;AAaJ;;;;;AASE;AACA;;;;AAQG;;;;;;AAQL;;AAGE;;;;;AAKJ;;"}
|