"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.findCustomDrugByName = void 0;

var _drugCache = require("./drug-cache");

const findCustomDrugByName = term => {
  if (!term) {
    return Promise.resolve([]);
  }

  return fetch("https://rxnav.nlm.nih.gov/REST/approximateTerm.json?maxEntries=4&term=".concat(encodeURIComponent(term))).then(res => res.json()).then(parsed => {
    const resultsById = (parsed.approximateGroup.candidate || []).reduce((result, item) => {
      const id = item.rxcui;

      if (!result[id]) {
        result[id] = {
          id,
          score: item.score
        };
      }

      return result;
    }, {});
    return Object.keys(resultsById);
  }).then(ids => Promise.all(ids.map(_drugCache.getDrugName)).then(names => names.map((name, index) => ({
    id: ids[index],
    name
  }))).then(matches => matches.filter(item => !!item.name)));
};

exports.findCustomDrugByName = findCustomDrugByName;