diff --git a/api/src/repositories/taxonomy-repository.ts b/api/src/repositories/taxonomy-repository.ts index 617d2438..c055ffe9 100644 --- a/api/src/repositories/taxonomy-repository.ts +++ b/api/src/repositories/taxonomy-repository.ts @@ -3,6 +3,7 @@ import { z } from 'zod'; import { getKnex } from '../database/db'; import { getLogger } from '../utils/logger'; import { BaseRepository } from './base-repository'; +import { ApiExecuteSQLError } from '../errors/api-error'; const defaultLog = getLogger('repositories/taxonomy-repository'); @@ -64,7 +65,7 @@ export class TaxonomyRepository extends BaseRepository { commonName: string | null, itisData: Record, itisUpdateDate: string - ): Promise { + ): Promise { defaultLog.debug({ label: 'addItisTaxonRecord', itisTsn }); const sqlStatement = SQL` @@ -98,7 +99,16 @@ export class TaxonomyRepository extends BaseRepository { taxon.record_end_date IS null; `; - await this.connection.sql(sqlStatement, TaxonRecord); + const response = await this.connection.sql(sqlStatement, TaxonRecord); + + if (response.rowCount !== 1) { + throw new ApiExecuteSQLError('Failed to insert new taxon record', [ + 'TaxonomyRepository->addItisTaxonRecord', + 'rowCount was null or undefined, expected rowCount = 1' + ]); + } + + return response.rows[0]; } /** diff --git a/api/src/services/taxonomy-service.ts b/api/src/services/taxonomy-service.ts index f6eb6463..5b24e759 100644 --- a/api/src/services/taxonomy-service.ts +++ b/api/src/services/taxonomy-service.ts @@ -40,17 +40,19 @@ export class TaxonomyService { const missingTsnIds = tsnIds.filter((tsnId) => !existingTsnIds.includes(tsnId)); + let patchedTaxonRecords: TaxonRecord[] = []; + if (missingTsnIds.length) { // If the local database does not contain a record for all of the requested ids, search ITIS for the missing // taxon records, patching the missing records in the local database in the process const itisService = new ItisService(); const itisResponse = await itisService.searchItisByTSN(missingTsnIds); - await Promise.all(itisResponse.map(async (item) => this.addItisTaxonRecord(item))); + patchedTaxonRecords = await Promise.all(itisResponse.map(async (item) => this.addItisTaxonRecord(item))); } // Missing ids patched, return taxon records for all requested ids - return this._sanitizeTaxonRecordsData(await this.taxonRepository.getTaxonByTsnIds(tsnIds)); + return this._sanitizeTaxonRecordsData(existingTaxonRecords.concat(patchedTaxonRecords)); } _sanitizeTaxonRecordsData(taxonRecords: TaxonRecord[]): TaxonSearchResult[] { @@ -70,7 +72,7 @@ export class TaxonomyService { * @return {*} {Promise} * @memberof TaxonomyService */ - async addItisTaxonRecord(itisSolrResponse: ItisSolrSearchResponse): Promise { + async addItisTaxonRecord(itisSolrResponse: ItisSolrSearchResponse): Promise { let commonName = null; if (itisSolrResponse.commonNames) { commonName = itisSolrResponse.commonNames[0].split('$')[1];