Skip to content

Commit

Permalink
feat: Change the find-collection-by-id method to directly hit the sin…
Browse files Browse the repository at this point in the history
…gle-collection API endpoint if not found in cache.
  • Loading branch information
adam-coster committed Jun 26, 2021
1 parent fd13627 commit 53a1a25
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 6 deletions.
20 changes: 16 additions & 4 deletions src/lib/BravoClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
FavroDataCollection,
} from '../types/FavroApi';
import { FavroResponse } from './FavroResponse';
import { findRequiredByField } from './utility.js';
import { findByField, findRequiredByField } from './utility.js';
import { FavroCollection } from './FavroCollection';
import { FavroUser } from './FavroUser';

Expand Down Expand Up @@ -282,12 +282,24 @@ export class BravoClient {
}

async findCollectionById(collectionId: string) {
return findRequiredByField(
await this.listCollections(),
// See if already in the cache
let collection = findByField(
this._collections || [],
'collectionId',
collectionId,
{ ignoreCase: true },
);
if (!collection) {
// Then hit the API directly!
const res = await this.request<FavroDataCollection>(
`collections/${collectionId}`,
);
assertBravoClaim(
res.entities.length == 1,
`No collection found with id ${collectionId}`,
);
collection = new FavroCollection(res.entities[0]);
}
return collection;
}

//#endregion
Expand Down
17 changes: 15 additions & 2 deletions src/lib/utility.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ export function stringsMatchIgnoringCase(string1: string, string2: string) {
);
}

export function findRequiredByField<
export function findByField<
Item extends Record<string, any>,
Field extends keyof Item,
>(
findIn: Item[],
byField: Field,
value: Item[Field],
options?: { ignoreCase?: boolean },
): Item {
): Item | undefined {
assertBravoClaim(findIn, 'Search array does not exist');
const item = findIn.find((item) => {
if (
Expand All @@ -29,6 +29,19 @@ export function findRequiredByField<
}
return item[byField] == value;
});
return item;
}

export function findRequiredByField<
Item extends Record<string, any>,
Field extends keyof Item,
>(
findIn: Item[],
byField: Field,
value: Item[Field],
options?: { ignoreCase?: boolean },
): Item {
const item = findByField(findIn, byField, value, options);
assertBravoClaim(item, 'Matching entity not found');
return item;
}

0 comments on commit 53a1a25

Please sign in to comment.