{"size": 1113, "ext": "js", "max_stars_repo_path": "snprc_ehr/src/client/ChipReader/api/fetchAnimalId.js", "max_stars_repo_name": "LabKey/snprcEHRModules", "max_stars_repo_stars_event_min_datetime": "2018-11-13T17:29:20.000Z", "max_stars_repo_stars_event_max_datetime": "2018-11-13T17:29:25.000Z", "max_issues_repo_path": "snprc_ehr/src/client/ChipReader/api/fetchAnimalId.js", "max_issues_repo_name": "LabKey/snprcEHRModules", "max_issues_repo_issues_event_min_datetime": "2019-02-27T18:02:47.000Z", "max_issues_repo_issues_event_max_datetime": "2022-03-30T22:16:03.000Z", "max_forks_repo_path": "snprc_ehr/src/client/ChipReader/api/fetchAnimalId.js", "max_forks_repo_name": "LabKey/snprcEHRModules", "max_forks_repo_forks_event_min_datetime": "2019-12-04T16:29:52.000Z", "max_forks_repo_forks_event_max_datetime": "2019-12-04T16:29:52.000Z"}
{"max_stars_count": 2, "max_issues_count": 36, "max_forks_count": 1, "avg_line_length": 30.9166666667, "max_line_length": 104, "alphanum_fraction": 0.5534591195}
import moment from 'moment'
import { executeSql } from '../../Shared/api/api'

const parse = rows => {
    if (rows.length === 0) {
       return [{ value: 'Not Found', url: '', location: '', time: moment() }]
    }

    return rows.map(({ data }) => {
        return { value: data.Id.value, url: data.Id.url, location: data.location.value, time: moment() }
    })
}

const fetchAnimalId = chipId => {
    const parameters = { chipId: `%${chipId}%` }
    const sql = 'PARAMETERS ( chipId VARCHAR DEFAULT NULL ) '
        .concat('SELECT ih.Id AS Id, ih.Id.curLocation.location as location ')
        .concat('FROM study.idHistory as ih ')
        .concat('WHERE ih.value like chipId')

    return new Promise((resolve, reject) => {
        executeSql({
            schemaName: 'study',
            sql,
            parameters
        }).then(({ rows }) => {
            const parseRows = parse(rows)
            if (parseRows.length !== 1) throw new Error('Animal not found')
            resolve(parseRows[0])
        }).catch(error => {
            reject(error)
        })
    })
}
export default fetchAnimalId
