Skip to content

Commit

Permalink
fix(mdw): thunk loader needs ctx.loader
Browse files Browse the repository at this point in the history
  • Loading branch information
neurosnap committed Apr 15, 2024
1 parent 70f24ec commit f47ecce
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 5 deletions.
11 changes: 11 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
fmt:
deno fmt
.PHONY:

lint:
deno lint
.PHONY: lint

test:
deno test --allow-env --allow-read
.PHONY: test
26 changes: 21 additions & 5 deletions mdw/store.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ApiCtx, ThunkCtx } from "../query/mod.ts";
import type { ApiCtx, ThunkCtxWLoader } from "../query/mod.ts";
import { compose } from "../compose.ts";
import type { AnyState, Next } from "../types.ts";
import {
Expand Down Expand Up @@ -75,28 +75,41 @@ export function loader<M extends AnyState = AnyState>(schema: {
loaders: LoaderOutput<M, AnyState>;
}) {
return function* <
Ctx extends ThunkCtx = ThunkCtx,
Ctx extends ThunkCtxWLoader = ThunkCtxWLoader,
>(ctx: Ctx, next: Next) {
yield* updateStore([
schema.loaders.start({ id: ctx.name }),
schema.loaders.start({ id: ctx.key }),
]);

if (!ctx.loader) ctx.loader = {} as any;

try {
yield* next();

if (!ctx.loader) {
ctx.loader = {};
}

yield* updateStore([
schema.loaders.success({ id: ctx.name }),
schema.loaders.success({ id: ctx.key }),
schema.loaders.success({ id: ctx.name, ...ctx.loader }),
schema.loaders.success({ id: ctx.key, ...ctx.loader }),
]);
} catch (err) {
if (!ctx.loader) {
ctx.loader = {};
}

yield* updateStore([
schema.loaders.error({
id: ctx.name,
message: err.message,
...ctx.loader,
}),
schema.loaders.error({
id: ctx.key,
message: err.message,
...ctx.loader,
}),
]);
} finally {
Expand All @@ -106,7 +119,10 @@ export function loader<M extends AnyState = AnyState>(schema: {
const ids = loaders
.filter((loader) => loader.status === "loading")
.map((loader) => loader.id);
yield* updateStore(schema.loaders.resetByIds(ids));

if (ids.length > 0) {
yield* updateStore(schema.loaders.resetByIds(ids));
}
}
};
}
Expand Down
4 changes: 4 additions & 0 deletions query/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ export interface ThunkCtx<P = any> extends Payload<P> {
result: Result<void>;
}

export interface ThunkCtxWLoader extends ThunkCtx {
loader: Omit<LoaderPayload<any>, "id"> | null;
}

export interface LoaderCtx<P = unknown> extends ThunkCtx<P> {
loader: Partial<LoaderItemState> | null;
}
Expand Down

0 comments on commit f47ecce

Please sign in to comment.