chore: refactor runWithoutActiveAccount to handle promises

This commit is contained in:
Matteo Manchi
2025-08-21 17:51:48 +02:00
parent bb9d837236
commit 65332631d2
3 changed files with 31 additions and 18 deletions

View File

@@ -159,6 +159,8 @@ export function setActiveAccount(account: Account) {
*
* Takes care of restoring the active account after the callback is run.
*
* If the callback returns a promise, waits for it before restoring the active account.
*
* @param callback - The callback to run.
* @returns The result of the callback.
*/
@@ -168,6 +170,14 @@ export function runWithoutActiveAccount<Result>(
const me = Account.getMe();
activeAccountContext.set(null);
const result = callback();
if (result instanceof Promise) {
return result.finally(() => {
activeAccountContext.set(me);
return result;
}) as Result;
}
activeAccountContext.set(me);
return result;
}

View File

@@ -7,7 +7,11 @@ import {
co,
coValueClassFromCoValueClassOrSchema,
} from "../internal.js";
import { createJazzTestAccount, setupJazzTestSync } from "../testing.js";
import {
createJazzTestAccount,
runWithoutActiveAccount,
setupJazzTestSync,
} from "../testing.js";
import { waitFor } from "./utils.js";
const Crypto = await WasmCrypto.create();
@@ -909,16 +913,16 @@ describe("CoList unique methods", () => {
test("upsertUnique without an active account", async () => {
const account = activeAccountContext.get();
activeAccountContext.set(null);
const ItemList = co.list(z.string());
const sourceData = ["item1", "item2", "item3"];
const result = await ItemList.upsertUnique({
value: sourceData,
unique: "new-list",
owner: account,
const result = await runWithoutActiveAccount(() => {
return ItemList.upsertUnique({
value: sourceData,
unique: "new-list",
owner: account,
});
});
expect(result).not.toBeNull();

View File

@@ -1551,8 +1551,6 @@ describe("Creating and finding unique CoMaps", async () => {
test("upserting without an active account", async () => {
const account = activeAccountContext.get();
activeAccountContext.set(null);
// Schema
const Event = co.map({
title: z.string(),
@@ -1567,15 +1565,16 @@ describe("Creating and finding unique CoMaps", async () => {
_id: "test-event-external-id",
};
// Upserting
const activeEvent = await Event.upsertUnique({
value: {
title: sourceData.title,
identifier: sourceData.identifier,
external_id: sourceData._id,
},
unique: sourceData.identifier,
owner: account,
const activeEvent = await runWithoutActiveAccount(() => {
return Event.upsertUnique({
value: {
title: sourceData.title,
identifier: sourceData.identifier,
external_id: sourceData._id,
},
unique: sourceData.identifier,
owner: account,
});
});
expect(activeEvent).toEqual({