From d24ff07bfcc5acae7afce0aa788691b77acc9b86 Mon Sep 17 00:00:00 2001 From: danybeltran Date: Fri, 3 Nov 2023 01:21:02 -0600 Subject: [PATCH] feat(rpc): Adds small rpc implementation --- package.json | 2 +- src/hooks/index.ts | 3 ++- src/hooks/others.ts | 38 ++++++++++++++++++++++++++++++++++++++ src/index.ts | 5 ++++- src/server/index.ts | 21 +++++++++++++++++++++ 5 files changed, 66 insertions(+), 3 deletions(-) create mode 100644 src/server/index.ts diff --git a/package.json b/package.json index cd121c6..1d2edee 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "http-react", - "version": "3.0.6", + "version": "3.1.0", "description": "React hooks for data fetching", "main": "dist/index.js", "scripts": { diff --git a/src/hooks/index.ts b/src/hooks/index.ts index 48ca288..e8db14c 100644 --- a/src/hooks/index.ts +++ b/src/hooks/index.ts @@ -36,5 +36,6 @@ export { useReFetch, useRevalidating, useSuccess, - useDebounceFetch + useDebounceFetch, + createActionsHook } from './others' diff --git a/src/hooks/others.ts b/src/hooks/others.ts index 63594e0..f182a02 100644 --- a/src/hooks/others.ts +++ b/src/hooks/others.ts @@ -636,3 +636,41 @@ export function useImperative() { return imperativeFetch } + +export const createActionsHook = (cfg?: FetchInit) => + function useServerAction( + actionName: keyof Acts, + otherConfig?: FetchInit + ) { + type K = keyof Acts + const [args, setArgs] = React.useState() + + const { reFetch, ...other } = useFetch('/[action]', { + baseUrl: '/api/actions', + method: 'POST', + id: { + __ACTION_EXECUTION__: actionName + }, + params: { + action: actionName + }, + body: args?.args || {}, + query: args?.search || {}, + auto: false, + ...cfg, + ...otherConfig + }) + + return { + ...other, + execute(params: Acts[K], searchParams?: any) { + setArgs({ + args: params, + search: searchParams + }) + setTimeout(() => { + reFetch() + }, 0) + } + } + } diff --git a/src/index.ts b/src/index.ts index 4bcc290..7453add 100644 --- a/src/index.ts +++ b/src/index.ts @@ -47,7 +47,8 @@ export { useReFetch, useRevalidating, useSuccess, - useDebounceFetch + useDebounceFetch, + createActionsHook } from './hooks' export { FetchConfig, SSRSuspense } from './components/server' @@ -72,3 +73,5 @@ export { serialize, notNull } from './utils/shared' + +export { createActionHandler } from './server' diff --git a/src/server/index.ts b/src/server/index.ts new file mode 100644 index 0000000..014e27f --- /dev/null +++ b/src/server/index.ts @@ -0,0 +1,21 @@ +export function createActionHandler(actions: { + [e in keyof ActionTypes]: ( + req: Request, + args: ActionTypes[e], + searchParams: URLSearchParams + ) => any +}) { + return async ( + req: Request, + params: { + params: { + action: keyof ActionTypes + } + } + ) => + actions[params.params.action]( + req, + await req.json(), + new URL(req.url).searchParams + ) +}