Skip to content

Commit

Permalink
fix(cache): throw an error when assert while getting the value
Browse files Browse the repository at this point in the history
  • Loading branch information
smalluban committed Aug 21, 2024
1 parent 60fe84d commit 9cc25c0
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 7 deletions.
8 changes: 7 additions & 1 deletion src/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,13 @@ export function get(target, key, fn) {
return entry.value;
}

export function assert(target, key, value) {
export function assert(target, key, value, force) {
if (context && !force) {
throw Error(
`Try to assert value of the '${key}' inside of the value function`,
);
}

const entry = getEntry(target, key);

entry.value = undefined;
Expand Down
17 changes: 11 additions & 6 deletions src/store.js
Original file line number Diff line number Diff line change
Expand Up @@ -318,11 +318,16 @@ function getTypeConstructor(type, key) {
function setModelState(model, state, value) {
const lastConfig = cache.getEntry(model, "state").value;

cache.assert(model, "state", {
state,
value,
error: (state === "error" ? value : lastConfig?.error) || false,
});
cache.assert(
model,
"state",
{
state,
value,
error: (state === "error" ? value : lastConfig?.error) || false,
},
true,
);

return model;
}
Expand Down Expand Up @@ -1622,7 +1627,7 @@ function resolveModel(Model, config, id) {
const clone = Object.freeze(Object.create(lastModel));

definitions.set(clone, config);
cache.assert(clone, "state", getModelState(nextModel));
cache.assert(clone, "state", getModelState(nextModel), true);

return clone;
}
Expand Down
8 changes: 8 additions & 0 deletions test/spec/cache.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,14 @@ describe("cache:", () => {
).toThrow();
});

it("throws for assert value inside of the getter call", () => {
expect(() =>
get(target, "key", () => {
assert(target, "key", "value");
}),
).toThrow();
});

it("re-throws getter error with cleanup", () => {
expect(() =>
get(target, "key", () =>
Expand Down

0 comments on commit 9cc25c0

Please sign in to comment.