diff --git a/src/lib/BravoClient.ts b/src/lib/BravoClient.ts index 45e06ca..19c6c34 100644 --- a/src/lib/BravoClient.ts +++ b/src/lib/BravoClient.ts @@ -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'; @@ -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( + `collections/${collectionId}`, + ); + assertBravoClaim( + res.entities.length == 1, + `No collection found with id ${collectionId}`, + ); + collection = new FavroCollection(res.entities[0]); + } + return collection; } //#endregion diff --git a/src/lib/utility.ts b/src/lib/utility.ts index 2c0cb46..2eba1d2 100644 --- a/src/lib/utility.ts +++ b/src/lib/utility.ts @@ -9,7 +9,7 @@ export function stringsMatchIgnoringCase(string1: string, string2: string) { ); } -export function findRequiredByField< +export function findByField< Item extends Record, Field extends keyof Item, >( @@ -17,7 +17,7 @@ export function findRequiredByField< byField: Field, value: Item[Field], options?: { ignoreCase?: boolean }, -): Item { +): Item | undefined { assertBravoClaim(findIn, 'Search array does not exist'); const item = findIn.find((item) => { if ( @@ -29,6 +29,19 @@ export function findRequiredByField< } return item[byField] == value; }); + return item; +} + +export function findRequiredByField< + Item extends Record, + 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; }