Skip to content

Commit

Permalink
feat(store): add unloadAll (#91)
Browse files Browse the repository at this point in the history
  • Loading branch information
kyranet committed Jul 21, 2021
1 parent de5de92 commit 3909c51
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 2 deletions.
6 changes: 6 additions & 0 deletions src/lib/strategies/ILoaderStrategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,12 @@ export interface ILoaderStrategy<T extends Piece> {
*/
onUnload(store: Store<T>, piece: T): Awaited<unknown>;

/**
* Called after all pieces have been unloaded.
* @param store The store that unloaded all pieces.
*/
onUnloadAll(store: Store<T>): Awaited<unknown>;

/**
* @param error The error that was thrown.
* @param path The path of the file that caused the error to be thrown.
Expand Down
4 changes: 4 additions & 0 deletions src/lib/strategies/LoaderStrategy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,10 @@ export class LoaderStrategy<T extends Piece> implements ILoaderStrategy<T> {
return undefined;
}

public onUnloadAll(): unknown {
return undefined;
}

public onError(error: Error, path: string): void {
console.error(`Error when loading '${path}':`, error);
}
Expand Down
20 changes: 18 additions & 2 deletions src/lib/structures/Store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ export class Store<T extends Piece> extends Collection<string, T> {
/**
* Loads one or more pieces from a path.
* @param path The path of the file to load.
* @return An async iterator that yields each one of the loaded pieces.
* @return All the loaded pieces.
*/
public async load(path: string): Promise<T[]> {
const data = this.strategy.filter(path);
Expand Down Expand Up @@ -129,6 +129,22 @@ export class Store<T extends Piece> extends Collection<string, T> {
return piece;
}

/**
* Unloads all pieces from the store.
*/
public async unloadAll(): Promise<T[]> {
const promises = [];
for (const piece of this.values()) {
promises.push(this.unload(piece));
}

const results = await Promise.all(promises);

this.strategy.onUnloadAll(this);
Store.logger?.(`[STORE => ${this.name}] [UNLOAD-ALL] Removed all pieces.`);
return results;
}

/**
* Loads all pieces from all directories specified by {@link paths}.
*/
Expand All @@ -144,7 +160,7 @@ export class Store<T extends Piece> extends Collection<string, T> {
Store.logger?.(`[STORE => ${this.name}] [LOAD-ALL] Found '${pieces.length}' pieces.`);

// Clear the store before inserting the new pieces:
this.clear();
await this.unloadAll();
Store.logger?.(`[STORE => ${this.name}] [LOAD-ALL] Cleared all pieces.`);

// Load each piece:
Expand Down

0 comments on commit 3909c51

Please sign in to comment.