@faasjs/react 0.0.2-beta.95 → 0.0.3-beta.2

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.
package/README.md CHANGED
@@ -1,9 +1,305 @@
1
1
  # @faasjs/react
2
2
 
3
- React 插件
4
-
5
- [![License: MIT](https://img.shields.io/npm/l/@faasjs/react.svg)](https://github.com/faasjs/faasjs/blob/master/packages/faasjs/react/LICENSE)
3
+ [![License: MIT](https://img.shields.io/npm/l/@faasjs/react.svg)](https://github.com/faasjs/faasjs/blob/main/packages/faasjs/react/LICENSE)
6
4
  [![NPM Stable Version](https://img.shields.io/npm/v/@faasjs/react/stable.svg)](https://www.npmjs.com/package/@faasjs/react)
7
5
  [![NPM Beta Version](https://img.shields.io/npm/v/@faasjs/react/beta.svg)](https://www.npmjs.com/package/@faasjs/react)
8
6
 
9
- https://faasjs.com/guide/excel/react.html
7
+ React plugin for FaasJS.
8
+
9
+ **If you use [SWR](https://swr.vercel.app) or [React Query / TanStack Query](https://tanstack.com/query), please use [`@faasjs/browser`](https://faasjs.com/doc/browser) directly.**
10
+
11
+ ## Install
12
+
13
+ npm install @faasjs/react
14
+
15
+ ## Modules
16
+
17
+ ### Classes
18
+
19
+ - [FaasBrowserClient](classes/FaasBrowserClient.md)
20
+ - [Response](classes/Response.md)
21
+ - [ResponseError](classes/ResponseError.md)
22
+
23
+ ### Type Aliases
24
+
25
+ - [FaasAction](#faasaction)
26
+ - [FaasData](#faasdata)
27
+ - [FaasDataInjection](#faasdatainjection)
28
+ - [FaasDataWrapperProps](#faasdatawrapperprops)
29
+ - [FaasParams](#faasparams)
30
+ - [FaasReactClientInstance](#faasreactclientinstance)
31
+ - [Options](#options)
32
+ - [ResponseHeaders](#responseheaders)
33
+
34
+ ### Functions
35
+
36
+ - [FaasDataWrapper](#faasdatawrapper)
37
+ - [FaasReactClient](#faasreactclient)
38
+ - [faas](#faas)
39
+ - [getClient](#getclient)
40
+ - [useFaas](#usefaas)
41
+
42
+ ## Type Aliases
43
+
44
+ ### FaasAction
45
+
46
+ Ƭ **FaasAction**: `FaasActionPaths` \| `Record`<`string`, `any`\>
47
+
48
+ ___
49
+
50
+ ### FaasData
51
+
52
+ Ƭ **FaasData**<`T`\>: `T` extends `FaasActionPaths` ? `FaasActions`[`T`][``"Data"``] : `T`
53
+
54
+ #### Type parameters
55
+
56
+ | Name | Type |
57
+ | :------ | :------ |
58
+ | `T` | `any` |
59
+
60
+ ___
61
+
62
+ ### FaasDataInjection
63
+
64
+ Ƭ **FaasDataInjection**<`Data`\>: `Object`
65
+
66
+ Injects FaasData props.
67
+
68
+ #### Type parameters
69
+
70
+ | Name | Type |
71
+ | :------ | :------ |
72
+ | `Data` | `any` |
73
+
74
+ #### Type declaration
75
+
76
+ | Name | Type |
77
+ | :------ | :------ |
78
+ | `action` | `string` \| `any` |
79
+ | `data` | `Data` |
80
+ | `error` | `any` |
81
+ | `loading` | `boolean` |
82
+ | `params` | `Record`<`string`, `any`\> |
83
+ | `promise` | `Promise`<[`Response`](classes/Response.md)<`Data`\>\> |
84
+ | `setData` | `React.Dispatch`<`React.SetStateAction`<`Data`\>\> |
85
+ | `setError` | `React.Dispatch`<`React.SetStateAction`<`any`\>\> |
86
+ | `setLoading` | `React.Dispatch`<`React.SetStateAction`<`boolean`\>\> |
87
+ | `setPromise` | `React.Dispatch`<`React.SetStateAction`<`Promise`<[`Response`](classes/Response.md)<`Data`\>\>\>\> |
88
+ | `reload` | (`params?`: `Record`<`string`, `any`\>) => `Promise`<[`Response`](classes/Response.md)<`Data`\>\> |
89
+
90
+ ___
91
+
92
+ ### FaasDataWrapperProps
93
+
94
+ Ƭ **FaasDataWrapperProps**<`PathOrData`\>: `Object`
95
+
96
+ #### Type parameters
97
+
98
+ | Name | Type |
99
+ | :------ | :------ |
100
+ | `PathOrData` | extends [`FaasAction`](#faasaction) |
101
+
102
+ #### Type declaration
103
+
104
+ | Name | Type | Description |
105
+ | :------ | :------ | :------ |
106
+ | `action` | `string` | - |
107
+ | `data?` | [`FaasData`](#faasdata)<`PathOrData`\> | use custom data, should work with setData |
108
+ | `fallback?` | `JSX.Element` \| ``false`` | - |
109
+ | `params?` | [`FaasParams`](#faasparams)<`PathOrData`\> | - |
110
+ | `setData?` | `React.Dispatch`<`React.SetStateAction`<[`FaasData`](#faasdata)<`PathOrData`\>\>\> | use custom setData, should work with data |
111
+ | `onDataChange?` | (`args`: [`FaasDataInjection`](#faasdatainjection)<[`FaasData`](#faasdata)<`PathOrData`\>\>) => `void` | - |
112
+ | `render?` | (`args`: [`FaasDataInjection`](#faasdatainjection)<[`FaasData`](#faasdata)<`PathOrData`\>\>) => `Element` \| `Element`[] | - |
113
+
114
+ ___
115
+
116
+ ### FaasParams
117
+
118
+ Ƭ **FaasParams**<`T`\>: `T` extends `FaasActionPaths` ? `FaasActions`[`T`][``"Params"``] : `any`
119
+
120
+ #### Type parameters
121
+
122
+ | Name | Type |
123
+ | :------ | :------ |
124
+ | `T` | `any` |
125
+
126
+ ___
127
+
128
+ ### FaasReactClientInstance
129
+
130
+ Ƭ **FaasReactClientInstance**: `Object`
131
+
132
+ #### Type declaration
133
+
134
+ | Name | Type |
135
+ | :------ | :------ |
136
+ | `faas` | <PathOrData\>(`action`: `string` \| `PathOrData`, `params`: [`FaasParams`](#faasparams)<`PathOrData`\>) => `Promise`<[`Response`](classes/Response.md)<[`FaasData`](#faasdata)<`PathOrData`\>\>\> |
137
+ | `useFaas` | <PathOrData\>(`action`: `string` \| `PathOrData`, `defaultParams`: [`FaasParams`](#faasparams)<`PathOrData`\>) => [`FaasDataInjection`](#faasdatainjection)<[`FaasData`](#faasdata)<`PathOrData`\>\> |
138
+ | `FaasDataWrapper` | <PathOrData\>(`props`: [`FaasDataWrapperProps`](#faasdatawrapperprops)<`PathOrData`\>) => `Element` |
139
+
140
+ ___
141
+
142
+ ### Options
143
+
144
+ Ƭ **Options**: `RequestInit` & { `beforeRequest?`: (`{
145
+ action, params, options
146
+ }`: { `action`: `string` ; `options`: [`Options`](#options) ; `params`: `Record`<`string`, `any`\> }) => `Promise`<`void`\> \| `void` ; `headers?`: { `[key: string]`: `string`; } ; `request?`: <PathOrData\>(`url`: `string`, `options`: [`Options`](#options)) => `Promise`<[`Response`](classes/Response.md)<[`FaasData`](#faasdata)<`PathOrData`\>\>\> }
147
+
148
+ ___
149
+
150
+ ### ResponseHeaders
151
+
152
+ Ƭ **ResponseHeaders**: `Object`
153
+
154
+ #### Index signature
155
+
156
+ ▪ [key: `string`]: `string`
157
+
158
+ ## Functions
159
+
160
+ ### FaasDataWrapper
161
+
162
+ ▸ **FaasDataWrapper**<`PathOrData`\>(`props`): `JSX.Element`
163
+
164
+ A data wrapper for react components
165
+
166
+ #### Type parameters
167
+
168
+ | Name | Type |
169
+ | :------ | :------ |
170
+ | `PathOrData` | extends `Record`<`string`, `any`\> |
171
+
172
+ #### Parameters
173
+
174
+ | Name | Type |
175
+ | :------ | :------ |
176
+ | `props` | [`FaasDataWrapperProps`](#faasdatawrapperprops)<`PathOrData`\> |
177
+
178
+ #### Returns
179
+
180
+ `JSX.Element`
181
+
182
+ ```ts
183
+ <FaasDataWrapper<{
184
+ id: string
185
+ title: string
186
+ }>
187
+ action='post/get'
188
+ params={ { id: 1 } }
189
+ render={ ({ data }) => <h1>{ data.title }</h1> }
190
+ />
191
+ ```
192
+
193
+ ___
194
+
195
+ ### FaasReactClient
196
+
197
+ ▸ **FaasReactClient**(`__namedParameters`): [`FaasReactClientInstance`](#faasreactclientinstance)
198
+
199
+ Before use faas, you should initialize a FaasReactClient.
200
+
201
+ #### Parameters
202
+
203
+ | Name | Type |
204
+ | :------ | :------ |
205
+ | `__namedParameters` | `Object` |
206
+ | `__namedParameters.domain` | `string` |
207
+ | `__namedParameters.onError?` | (`action`: `string`, `params`: `Record`<`string`, `any`\>) => (`res`: [`ResponseError`](classes/ResponseError.md)) => `Promise`<`void`\> |
208
+ | `__namedParameters.options?` | [`Options`](#options) |
209
+
210
+ #### Returns
211
+
212
+ [`FaasReactClientInstance`](#faasreactclientinstance)
213
+
214
+ ```ts
215
+ const client = FaasReactClient({
216
+ domain: 'localhost:8080/api'
217
+ })
218
+ ```
219
+
220
+ ___
221
+
222
+ ### faas
223
+
224
+ ▸ **faas**<`PathOrData`\>(`action`, `params`): `Promise`<[`Response`](classes/Response.md)<[`FaasData`](#faasdata)<`PathOrData`\>\>\>
225
+
226
+ Request faas server
227
+
228
+ #### Type parameters
229
+
230
+ | Name | Type |
231
+ | :------ | :------ |
232
+ | `PathOrData` | extends `Record`<`string`, `any`\> |
233
+
234
+ #### Parameters
235
+
236
+ | Name | Type | Description |
237
+ | :------ | :------ | :------ |
238
+ | `action` | `string` \| `PathOrData` | {string} action name |
239
+ | `params` | [`FaasParams`](#faasparams)<`PathOrData`\> | {object} action params |
240
+
241
+ #### Returns
242
+
243
+ `Promise`<[`Response`](classes/Response.md)<[`FaasData`](#faasdata)<`PathOrData`\>\>\>
244
+
245
+ ```ts
246
+ faas<{ title: string }>('post/get', { id: 1 }).then(res => {
247
+ console.log(res.data.title)
248
+ })
249
+ ```
250
+
251
+ ___
252
+
253
+ ### getClient
254
+
255
+ ▸ **getClient**(`domain?`): [`FaasReactClientInstance`](#faasreactclientinstance)
256
+
257
+ Get FaasReactClient instance
258
+
259
+ #### Parameters
260
+
261
+ | Name | Type | Description |
262
+ | :------ | :------ | :------ |
263
+ | `domain?` | `string` | {string} empty string for default domain |
264
+
265
+ #### Returns
266
+
267
+ [`FaasReactClientInstance`](#faasreactclientinstance)
268
+
269
+ ```ts
270
+ getClient()
271
+ // or
272
+ getClient('another-domain')
273
+ ```
274
+
275
+ ___
276
+
277
+ ### useFaas
278
+
279
+ ▸ **useFaas**<`PathOrData`\>(`action`, `defaultParams`): [`FaasDataInjection`](#faasdatainjection)<[`FaasData`](#faasdata)<`PathOrData`\>\>
280
+
281
+ Request faas server with React hook
282
+
283
+ #### Type parameters
284
+
285
+ | Name | Type |
286
+ | :------ | :------ |
287
+ | `PathOrData` | extends `Record`<`string`, `any`\> |
288
+
289
+ #### Parameters
290
+
291
+ | Name | Type | Description |
292
+ | :------ | :------ | :------ |
293
+ | `action` | `string` \| `PathOrData` | {string} action name |
294
+ | `defaultParams` | [`FaasParams`](#faasparams)<`PathOrData`\> | {object} initial action params |
295
+
296
+ #### Returns
297
+
298
+ [`FaasDataInjection`](#faasdatainjection)<[`FaasData`](#faasdata)<`PathOrData`\>\>
299
+
300
+ ```ts
301
+ function Post ({ id }) {
302
+ const { data } = useFaas<{ title: string }>('post/get', { id })
303
+ return <h1>{data.title}</h1>
304
+ }
305
+ ```
@@ -0,0 +1,121 @@
1
+ import { Response, Options, ResponseError } from '@faasjs/browser';
2
+ export { FaasBrowserClient, Options, Response, ResponseError, ResponseHeaders } from '@faasjs/browser';
3
+ import { FaasAction, FaasData, FaasParams } from '@faasjs/types';
4
+ export { FaasAction, FaasData, FaasParams } from '@faasjs/types';
5
+
6
+ /**
7
+ * Injects FaasData props.
8
+ */
9
+ type FaasDataInjection<Data = any> = {
10
+ action: string | any;
11
+ params: Record<string, any>;
12
+ loading: boolean;
13
+ data: Data;
14
+ error: any;
15
+ promise: Promise<Response<Data>>;
16
+ reload(params?: Record<string, any>): Promise<Response<Data>>;
17
+ setData: React.Dispatch<React.SetStateAction<Data>>;
18
+ setLoading: React.Dispatch<React.SetStateAction<boolean>>;
19
+ setPromise: React.Dispatch<React.SetStateAction<Promise<Response<Data>>>>;
20
+ setError: React.Dispatch<React.SetStateAction<any>>;
21
+ };
22
+ type FaasDataWrapperProps<PathOrData extends FaasAction> = {
23
+ render?(args: FaasDataInjection<FaasData<PathOrData>>): JSX.Element | JSX.Element[];
24
+ fallback?: JSX.Element | false;
25
+ action: string;
26
+ params?: FaasParams<PathOrData>;
27
+ onDataChange?(args: FaasDataInjection<FaasData<PathOrData>>): void;
28
+ /** use custom data, should work with setData */
29
+ data?: FaasData<PathOrData>;
30
+ /** use custom setData, should work with data */
31
+ setData?: React.Dispatch<React.SetStateAction<FaasData<PathOrData>>>;
32
+ };
33
+ type FaasReactClientInstance = {
34
+ faas: <PathOrData extends FaasAction>(action: string | PathOrData, params: FaasParams<PathOrData>) => Promise<Response<FaasData<PathOrData>>>;
35
+ useFaas: <PathOrData extends FaasAction>(action: string | PathOrData, defaultParams: FaasParams<PathOrData>, options?: {
36
+ data?: FaasData<PathOrData>;
37
+ setData?: React.Dispatch<React.SetStateAction<FaasData<PathOrData>>>;
38
+ skip?: boolean;
39
+ }) => FaasDataInjection<FaasData<PathOrData>>;
40
+ FaasDataWrapper<PathOrData extends FaasAction>(props: FaasDataWrapperProps<PathOrData>): JSX.Element;
41
+ };
42
+ /**
43
+ * Before use faas, you should initialize a FaasReactClient.
44
+ *
45
+ * @param props.domain {string} The domain of your faas server
46
+ * @param props.options {Options} The options of client
47
+ * @returns {FaasReactClientInstance}
48
+ *
49
+ * ```ts
50
+ * const client = FaasReactClient({
51
+ * domain: 'localhost:8080/api'
52
+ * })
53
+ * ```
54
+ */
55
+ declare function FaasReactClient({ domain, options, onError }: {
56
+ domain: string;
57
+ options?: Options;
58
+ onError?: (action: string, params: Record<string, any>) => (res: ResponseError) => Promise<void>;
59
+ }): FaasReactClientInstance;
60
+ /**
61
+ * Get FaasReactClient instance
62
+ * @param domain {string} empty string for default domain
63
+ * @returns {FaasReactClientInstance}
64
+ *
65
+ * ```ts
66
+ * getClient()
67
+ * // or
68
+ * getClient('another-domain')
69
+ * ```
70
+ */
71
+ declare function getClient(domain?: string): FaasReactClientInstance;
72
+ /**
73
+ * Request faas server
74
+ *
75
+ * @param action {string} action name
76
+ * @param params {object} action params
77
+ * @returns {Promise<Response<any>>}
78
+ *
79
+ * ```ts
80
+ * faas<{ title: string }>('post/get', { id: 1 }).then(res => {
81
+ * console.log(res.data.title)
82
+ * })
83
+ * ```
84
+ */
85
+ declare function faas<PathOrData extends FaasAction>(action: string | PathOrData, params: FaasParams<PathOrData>): Promise<Response<FaasData<PathOrData>>>;
86
+ /**
87
+ * Request faas server with React hook
88
+ * @param action {string} action name
89
+ * @param defaultParams {object} initial action params
90
+ * @returns {FaasDataInjection<any>}
91
+ *
92
+ * ```ts
93
+ * function Post ({ id }) {
94
+ * const { data } = useFaas<{ title: string }>('post/get', { id })
95
+ * return <h1>{data.title}</h1>
96
+ * }
97
+ * ```
98
+ */
99
+ declare function useFaas<PathOrData extends FaasAction>(action: string | PathOrData, defaultParams: FaasParams<PathOrData>, options?: {
100
+ data?: FaasData<PathOrData>;
101
+ setData?: React.Dispatch<React.SetStateAction<FaasData<PathOrData>>>;
102
+ skip?: boolean;
103
+ }): FaasDataInjection<FaasData<PathOrData>>;
104
+ /**
105
+ * A data wrapper for react components
106
+ * @returns {JSX.Element}
107
+ *
108
+ * ```ts
109
+ * <FaasDataWrapper<{
110
+ * id: string
111
+ * title: string
112
+ * }>
113
+ * action='post/get'
114
+ * params={ { id: 1 } }
115
+ * render={ ({ data }) => <h1>{ data.title }</h1> }
116
+ * />
117
+ * ```
118
+ */
119
+ declare function FaasDataWrapper<PathOrData extends FaasAction>(props: FaasDataWrapperProps<PathOrData>): JSX.Element;
120
+
121
+ export { FaasDataInjection, FaasDataWrapper, FaasDataWrapperProps, FaasReactClient, FaasReactClientInstance, faas, getClient, useFaas };
package/dist/index.js ADDED
@@ -0,0 +1,169 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.tsx
21
+ var src_exports = {};
22
+ __export(src_exports, {
23
+ FaasDataWrapper: () => FaasDataWrapper,
24
+ FaasReactClient: () => FaasReactClient,
25
+ faas: () => faas,
26
+ getClient: () => getClient,
27
+ useFaas: () => useFaas
28
+ });
29
+ module.exports = __toCommonJS(src_exports);
30
+ var import_browser = require("@faasjs/browser");
31
+ var import_react = require("react");
32
+ var clients = {};
33
+ function FaasReactClient({
34
+ domain,
35
+ options,
36
+ onError
37
+ }) {
38
+ const client = new import_browser.FaasBrowserClient(domain, options);
39
+ async function faas2(action, params) {
40
+ if (onError)
41
+ return client.action(action, params).catch(async (res) => {
42
+ await onError(action, params)(res);
43
+ return Promise.reject(res);
44
+ });
45
+ return client.action(action, params);
46
+ }
47
+ function useFaas2(action, defaultParams, options2) {
48
+ if (!options2)
49
+ options2 = {};
50
+ const [loading, setLoading] = (0, import_react.useState)(true);
51
+ const [data, setData] = (0, import_react.useState)();
52
+ const [error, setError] = (0, import_react.useState)();
53
+ const [promise, setPromise] = (0, import_react.useState)();
54
+ const [params, setParams] = (0, import_react.useState)(defaultParams);
55
+ const [reloadTimes, setReloadTimes] = (0, import_react.useState)(0);
56
+ (0, import_react.useEffect)(function() {
57
+ if (JSON.stringify(defaultParams) !== JSON.stringify(params)) {
58
+ setParams(defaultParams);
59
+ }
60
+ }, [JSON.stringify(defaultParams)]);
61
+ (0, import_react.useEffect)(function() {
62
+ if (options2 == null ? void 0 : options2.skip) {
63
+ setLoading(false);
64
+ return;
65
+ }
66
+ setLoading(true);
67
+ const request = client.action(action, params);
68
+ setPromise(request);
69
+ request.then((r) => (options2 == null ? void 0 : options2.setData) ? options2.setData(r.data) : setData(r.data)).catch(async (e) => {
70
+ if (onError)
71
+ try {
72
+ await onError(action, params)(e);
73
+ } catch (error2) {
74
+ setError(error2);
75
+ }
76
+ else
77
+ setError(e);
78
+ return Promise.reject(e);
79
+ }).finally(() => setLoading(false));
80
+ return () => setLoading(false);
81
+ }, [
82
+ action,
83
+ JSON.stringify(params),
84
+ reloadTimes,
85
+ options2.skip
86
+ ]);
87
+ return {
88
+ action,
89
+ params,
90
+ loading,
91
+ data: (options2 == null ? void 0 : options2.data) || data,
92
+ error,
93
+ promise,
94
+ async reload(params2) {
95
+ if (params2)
96
+ setParams(params2);
97
+ setReloadTimes(reloadTimes + 1);
98
+ return promise;
99
+ },
100
+ setData: (options2 == null ? void 0 : options2.setData) || setData,
101
+ setLoading,
102
+ setPromise,
103
+ setError
104
+ };
105
+ }
106
+ const reactClient = {
107
+ faas: faas2,
108
+ useFaas: useFaas2,
109
+ FaasDataWrapper({
110
+ action,
111
+ params,
112
+ fallback,
113
+ render,
114
+ onDataChange,
115
+ data,
116
+ setData
117
+ }) {
118
+ const request = useFaas2(action, params, {
119
+ data,
120
+ setData
121
+ });
122
+ const [loaded, setLoaded] = (0, import_react.useState)(false);
123
+ (0, import_react.useEffect)(function() {
124
+ if (!loaded && !request.loading)
125
+ setLoaded(true);
126
+ }, [request.loading]);
127
+ (0, import_react.useEffect)(function() {
128
+ if (onDataChange)
129
+ onDataChange(request);
130
+ }, [JSON.stringify(request.data)]);
131
+ if (loaded)
132
+ return render(request);
133
+ return fallback || null;
134
+ }
135
+ };
136
+ clients[domain] = reactClient;
137
+ return reactClient;
138
+ }
139
+ function getClient(domain) {
140
+ const client = clients[domain || Object.keys(clients)[0]];
141
+ if (!client)
142
+ throw Error("FaasReactClient is not initialized");
143
+ return client;
144
+ }
145
+ async function faas(action, params) {
146
+ return getClient().faas(action, params);
147
+ }
148
+ function useFaas(action, defaultParams, options) {
149
+ return getClient().useFaas(action, defaultParams, options);
150
+ }
151
+ function FaasDataWrapper(props) {
152
+ const [client, setClient] = (0, import_react.useState)();
153
+ (0, import_react.useEffect)(() => {
154
+ if (client)
155
+ return;
156
+ setClient(getClient());
157
+ }, []);
158
+ if (!client)
159
+ return props.fallback || null;
160
+ return (0, import_react.createElement)(client.FaasDataWrapper, props);
161
+ }
162
+ // Annotate the CommonJS export names for ESM import in node:
163
+ 0 && (module.exports = {
164
+ FaasDataWrapper,
165
+ FaasReactClient,
166
+ faas,
167
+ getClient,
168
+ useFaas
169
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,146 @@
1
+ // src/index.tsx
2
+ import {
3
+ FaasBrowserClient
4
+ } from "@faasjs/browser";
5
+ import {
6
+ useState,
7
+ useEffect,
8
+ createElement
9
+ } from "react";
10
+ var clients = {};
11
+ function FaasReactClient({
12
+ domain,
13
+ options,
14
+ onError
15
+ }) {
16
+ const client = new FaasBrowserClient(domain, options);
17
+ async function faas2(action, params) {
18
+ if (onError)
19
+ return client.action(action, params).catch(async (res) => {
20
+ await onError(action, params)(res);
21
+ return Promise.reject(res);
22
+ });
23
+ return client.action(action, params);
24
+ }
25
+ function useFaas2(action, defaultParams, options2) {
26
+ if (!options2)
27
+ options2 = {};
28
+ const [loading, setLoading] = useState(true);
29
+ const [data, setData] = useState();
30
+ const [error, setError] = useState();
31
+ const [promise, setPromise] = useState();
32
+ const [params, setParams] = useState(defaultParams);
33
+ const [reloadTimes, setReloadTimes] = useState(0);
34
+ useEffect(function() {
35
+ if (JSON.stringify(defaultParams) !== JSON.stringify(params)) {
36
+ setParams(defaultParams);
37
+ }
38
+ }, [JSON.stringify(defaultParams)]);
39
+ useEffect(function() {
40
+ if (options2 == null ? void 0 : options2.skip) {
41
+ setLoading(false);
42
+ return;
43
+ }
44
+ setLoading(true);
45
+ const request = client.action(action, params);
46
+ setPromise(request);
47
+ request.then((r) => (options2 == null ? void 0 : options2.setData) ? options2.setData(r.data) : setData(r.data)).catch(async (e) => {
48
+ if (onError)
49
+ try {
50
+ await onError(action, params)(e);
51
+ } catch (error2) {
52
+ setError(error2);
53
+ }
54
+ else
55
+ setError(e);
56
+ return Promise.reject(e);
57
+ }).finally(() => setLoading(false));
58
+ return () => setLoading(false);
59
+ }, [
60
+ action,
61
+ JSON.stringify(params),
62
+ reloadTimes,
63
+ options2.skip
64
+ ]);
65
+ return {
66
+ action,
67
+ params,
68
+ loading,
69
+ data: (options2 == null ? void 0 : options2.data) || data,
70
+ error,
71
+ promise,
72
+ async reload(params2) {
73
+ if (params2)
74
+ setParams(params2);
75
+ setReloadTimes(reloadTimes + 1);
76
+ return promise;
77
+ },
78
+ setData: (options2 == null ? void 0 : options2.setData) || setData,
79
+ setLoading,
80
+ setPromise,
81
+ setError
82
+ };
83
+ }
84
+ const reactClient = {
85
+ faas: faas2,
86
+ useFaas: useFaas2,
87
+ FaasDataWrapper({
88
+ action,
89
+ params,
90
+ fallback,
91
+ render,
92
+ onDataChange,
93
+ data,
94
+ setData
95
+ }) {
96
+ const request = useFaas2(action, params, {
97
+ data,
98
+ setData
99
+ });
100
+ const [loaded, setLoaded] = useState(false);
101
+ useEffect(function() {
102
+ if (!loaded && !request.loading)
103
+ setLoaded(true);
104
+ }, [request.loading]);
105
+ useEffect(function() {
106
+ if (onDataChange)
107
+ onDataChange(request);
108
+ }, [JSON.stringify(request.data)]);
109
+ if (loaded)
110
+ return render(request);
111
+ return fallback || null;
112
+ }
113
+ };
114
+ clients[domain] = reactClient;
115
+ return reactClient;
116
+ }
117
+ function getClient(domain) {
118
+ const client = clients[domain || Object.keys(clients)[0]];
119
+ if (!client)
120
+ throw Error("FaasReactClient is not initialized");
121
+ return client;
122
+ }
123
+ async function faas(action, params) {
124
+ return getClient().faas(action, params);
125
+ }
126
+ function useFaas(action, defaultParams, options) {
127
+ return getClient().useFaas(action, defaultParams, options);
128
+ }
129
+ function FaasDataWrapper(props) {
130
+ const [client, setClient] = useState();
131
+ useEffect(() => {
132
+ if (client)
133
+ return;
134
+ setClient(getClient());
135
+ }, []);
136
+ if (!client)
137
+ return props.fallback || null;
138
+ return createElement(client.FaasDataWrapper, props);
139
+ }
140
+ export {
141
+ FaasDataWrapper,
142
+ FaasReactClient,
143
+ faas,
144
+ getClient,
145
+ useFaas
146
+ };
package/package.json CHANGED
@@ -1,23 +1,37 @@
1
1
  {
2
2
  "name": "@faasjs/react",
3
- "version": "0.0.2-beta.95",
3
+ "version": "0.0.3-beta.2",
4
4
  "license": "MIT",
5
- "main": "lib/index.js",
6
- "types": "lib/index.d.ts",
5
+ "main": "dist/index.js",
6
+ "module": "dist/index.mjs",
7
+ "types": "dist/index.d.ts",
8
+ "homepage": "https://faasjs.com/doc/react",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/faasjs/faasjs.git",
12
+ "directory": "packages/react"
13
+ },
14
+ "bugs": {
15
+ "url": "https://github.com/faasjs/faasjs/issues"
16
+ },
17
+ "funding": "https://github.com/sponsors/faasjs",
7
18
  "scripts": {
8
- "prepack": "rm -rf ./lib && rollup -c && mv lib/*/src/* lib/"
19
+ "build": "tsup src/index.tsx --format esm,cjs",
20
+ "build:types": "tsup-node src/index.tsx --dts-only"
9
21
  },
10
22
  "files": [
11
- "lib"
23
+ "dist"
12
24
  ],
13
25
  "dependencies": {
14
- "@faasjs/browser": "^0.0.2-beta.95"
26
+ "@faasjs/browser": "^0.0.3-beta.2",
27
+ "@faasjs/types": "^0.0.3-beta.2",
28
+ "react": "*"
15
29
  },
16
30
  "devDependencies": {
17
- "react": "*",
18
- "rollup": "*",
19
- "rollup-plugin-typescript2": "*",
20
- "typescript": "*"
31
+ "@types/react": "*"
21
32
  },
22
- "gitHead": "e5955ed30661b9cb7ddda79cc4f75567113801f0"
33
+ "engines": {
34
+ "npm": ">=8.0.0",
35
+ "node": ">=16.0.0"
36
+ }
23
37
  }
package/lib/index.d.ts DELETED
@@ -1,12 +0,0 @@
1
- import { Response } from '@faasjs/browser';
2
- export declare function FaasClient({ domain, onError }: {
3
- domain: string;
4
- onError?(action: string, params: any): (res: any) => any;
5
- }): {
6
- faas<T = any>(action: string, params: any): Promise<Response<T>>;
7
- useFaas<T = any>(action: string, params?: any): {
8
- loading: boolean;
9
- data: T;
10
- error: any;
11
- };
12
- };
package/lib/index.js DELETED
@@ -1,117 +0,0 @@
1
- 'use strict';
2
-
3
- Object.defineProperty(exports, '__esModule', { value: true });
4
-
5
- function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
6
-
7
- var Client = _interopDefault(require('@faasjs/browser'));
8
-
9
- /*! *****************************************************************************
10
- Copyright (c) Microsoft Corporation.
11
-
12
- Permission to use, copy, modify, and/or distribute this software for any
13
- purpose with or without fee is hereby granted.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
16
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
17
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
18
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
19
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
20
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
21
- PERFORMANCE OF THIS SOFTWARE.
22
- ***************************************************************************** */
23
-
24
- function __awaiter(thisArg, _arguments, P, generator) {
25
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
26
- return new (P || (P = Promise))(function (resolve, reject) {
27
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
28
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
29
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
30
- step((generator = generator.apply(thisArg, _arguments || [])).next());
31
- });
32
- }
33
-
34
- function __generator(thisArg, body) {
35
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
36
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
37
- function verb(n) { return function (v) { return step([n, v]); }; }
38
- function step(op) {
39
- if (f) throw new TypeError("Generator is already executing.");
40
- while (_) try {
41
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
42
- if (y = 0, t) op = [op[0] & 2, t.value];
43
- switch (op[0]) {
44
- case 0: case 1: t = op; break;
45
- case 4: _.label++; return { value: op[1], done: false };
46
- case 5: _.label++; y = op[1]; op = [0]; continue;
47
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
48
- default:
49
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
50
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
51
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
52
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
53
- if (t[2]) _.ops.pop();
54
- _.trys.pop(); continue;
55
- }
56
- op = body.call(thisArg, _);
57
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
58
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
59
- }
60
- }
61
-
62
- function __read(o, n) {
63
- var m = typeof Symbol === "function" && o[Symbol.iterator];
64
- if (!m) return o;
65
- var i = m.call(o), r, ar = [], e;
66
- try {
67
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
68
- }
69
- catch (error) { e = { error: error }; }
70
- finally {
71
- try {
72
- if (r && !r.done && (m = i["return"])) m.call(i);
73
- }
74
- finally { if (e) throw e.error; }
75
- }
76
- return ar;
77
- }
78
-
79
- // eslint-disable-next-line @typescript-eslint/no-var-requires
80
- var React = require('react');
81
- function FaasClient(_a) {
82
- var domain = _a.domain, onError = _a.onError;
83
- var client = new Client(domain);
84
- return {
85
- faas: function (action, params) {
86
- return __awaiter(this, void 0, void 0, function () {
87
- return __generator(this, function (_a) {
88
- if (onError)
89
- return [2 /*return*/, client.action(action, params).catch(onError(action, params))];
90
- return [2 /*return*/, client.action(action, params)];
91
- });
92
- });
93
- },
94
- useFaas: function (action, params) {
95
- var _a = __read(React.useState(false), 2), loading = _a[0], setLoading = _a[1];
96
- var _b = __read(React.useState(), 2), data = _b[0], setData = _b[1];
97
- var _c = __read(React.useState(), 2), error = _c[0], setError = _c[1];
98
- React.useEffect(function () {
99
- setLoading(true);
100
- client.action(action, params).then(function (r) {
101
- setData(r === null || r === void 0 ? void 0 : r.data);
102
- }).catch(function (e) {
103
- if (onError)
104
- onError(action, params)(e);
105
- setError(e);
106
- }).finally(function () { return setLoading(false); });
107
- }, [action, JSON.stringify(params)]);
108
- return {
109
- loading: loading,
110
- data: data,
111
- error: error
112
- };
113
- }
114
- };
115
- }
116
-
117
- exports.FaasClient = FaasClient;