@zenflux/react-commander 0.0.1-dev
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/package.json +61 -0
- package/readme.md +1422 -0
- package/src/_internal/constants.ts +18 -0
- package/src/_internal/core.ts +208 -0
- package/src/_internal/definitions.ts +47 -0
- package/src/command-base.ts +106 -0
- package/src/commands-context.ts +20 -0
- package/src/commands-manager.ts +357 -0
- package/src/commands-provider.tsx +37 -0
- package/src/definitions.ts +165 -0
- package/src/hooks/index.ts +10 -0
- package/src/hooks/use-child-command/use-child-command-hook.ts +44 -0
- package/src/hooks/use-child-command/use-child-command-runner.ts +32 -0
- package/src/hooks/use-command/use-command-hook.ts +23 -0
- package/src/hooks/use-command/use-command-runner.ts +16 -0
- package/src/hooks/use-command/use-command-state.ts +132 -0
- package/src/hooks/use-command/use-command.ts +260 -0
- package/src/hooks/use-component/use-component-with-ref.ts +30 -0
- package/src/hooks/use-component/use-component.ts +56 -0
- package/src/hooks/utils.ts +90 -0
- package/src/index.ts +9 -0
- package/src/query/query-auto-save-manager.ts +54 -0
- package/src/query/query-cache.ts +91 -0
- package/src/query/query-client.tsx +67 -0
- package/src/query/query-component.tsx +101 -0
- package/src/query/query-definitions.ts +32 -0
- package/src/query/query-list-diff.ts +8 -0
- package/src/query/query-list-module-base.ts +20 -0
- package/src/query/query-module-base.ts +200 -0
- package/src/query/query-provider.tsx +47 -0
- package/src/query/query-router.ts +85 -0
- package/src/query/query-utils.ts +30 -0
- package/src/with-commands.tsx +363 -0
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
export type QueryCacheKey = readonly unknown[];
|
|
2
|
+
|
|
3
|
+
export type QueryCache = {
|
|
4
|
+
fetchQuery<T>( options: { queryKey: QueryCacheKey; queryFn: () => Promise<T> } ): Promise<T>;
|
|
5
|
+
prefetchQuery<T>( options: { queryKey: QueryCacheKey; queryFn: () => Promise<T> } ): Promise<void>;
|
|
6
|
+
getQueryData<T>( queryKey: QueryCacheKey ): T | undefined;
|
|
7
|
+
invalidateQueries( options: { queryKey: QueryCacheKey } ): Promise<void>;
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
function serializeKey( key: QueryCacheKey ): string {
|
|
11
|
+
return JSON.stringify( key );
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function keyStartsWith( key: string, prefix: string ): boolean {
|
|
15
|
+
// Both are JSON arrays; startsWith by string is safe here because we keep exact shapes
|
|
16
|
+
return key.startsWith( prefix.slice( 0, -1 ) );
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function queryCreateMemoryCache(): QueryCache {
|
|
20
|
+
const data = new Map<string, unknown>();
|
|
21
|
+
const inFlight = new Map<string, Promise<unknown>>();
|
|
22
|
+
|
|
23
|
+
const get = <T>( key: QueryCacheKey ): T | undefined => {
|
|
24
|
+
return data.get( serializeKey( key ) ) as T | undefined;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
const set = ( key: QueryCacheKey, value: unknown ) => {
|
|
28
|
+
data.set( serializeKey( key ), value );
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const fetchQuery = async <T>( options: { queryKey: QueryCacheKey; queryFn: () => Promise<T> } ): Promise<T> => {
|
|
32
|
+
const serialized = serializeKey( options.queryKey );
|
|
33
|
+
const cached = get<T>( options.queryKey );
|
|
34
|
+
if ( cached !== undefined ) return cached;
|
|
35
|
+
|
|
36
|
+
const existing = inFlight.get( serialized );
|
|
37
|
+
if ( existing ) return existing as Promise<T>;
|
|
38
|
+
|
|
39
|
+
const promise = options.queryFn().then( value => {
|
|
40
|
+
set( options.queryKey, value );
|
|
41
|
+
inFlight.delete( serialized );
|
|
42
|
+
return value;
|
|
43
|
+
} ).catch( error => {
|
|
44
|
+
inFlight.delete( serialized );
|
|
45
|
+
throw error;
|
|
46
|
+
} );
|
|
47
|
+
|
|
48
|
+
inFlight.set( serialized, promise );
|
|
49
|
+
return promise;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
const prefetchQuery = async <T>( options: { queryKey: QueryCacheKey; queryFn: () => Promise<T> } ): Promise<void> => {
|
|
53
|
+
const serialized = serializeKey( options.queryKey );
|
|
54
|
+
const cached = get<T>( options.queryKey );
|
|
55
|
+
if ( cached !== undefined ) return;
|
|
56
|
+
|
|
57
|
+
const existing = inFlight.get( serialized );
|
|
58
|
+
if ( existing ) {
|
|
59
|
+
await existing;
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const promise = options.queryFn().then( value => {
|
|
64
|
+
set( options.queryKey, value );
|
|
65
|
+
inFlight.delete( serialized );
|
|
66
|
+
return value;
|
|
67
|
+
} ).catch( error => {
|
|
68
|
+
inFlight.delete( serialized );
|
|
69
|
+
throw error;
|
|
70
|
+
} );
|
|
71
|
+
|
|
72
|
+
inFlight.set( serialized, promise );
|
|
73
|
+
await promise;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
const getQueryData = <T>( queryKey: QueryCacheKey ): T | undefined => {
|
|
77
|
+
return get<T>( queryKey );
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const invalidateQueries = async ( options: { queryKey: QueryCacheKey } ): Promise<void> => {
|
|
81
|
+
const prefix = serializeKey( options.queryKey );
|
|
82
|
+
for ( const key of Array.from( data.keys() ) ) {
|
|
83
|
+
if ( keyStartsWith( key, prefix ) ) {
|
|
84
|
+
data.delete( key );
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
|
|
89
|
+
return { fetchQuery, prefetchQuery, getQueryData, invalidateQueries };
|
|
90
|
+
}
|
|
91
|
+
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { QueryComponent } from "@zenflux/react-commander/query/component";
|
|
2
|
+
|
|
3
|
+
import { queryCreateMemoryCache } from "@zenflux/react-commander/query/cache";
|
|
4
|
+
|
|
5
|
+
import type { DQueryModuleBaseStatic } from "@zenflux/react-commander/query/definitions";
|
|
6
|
+
|
|
7
|
+
import type { QueryModuleBase } from "@zenflux/react-commander/query/module-base";
|
|
8
|
+
|
|
9
|
+
import type { QueryCache } from "@zenflux/react-commander/query/cache";
|
|
10
|
+
|
|
11
|
+
export class QueryClient {
|
|
12
|
+
private modules: Record<string, QueryModuleBase<object>> = {};
|
|
13
|
+
|
|
14
|
+
private readonly cacheRef: QueryCache;
|
|
15
|
+
|
|
16
|
+
public constructor( private baseURL: string, cache?: QueryCache ) {
|
|
17
|
+
QueryComponent.setClient( this );
|
|
18
|
+
this.cacheRef = cache ?? queryCreateMemoryCache();
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
public fetch( method: string, route: string, args: Record<string, unknown>, handler: ( response: Response ) => Promise<unknown> ) {
|
|
22
|
+
const url = new URL( `${ this.baseURL }/${ route }` );
|
|
23
|
+
|
|
24
|
+
for ( const key in args ) {
|
|
25
|
+
url.pathname = url.pathname.replace( `:${ key }`, String( args[ key ] ) );
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const promise = globalThis.fetch( url.toString(), {
|
|
29
|
+
method,
|
|
30
|
+
headers: {
|
|
31
|
+
"Content-Type": "application/json",
|
|
32
|
+
},
|
|
33
|
+
body: method === "GET" ? undefined : JSON.stringify( args ),
|
|
34
|
+
} );
|
|
35
|
+
|
|
36
|
+
return promise.then( handler );
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
public getModule<TResource extends object = object>( module: DQueryModuleBaseStatic<TResource> ): QueryModuleBase<TResource> {
|
|
40
|
+
const moduleName = module.getName();
|
|
41
|
+
|
|
42
|
+
if ( ! this.modules[ moduleName ] ) {
|
|
43
|
+
throw new Error( `Query module ${ moduleName } not registered` );
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return this.modules[ moduleName ] as unknown as QueryModuleBase<TResource>;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
public registerModule<TResource extends object = object>( module: DQueryModuleBaseStatic<TResource> ) {
|
|
50
|
+
|
|
51
|
+
const moduleName = module.getName();
|
|
52
|
+
|
|
53
|
+
if ( this.modules[ moduleName ] ) {
|
|
54
|
+
throw new Error( `Query module ${ moduleName } already registered` );
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
this.modules[ moduleName ] = new module( this ) as unknown as QueryModuleBase<object>;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
public get Component() {
|
|
61
|
+
return QueryComponent;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
public get cache() {
|
|
65
|
+
return this.cacheRef;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
INTERNAL_ON_LOAD,
|
|
5
|
+
INTERNAL_ON_MOUNT,
|
|
6
|
+
INTERNAL_ON_UNMOUNT,
|
|
7
|
+
INTERNAL_ON_UPDATE,
|
|
8
|
+
INTERNAL_ON_CONTEXT_STATE_UPDATED,
|
|
9
|
+
INTERNAL_PROPS
|
|
10
|
+
} from "../_internal/constants.js";
|
|
11
|
+
|
|
12
|
+
import { wrapPromiseSuspendable } from "@zenflux/react-commander/query/utils";
|
|
13
|
+
|
|
14
|
+
import type { QueryClient } from "@zenflux/react-commander/query/client";
|
|
15
|
+
|
|
16
|
+
import type { QueryModuleBase } from "@zenflux/react-commander/query/module-base";
|
|
17
|
+
import type { DQueryComponentProps } from "@zenflux/react-commander/query/definitions";
|
|
18
|
+
|
|
19
|
+
export class QueryComponent<
|
|
20
|
+
TData = Record<string, unknown>,
|
|
21
|
+
TProps = Record<string, unknown>,
|
|
22
|
+
TResource extends object = object,
|
|
23
|
+
TState = React.ComponentState
|
|
24
|
+
> extends React.PureComponent<DQueryComponentProps<TData, TProps, TResource, TState>> {
|
|
25
|
+
private static client: QueryClient;
|
|
26
|
+
|
|
27
|
+
private readonly client: QueryClient;
|
|
28
|
+
|
|
29
|
+
private readonly queryModule: QueryModuleBase<TResource>;
|
|
30
|
+
|
|
31
|
+
public static setClient( query: QueryClient ) {
|
|
32
|
+
this.client = query;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
public constructor( props: DQueryComponentProps<TData, TProps, TResource> ) {
|
|
36
|
+
super( props );
|
|
37
|
+
|
|
38
|
+
this.client = ( this.constructor as typeof QueryComponent ).client;
|
|
39
|
+
|
|
40
|
+
if ( ! this.props.module ) {
|
|
41
|
+
throw new Error( "Parent <Query.Component> should have 'module' prop" );
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
this.queryModule = this.client.getModule<TResource>( this.props.module );
|
|
45
|
+
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
public render() {
|
|
49
|
+
// The resource will start loading
|
|
50
|
+
const resource = wrapPromiseSuspendable( ( async () => {
|
|
51
|
+
const data = await this.queryModule.getData<TData, TProps & { $data: TData }, TState>( this.props.component, this.props.props as Record<string, unknown> );
|
|
52
|
+
|
|
53
|
+
return {
|
|
54
|
+
element: React.createElement( this.props.component, this.props.props as TProps & { $data: TData /* TODO remove */ } ),
|
|
55
|
+
data,
|
|
56
|
+
};
|
|
57
|
+
} )() );
|
|
58
|
+
|
|
59
|
+
// The API Wrapper Component
|
|
60
|
+
const Component = () => {
|
|
61
|
+
const response = resource.read();
|
|
62
|
+
|
|
63
|
+
const internalProps = {
|
|
64
|
+
... response.element.props,
|
|
65
|
+
|
|
66
|
+
// Hooking lifecycle methods
|
|
67
|
+
[ INTERNAL_PROPS ]: {
|
|
68
|
+
handlers: {
|
|
69
|
+
[ INTERNAL_ON_LOAD ]: ( context: any ) => this.queryModule.onLoadInternal( context ),
|
|
70
|
+
[ INTERNAL_ON_MOUNT ]: ( context: any ) => this.queryModule.onMountInternal( context, response.data ),
|
|
71
|
+
[ INTERNAL_ON_UNMOUNT ]: ( context: any ) => this.queryModule.onUnmountInternal( context, response.data ),
|
|
72
|
+
[ INTERNAL_ON_UPDATE ]: ( context: any, state: any ) => this.queryModule.onUpdateInternal( context, state ),
|
|
73
|
+
[ INTERNAL_ON_CONTEXT_STATE_UPDATED ]: ( context: any, hasChanged: boolean ) =>
|
|
74
|
+
this.queryModule.onContextStateUpdatedInternal( context, hasChanged ),
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
const mount = () => {
|
|
80
|
+
return (
|
|
81
|
+
<response.element.type { ... internalProps }>
|
|
82
|
+
{ /* { data.children.map( ( child: React.ReactElement, index: number ) => (
|
|
83
|
+
<child.type key={ index } { ... child.props }>
|
|
84
|
+
{ child.props.children }
|
|
85
|
+
</child.type>
|
|
86
|
+
) ) } */ }
|
|
87
|
+
</response.element.type>
|
|
88
|
+
);
|
|
89
|
+
};
|
|
90
|
+
|
|
91
|
+
return mount();
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
return (
|
|
95
|
+
<React.Suspense fallback={ this.props.fallback ?? undefined }>
|
|
96
|
+
<Component/>
|
|
97
|
+
</React.Suspense>
|
|
98
|
+
);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
;
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { DCommandFunctionComponent } from "@zenflux/react-commander/definitions";
|
|
2
|
+
|
|
3
|
+
import type React from "react";
|
|
4
|
+
|
|
5
|
+
import type { QueryClient } from "@zenflux/react-commander/query/client";
|
|
6
|
+
|
|
7
|
+
import type { QueryModuleBase } from "@zenflux/react-commander/query/module-base";
|
|
8
|
+
|
|
9
|
+
export interface DQueryModuleBaseStatic<TResource extends object = object> {
|
|
10
|
+
new( query: QueryClient ): QueryModuleBase<TResource>;
|
|
11
|
+
|
|
12
|
+
getName(): string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface DQueryComponentProps<TData = Record<string, unknown>, TProps = Record<string, unknown>, TResource extends object = object, TState = React.ComponentState> {
|
|
16
|
+
children?: React.ReactElement;
|
|
17
|
+
module?: DQueryModuleBaseStatic<TResource>;
|
|
18
|
+
fallback?: React.ReactElement;
|
|
19
|
+
component: DCommandFunctionComponent<TProps & { $data: TData }, TState>;
|
|
20
|
+
props?: TProps;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface DQueryReadOnlyContext {
|
|
24
|
+
componentName: string;
|
|
25
|
+
props: Readonly<Record<string, unknown>>;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface DQueryEndpointConfig<TApiResponse, TData> {
|
|
29
|
+
method: string;
|
|
30
|
+
path: string;
|
|
31
|
+
prepareData?: ( apiResponse: TApiResponse ) => TData;
|
|
32
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export function queryDiffById<T>( prev: T[], curr: T[], getId: ( t: T ) => string ) {
|
|
2
|
+
const prevIds = new Set( prev.map( getId ) );
|
|
3
|
+
const currIds = new Set( curr.map( getId ) );
|
|
4
|
+
const added = curr.filter( i => ! prevIds.has( getId( i ) ) );
|
|
5
|
+
const removed = prev.filter( i => ! currIds.has( getId( i ) ) );
|
|
6
|
+
return { added, removed };
|
|
7
|
+
}
|
|
8
|
+
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { QueryModuleBase } from "@zenflux/react-commander/query/module-base";
|
|
2
|
+
import { QueryRouterBase } from "@zenflux/react-commander/query/router";
|
|
3
|
+
|
|
4
|
+
import type { QueryClient } from "@zenflux/react-commander/query/client";
|
|
5
|
+
|
|
6
|
+
class SimpleItemRouter<TEntity extends object> extends QueryRouterBase<TEntity, QueryModuleBase<TEntity[]>> {
|
|
7
|
+
public constructor( api: QueryClient, resource: string, model: QueryModuleBase<TEntity[]> ) {
|
|
8
|
+
super( api, resource, model );
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export abstract class QueryListModuleBase<TEntity extends object> extends QueryModuleBase<TEntity[]> {
|
|
13
|
+
protected readonly itemRouter: QueryRouterBase<TEntity, QueryModuleBase<TEntity[]>>;
|
|
14
|
+
|
|
15
|
+
protected constructor( api: QueryClient ) {
|
|
16
|
+
super( api );
|
|
17
|
+
this.itemRouter = new SimpleItemRouter<TEntity>( api, this.getResourceName(), this );
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { QueryRouterBase } from "@zenflux/react-commander/query/router";
|
|
2
|
+
|
|
3
|
+
import type { DCommandFunctionComponent } from "@zenflux/react-commander/definitions";
|
|
4
|
+
import type { QueryClient } from "@zenflux/react-commander/query/client";
|
|
5
|
+
import type { DQueryReadOnlyContext, DQueryEndpointConfig } from "@zenflux/react-commander/query/definitions";
|
|
6
|
+
|
|
7
|
+
interface Route<TApiResponse, TData> {
|
|
8
|
+
path: string;
|
|
9
|
+
handlers: {
|
|
10
|
+
requestHandler?: ( element: DCommandFunctionComponent<Record<string, unknown>, React.ComponentState>, request: Record<string, unknown> ) => Promise<Record<string, unknown>>;
|
|
11
|
+
responseHandler?: ( element: DCommandFunctionComponent<Record<string, unknown>, React.ComponentState>, response: Response ) => Promise<TApiResponse>;
|
|
12
|
+
prepareData?: ( apiResponse: TApiResponse ) => TData;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
class SimpleQueryRouter<TResource extends object> extends QueryRouterBase<TResource, QueryModuleBase<TResource>> {
|
|
17
|
+
public constructor( api: QueryClient, resource: string, model: QueryModuleBase<TResource> ) {
|
|
18
|
+
super( api, resource, model );
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export abstract class QueryModuleBase<TResource extends object = object> {
|
|
23
|
+
|
|
24
|
+
protected api: QueryClient;
|
|
25
|
+
protected router: QueryRouterBase<TResource, QueryModuleBase<TResource>>;
|
|
26
|
+
|
|
27
|
+
private routes: Map<RequestInit[ "method" ], Map<Route<unknown, unknown>[ "path" ], Route<unknown, unknown>>> = new Map();
|
|
28
|
+
|
|
29
|
+
public static getName(): string {
|
|
30
|
+
throw new Error( "Please extend QueryModuleBase and implement static getName()" );
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
public constructor( api: QueryClient ) {
|
|
34
|
+
this.api = api;
|
|
35
|
+
this.router = new SimpleQueryRouter<TResource>( api, this.getResourceName(), this );
|
|
36
|
+
|
|
37
|
+
this.registerEndpoints();
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
protected abstract getResourceName(): string;
|
|
41
|
+
|
|
42
|
+
protected abstract registerEndpoints(): void;
|
|
43
|
+
|
|
44
|
+
public onLoadInternal( context: DQueryReadOnlyContext ) {
|
|
45
|
+
this.load?.( context );
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
public onUnmountInternal( context: DQueryReadOnlyContext, resource: TResource ) {
|
|
49
|
+
this.onUnmount?.( context, resource );
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
public onMountInternal( context: DQueryReadOnlyContext, resource: TResource ) {
|
|
53
|
+
this.onMount?.( context, resource );
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
public onUpdateInternal( context: DQueryReadOnlyContext, state: {
|
|
57
|
+
currentProps: Readonly<Record<string, unknown>>;
|
|
58
|
+
currentState: Readonly<Record<string, unknown>>;
|
|
59
|
+
prevProps: Readonly<Record<string, unknown>>;
|
|
60
|
+
prevState: Readonly<Record<string, unknown>>;
|
|
61
|
+
snapshot: unknown;
|
|
62
|
+
} ) {
|
|
63
|
+
this.onUpdate?.( context, state );
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
public onContextStateUpdatedInternal( context: DQueryReadOnlyContext, hasChanged: boolean ) {
|
|
67
|
+
this.onContextStateUpdated?.( context, hasChanged );
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
public async getData<TData, TProps = Record<string, unknown>, TState = React.ComponentState>( element: DCommandFunctionComponent<TProps, TState>, args?: Record<string, unknown> ): Promise<TData> {
|
|
71
|
+
const componentName = element.getName!();
|
|
72
|
+
|
|
73
|
+
const route = this.routes.get( "GET" )?.get( componentName ) as Route<unknown, TData> | undefined;
|
|
74
|
+
|
|
75
|
+
if ( ! route ) {
|
|
76
|
+
throw new Error( `Cannot find route for ${ componentName }` );
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const request = await route.handlers.requestHandler!( element as DCommandFunctionComponent<Record<string, unknown>, React.ComponentState>, args || {} );
|
|
80
|
+
|
|
81
|
+
const queryKey = [ this.getResourceName(), "getData", componentName, JSON.stringify( request ) ] as const;
|
|
82
|
+
|
|
83
|
+
const apiResponse = await this.api.cache.fetchQuery( {
|
|
84
|
+
queryKey,
|
|
85
|
+
queryFn: () => this.api.fetch( "GET", route.path, request, ( response ) => {
|
|
86
|
+
return route.handlers.responseHandler!( element as DCommandFunctionComponent<Record<string, unknown>, React.ComponentState>, response );
|
|
87
|
+
} )
|
|
88
|
+
} );
|
|
89
|
+
|
|
90
|
+
if ( route.handlers.prepareData ) {
|
|
91
|
+
return route.handlers.prepareData( apiResponse );
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return apiResponse as TData;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
protected register( method: string, name: string, route: Route<unknown, unknown> | string ): void {
|
|
98
|
+
if ( ! this.routes.has( method ) ) {
|
|
99
|
+
this.routes.set( method, new Map() );
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
if ( typeof route === "string" ) {
|
|
103
|
+
route = { path: route, handlers: {} };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
if ( ! route.handlers.requestHandler ) {
|
|
107
|
+
route.handlers.requestHandler = this.requestHandler.bind( this );
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if ( ! route.handlers.responseHandler ) {
|
|
111
|
+
route.handlers.responseHandler = this.responseHandler.bind( this );
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
this.routes.get( method )!.set( name, route );
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
public async request<TResult = unknown>( name: string, args?: Record<string, unknown> ): Promise<TResult> {
|
|
118
|
+
let found: { method: string; route: Route<unknown, unknown> } | null = null;
|
|
119
|
+
|
|
120
|
+
for ( const [ method, map ] of this.routes ) {
|
|
121
|
+
if ( typeof method !== "string" ) continue;
|
|
122
|
+
const route = map.get( name );
|
|
123
|
+
if ( route ) {
|
|
124
|
+
found = { method, route };
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
if ( ! found ) {
|
|
130
|
+
throw new Error( `Cannot find route for ${ name }` );
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const payload = args ?? {};
|
|
134
|
+
|
|
135
|
+
const result = await this.api.fetch( found.method!, found.route.path, payload, async ( response ) => {
|
|
136
|
+
if ( found!.route.handlers.responseHandler ) {
|
|
137
|
+
return await ( found!.route.handlers.responseHandler as ( e: DCommandFunctionComponent<Record<string, unknown>, React.ComponentState>, r: Response ) => Promise<unknown> )( undefined as unknown as DCommandFunctionComponent<Record<string, unknown>, React.ComponentState>, response );
|
|
138
|
+
}
|
|
139
|
+
return await response.json();
|
|
140
|
+
} );
|
|
141
|
+
|
|
142
|
+
return result as TResult;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
protected defineEndpoint<TApiResponse, TData>(
|
|
146
|
+
name: string,
|
|
147
|
+
config: DQueryEndpointConfig<TApiResponse, TData>
|
|
148
|
+
): void {
|
|
149
|
+
const route: Route<TApiResponse, TData> = {
|
|
150
|
+
path: config.path,
|
|
151
|
+
handlers: {
|
|
152
|
+
requestHandler: this.requestHandler.bind( this ),
|
|
153
|
+
responseHandler: this.responseHandler.bind( this ) as ( element: DCommandFunctionComponent<Record<string, unknown>, React.ComponentState>, response: Response ) => Promise<TApiResponse>,
|
|
154
|
+
prepareData: config.prepareData,
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
|
|
158
|
+
this.register( config.method, name, route as Route<unknown, unknown> );
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
protected abstract responseHandler( element: DCommandFunctionComponent<Record<string, unknown>, React.ComponentState>, response: Response ): Promise<unknown>;
|
|
162
|
+
|
|
163
|
+
protected abstract requestHandler( element: DCommandFunctionComponent<Record<string, unknown>, React.ComponentState>, request: Record<string, unknown> ): Promise<Record<string, unknown>>;
|
|
164
|
+
|
|
165
|
+
protected load?( context: DQueryReadOnlyContext ): void;
|
|
166
|
+
|
|
167
|
+
protected onMount?( context: DQueryReadOnlyContext, resource?: TResource ): void;
|
|
168
|
+
|
|
169
|
+
protected onUnmount?( context: DQueryReadOnlyContext, resource?: TResource ): void;
|
|
170
|
+
|
|
171
|
+
protected onUpdate?( context: DQueryReadOnlyContext, state: {
|
|
172
|
+
currentProps: Readonly<Record<string, unknown>>;
|
|
173
|
+
currentState: Readonly<Record<string, unknown>>;
|
|
174
|
+
prevProps: Readonly<Record<string, unknown>>;
|
|
175
|
+
prevState: Readonly<Record<string, unknown>>;
|
|
176
|
+
snapshot: unknown;
|
|
177
|
+
} ): void;
|
|
178
|
+
|
|
179
|
+
protected onContextStateUpdated?( context: DQueryReadOnlyContext, hasChanged: boolean ): void;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export abstract class QueryItemModuleBase<TEntity extends object> extends QueryModuleBase<TEntity> {
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export abstract class QueryListModuleBase<TEntity extends object> extends QueryModuleBase<TEntity[]> {
|
|
186
|
+
protected readonly itemRouter: QueryRouterBase<TEntity, QueryModuleBase<TEntity[]>>;
|
|
187
|
+
|
|
188
|
+
protected constructor( api: QueryClient ) {
|
|
189
|
+
super( api );
|
|
190
|
+
|
|
191
|
+
class SimpleItemRouter<TEntity2 extends object> extends QueryRouterBase<TEntity2, QueryModuleBase<TEntity2[]>> {
|
|
192
|
+
public constructor( api2: QueryClient, resource: string, model: QueryModuleBase<TEntity2[]> ) {
|
|
193
|
+
super( api2, resource, model );
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
this.itemRouter = new SimpleItemRouter<TEntity>( api, this.getResourceName(), this );
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import React from "react";
|
|
2
|
+
|
|
3
|
+
import type { QueryClient } from "@zenflux/react-commander/query/client";
|
|
4
|
+
import type { DQueryModuleBaseStatic } from "@zenflux/react-commander/query/definitions";
|
|
5
|
+
import type { QueryModuleBase } from "@zenflux/react-commander/query/module-base";
|
|
6
|
+
|
|
7
|
+
const QueryClientContext = React.createContext<QueryClient | null>( null );
|
|
8
|
+
|
|
9
|
+
let currentClient: QueryClient | null = null;
|
|
10
|
+
|
|
11
|
+
export function QueryProvider( props: { client: QueryClient; children: React.ReactNode } ) {
|
|
12
|
+
const { client, children } = props;
|
|
13
|
+
|
|
14
|
+
React.useEffect( () => {
|
|
15
|
+
currentClient = client;
|
|
16
|
+
return () => {
|
|
17
|
+
if ( currentClient === client ) currentClient = null;
|
|
18
|
+
};
|
|
19
|
+
}, [ client ] );
|
|
20
|
+
|
|
21
|
+
return (
|
|
22
|
+
<QueryClientContext.Provider value={ client }>
|
|
23
|
+
{ children }
|
|
24
|
+
</QueryClientContext.Provider>
|
|
25
|
+
);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function useQueryClient(): QueryClient {
|
|
29
|
+
const client = React.useContext( QueryClientContext );
|
|
30
|
+
if ( ! client ) {
|
|
31
|
+
throw new Error( "QueryClient is not available. Wrap your app with <QueryProvider client={...}>" );
|
|
32
|
+
}
|
|
33
|
+
return client;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function getQueryClient(): QueryClient {
|
|
37
|
+
if ( ! currentClient ) {
|
|
38
|
+
throw new Error( "No QueryClient set. Ensure <QueryProvider> is mounted." );
|
|
39
|
+
}
|
|
40
|
+
return currentClient;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function getQueryModule<TResource extends object>( module: DQueryModuleBaseStatic<TResource> ): QueryModuleBase<TResource> {
|
|
44
|
+
const client = getQueryClient();
|
|
45
|
+
return client.getModule<TResource>( module );
|
|
46
|
+
}
|
|
47
|
+
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import type { QueryClient } from "@zenflux/react-commander/query/client";
|
|
2
|
+
|
|
3
|
+
export interface QueryModel {
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
export abstract class QueryRouterBase<Resource, Model extends QueryModel = QueryModel> {
|
|
7
|
+
|
|
8
|
+
protected readonly api: QueryClient;
|
|
9
|
+
protected readonly resource: string;
|
|
10
|
+
protected readonly model: Model;
|
|
11
|
+
|
|
12
|
+
private listCache?: Promise<Resource[]>;
|
|
13
|
+
private itemCache: Map<string, Promise<Resource>> = new Map();
|
|
14
|
+
|
|
15
|
+
public constructor( api: QueryClient, resource: string, model: Model ) {
|
|
16
|
+
this.api = api;
|
|
17
|
+
this.resource = resource;
|
|
18
|
+
this.model = model;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
protected fetchList = async (): Promise<Resource[]> => {
|
|
22
|
+
return this.api.fetch( "GET", `v1/${ this.resource }`, {}, ( r ) => r.json() ) as Promise<Resource[]>;
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
protected fetchItem = async ( key: string ): Promise<Resource> => {
|
|
26
|
+
return this.api.fetch( "GET", `v1/${ this.resource }/:key`, { key }, ( r ) => r.json() ) as Promise<Resource>;
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
protected saveItem = async ( input: Resource & { key: string } ): Promise<void> => {
|
|
30
|
+
await this.api.fetch( "POST", `v1/${ this.resource }/:key`, input as unknown as Record<string, unknown>, ( r ) => r.json() );
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
protected deleteItem = async ( key: string ): Promise<void> => {
|
|
34
|
+
await this.api.fetch( "DELETE", `v1/${ this.resource }/${ key }`, {}, ( r ) => r.json() );
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
protected queryKeyList(): readonly unknown[] {
|
|
38
|
+
return [ this.resource, "list" ] as const;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
protected queryKeyItem( key: string ): readonly unknown[] {
|
|
42
|
+
return [ this.resource, "item", key ] as const;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
public async list(): Promise<Resource[]> {
|
|
46
|
+
return this.api.cache.fetchQuery( {
|
|
47
|
+
queryKey: this.queryKeyList(),
|
|
48
|
+
queryFn: this.fetchList,
|
|
49
|
+
} );
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
public async item( key: string ): Promise<Resource> {
|
|
53
|
+
return this.api.cache.fetchQuery( {
|
|
54
|
+
queryKey: this.queryKeyItem( key ),
|
|
55
|
+
queryFn: () => this.fetchItem( key ),
|
|
56
|
+
} );
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
public async save( input: Resource & { key: string } ): Promise<void> {
|
|
60
|
+
await this.saveItem( input );
|
|
61
|
+
await this.api.cache.invalidateQueries( { queryKey: [ this.resource ] } );
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
public async remove( key: string ): Promise<void> {
|
|
65
|
+
await this.deleteItem( key );
|
|
66
|
+
await this.api.cache.invalidateQueries( { queryKey: [ this.resource ] } );
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
protected invalidate( key?: string ) {
|
|
70
|
+
this.listCache = undefined;
|
|
71
|
+
if ( key ) this.itemCache.delete( key );
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
public async queryPrefetchItem( key: string ): Promise<void> {
|
|
75
|
+
await this.api.cache.prefetchQuery( {
|
|
76
|
+
queryKey: this.queryKeyItem( key ),
|
|
77
|
+
queryFn: () => this.fetchItem( key ),
|
|
78
|
+
} );
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
public queryGetCachedItem( key: string ): Resource | undefined {
|
|
82
|
+
return this.api.cache.getQueryData<Resource>( this.queryKeyItem( key ) ) as Resource | undefined;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export function wrapPromiseSuspendable( promise: Promise<any> ) {
|
|
2
|
+
let status = "pending";
|
|
3
|
+
let result: any;
|
|
4
|
+
let suspender = promise.then(
|
|
5
|
+
( r ) => {
|
|
6
|
+
status = "success";
|
|
7
|
+
result = r;
|
|
8
|
+
},
|
|
9
|
+
( e ) => {
|
|
10
|
+
status = "error";
|
|
11
|
+
result = e;
|
|
12
|
+
}
|
|
13
|
+
);
|
|
14
|
+
return {
|
|
15
|
+
read() {
|
|
16
|
+
if ( status === "pending" ) {
|
|
17
|
+
throw suspender;
|
|
18
|
+
} else if ( status === "error" ) {
|
|
19
|
+
throw result;
|
|
20
|
+
} else if ( status === "success" ) {
|
|
21
|
+
return result;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function fakeTimeout( ms: number ) {
|
|
28
|
+
return new Promise( ( resolve ) => setTimeout( resolve, ms ) );
|
|
29
|
+
}
|
|
30
|
+
|