wait for event refactor

This commit is contained in:
Jonathan Jogenfors
2024-02-29 23:04:56 +01:00
parent 967b30cfa5
commit 0f331a3b50
2 changed files with 22 additions and 20 deletions

View File

@@ -84,10 +84,7 @@ describe(`Library watcher (e2e)`, () => {
`${IMMICH_TEST_ASSET_TEMP_PATH}/file5.jPg`,
);
await waitForEvent(libraryService, StorageEvent.ADD);
await waitForEvent(libraryService, StorageEvent.ADD);
await waitForEvent(libraryService, StorageEvent.ADD);
await waitForEvent(libraryService, StorageEvent.ADD);
await waitForEvent(libraryService, StorageEvent.ADD, 4);
const afterAssets = await api.assetApi.getAllAssets(server, admin.accessToken);
expect(afterAssets.length).toEqual(4);
@@ -161,9 +158,7 @@ describe(`Library watcher (e2e)`, () => {
`${IMMICH_TEST_ASSET_TEMP_PATH}/dir3/file4.jpg`,
);
await waitForEvent(libraryService, StorageEvent.ADD);
await waitForEvent(libraryService, StorageEvent.ADD);
await waitForEvent(libraryService, StorageEvent.ADD);
await waitForEvent(libraryService, StorageEvent.ADD, 3);
const assets = await api.assetApi.getAllAssets(server, admin.accessToken);
expect(assets.length).toEqual(3);

View File

@@ -138,19 +138,26 @@ export const testApp = {
},
};
export function waitForEvent<T>(emitter: EventEmitter, event: string): Promise<T> {
return new Promise((resolve, reject) => {
const success = (value: T) => {
emitter.off(StorageEvent.ERROR, fail);
resolve(value);
};
const fail = (error: Error) => {
emitter.off(event, success);
reject(error);
};
emitter.once(event, success);
emitter.once(StorageEvent.ERROR, fail);
});
export function waitForEvent(emitter: EventEmitter, event: string, times = 1): Promise<void[]> {
const promises: Promise<void>[] = [];
for (let i = 1; i <= times; i++) {
promises.push(
new Promise((resolve, reject) => {
const success = (value: any) => {
emitter.off(StorageEvent.ERROR, fail);
resolve(value);
};
const fail = (error: Error) => {
emitter.off(event, success);
reject(error);
};
emitter.once(event, success);
emitter.once(StorageEvent.ERROR, fail);
}),
);
}
return Promise.all(promises);
}
const directoryExists = async (dirPath: string) =>