Skip to content

Commit

Permalink
refactor: implement query preflight to use simple atom when possible
Browse files Browse the repository at this point in the history
  • Loading branch information
tien committed Jun 12, 2024
1 parent 76f0187 commit 1243b00
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 12 deletions.
2 changes: 1 addition & 1 deletion packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ export {
type QueryInstruction,
} from "./QueryBuilder.js";
export * from "./errors.js";
export { default as query } from "./query.js";
export { preflight, default as query } from "./query.js";
export * from "./symbols.js";
23 changes: 23 additions & 0 deletions packages/core/src/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,29 @@ import type {
import type { ReDotDescriptor } from "@reactive-dot/types";
import type { ChainDefinition, TypedApi } from "polkadot-api";

export const preflight = <TInstruction extends QueryInstruction>(
instruction: TInstruction,
) => {
type Return = TInstruction["instruction"] extends "fetch-constant"
? "promise"
: TInstruction["instruction"] extends "call-api"
? "promise"
: TInstruction["instruction"] extends "read-storage-entries"
? "promise"
: TInstruction["instruction"] extends "read-storage"
? "observable"
: "promise" | "observable";

switch (instruction.instruction) {
case "fetch-constant":
case "call-api":
case "read-storage-entries":
return "promise" as Return;
case "read-storage":
return "observable" as Return;
}
};

const query = <
TInstruction extends QueryInstruction,
TDescriptor extends ChainDefinition = ReDotDescriptor,
Expand Down
30 changes: 19 additions & 11 deletions packages/react/src/stores/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {
MultiInstruction,
QueryError,
QueryInstruction,
preflight,
query,
} from "@reactive-dot/core";
import type { ChainId } from "@reactive-dot/types";
Expand All @@ -20,17 +21,24 @@ const _queryAtomFamily = atomFamily(
// eslint-disable-next-line @typescript-eslint/ban-types
{}>
>;
}) =>
atomWithObservable((get) =>
from(get(typedApiAtomFamily(param.chainId))).pipe(
switchMap(
(api) =>
query(api, param.instruction) as
| Promise<unknown>
| Observable<unknown>,
),
),
),
}) => {
switch (preflight(param.instruction)) {
case "promise":
return atom(async (get, { signal }) => {
const api = await get(typedApiAtomFamily(param.chainId));

return query(api, param.instruction, { signal }) as Promise<unknown>;
});
case "observable":
return atomWithObservable((get) =>
from(get(typedApiAtomFamily(param.chainId))).pipe(
switchMap(
(api) => query(api, param.instruction) as Observable<unknown>,
),
),
);
}
},
(a, b) => stringify(a) === stringify(b),
);

Expand Down

0 comments on commit 1243b00

Please sign in to comment.