<commit_before>import {LogManager} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import 'fetch';
import {OpenbelApiClient} from './openbelapi-client';
import {Authentication} from './authentication';
import {EventAggregator} from 'aurelia-event-aggregator';

let logger = LogManager.getLogger('openbelApi');

export class OpenbelapiService {
  static inject = [OpenbelApiClient, Authentication, EventAggregator];
  constructor(openbelApiClient, authentication, ea) {
    this.openbelApiClient = openbelApiClient;
    this.apiClient = this.openbelApiClient.client;
    this.auth = authentication;
    this.ea = ea;
    this.ea.subscribe('selectedOpenbelApiUrl', obj => {this.updateClient(obj)});
  }

  /**
   *  Update client with new Openbel API Url
   */
  updateClient(selectedOpenbelApiUrl) {
    this.apiClient = this.openbelApiClient.configureClient(selectedOpenbelApiUrl);
  }

  /**
   * <p>Process facets from search</p>
   * <p>This removes the facets that won't be used in the search results page
   *    and reorganizes it for presentation in the search results page.
   * </p>
   *
   * @param {Object} facets - facets returned by BEL API from search
   * @returns {Object} facets - facets after processing to be used in web page
   * */
  processFacets(facets) {
    let newFacets = {};

    for (let facet of facets) {
      if (
        facet.category === 'experiment_context' ||
        facet.name === 'Status' ||
        facet.category === 'citation' ||
        facet.name === 'dataset' ||
        facet.name === 'nanopub_status'
      ) {
        let facetName = facet.name;

        if (facet.category === 'citation') {
          facetName = 'Reference ID';
        }
        if (facet.name === 'dataset') {
          facetName = 'Datasets';
        }
        if (facet.name === 'nanopub_status') {
          facetName = 'Nanopub Status';
        }

        newFacets[facetName] = [];
        for (let value of facet.values) {
          let name = value.value;
          newFacets[facetName].push({
            'name': name,
            'count': value.count,
            'filter': value.filter
          });
        }
      }
    }

    return newFacets;
  }

  /**
   * Search the BELMgr database and return website ready results
   *
   * @param {String} filter - search string
   * @param {Integer} start - result page starting point (default = 0)
   * @param {Integer} size - number of results returned (default = 10)
   * @param {Integer} faceted - facet results if equals 1 (default = 1)
   * @return {Promise} data - processed search results ready to display on the search results web page
   * */
  search(start = 0, size = 10, faceted = 'yes', filters) {
    /* eslint-disable camelcase */
    let max_values_per_facet = 10;
    let getstring = `/nanopub?start=${start}&size=${size}&faceted=${faceted}&max_values_per_facet=${max_values_per_facet}`;
    /* eslint-enable camelcase */


    if (filters) {
      for (let filter of filters) {
        getstring += `&filter=${filter}`;
      }
    }

    // logger.debug('Filters2: ', filters);
    logger.debug('Getstring1: ', getstring);

    return this.apiClient.fetch(getstring)
      .then(response => response.json())
      .then(data => {
        logger.debug('Data: ', data);
        let newData = {};
        newData.nanopubs = data.nanopub_collection;
        newData.facets = this.processFacets(data.facets);
        newData.metadata = data.metadata;
        newData.searchUrl = data._links.self.href;
        return newData;
      })
      .catch(function(reason) {
        if (reason.status === 404) {
          return {
            'nanopubs': null,
            'facets': {}
          };
        }
        if (reason.status === 401) {
          logger.info('Unauthorized request');
        }
        logger.error('Search API Error: ', reason);
      });
  }

  /**
   * Get BEL components (subject, relation, object) from a BEL statement
   * @param belStatement
   * @returns {"subject": "", "relationship": "", "object": ""}
   */
  getBelComponents(belStatement) {
    if (belStatement) {
      return this.apiClient.fetch(`/expressions/${belStatement}/components?flatten=1`)
        .then(response => response.json())
        .then(data => {
          // logger.debug('BEL Nanopub: ', data);
          return data.expression_components;
        })
        .catch(function(reason) {
          logger.error(`GET BEL Components Error: ${reason}`);
        });
    }
    let comp = {};
    return comp;
  }

  getBelNanopub(id) {

    let token = this.auth.getToken();

    return this.apiClient.fetch(`/nanopub/${id}`)
      .then(response => response.json())
      .then(data => {
        let nanopub = data.nanopub;
        return nanopub;
      })
      .catch(function(reason) {
        logger.error(`GET BEL Nanopub Error: ${reason}`);
      });
  }

  /**
   * Load BEL Nanopub (POST or PUT)
   *
   * @param id
   * @param nanopub
   */
  loadBelNanopub(nanopub, id) {

    // Update Nanopub given an Id
    if (id) {
      return this.apiClient.fetch(`/nanopub/${id}`, {
        method: 'put',
        headers: {
          'Accept': 'application/hal+json',
          'Content-Type': 'application/json; profile=http://next.belframework.org/schema/nanopub.schema.json'

        },
        body: JSON.stringify(nanopub)
      }).catch(response => {
        logger.error('PUT Nanopub error ', response);
      });
    }

    // Create new Nanopub
    return this.apiClient.fetch(`/nanopub`, {
      method: 'post',
      headers: {
        'Accept': 'application/hal+json',
        'Content-Type': 'application/json; profile=http://next.belframework.org/schema/nanopub.schema.json'
      },
      body: JSON.stringify(nanopub)
    }).catch(response => {
      logger.error('POST Nanopub error ', response);
    });
  }

  deleteBelNanopub(nanopubId) {

    return this.apiClient.fetch(`/nanopub/${nanopubId}`, {
      method: 'delete',
      headers: {
        'Accept': 'application/hal+json',
        'Content-Type': 'application/json; profile=http://next.belframework.org/schema/nanopub.schema.json'
      }
    })
    .catch(function(reason) {
      logger.error(`DELETE BEL Nanopub Error: `, reason);
    });
  }
<commit_msg>update API route for nanopubs, e.g. /api/nanopubs<commit_after>import {LogManager} from 'aurelia-framework';
import {HttpClient} from 'aurelia-fetch-client';
import 'fetch';
import {OpenbelApiClient} from './openbelapi-client';
import {Authentication} from './authentication';
import {EventAggregator} from 'aurelia-event-aggregator';

let logger = LogManager.getLogger('openbelApi');

export class OpenbelapiService {
  static inject = [OpenbelApiClient, Authentication, EventAggregator];
  constructor(openbelApiClient, authentication, ea) {
    this.openbelApiClient = openbelApiClient;
    this.apiClient = this.openbelApiClient.client;
    this.auth = authentication;
    this.ea = ea;
    this.ea.subscribe('selectedOpenbelApiUrl', obj => {this.updateClient(obj)});
  }

  /**
   *  Update client with new Openbel API Url
   */
  updateClient(selectedOpenbelApiUrl) {
    this.apiClient = this.openbelApiClient.configureClient(selectedOpenbelApiUrl);
  }

  /**
   * <p>Process facets from search</p>
   * <p>This removes the facets that won't be used in the search results page
   *    and reorganizes it for presentation in the search results page.
   * </p>
   *
   * @param {Object} facets - facets returned by BEL API from search
   * @returns {Object} facets - facets after processing to be used in web page
   * */
  processFacets(facets) {
    let newFacets = {};

    for (let facet of facets) {
      if (
        facet.category === 'experiment_context' ||
        facet.name === 'Status' ||
        facet.category === 'citation' ||
        facet.name === 'dataset' ||
        facet.name === 'nanopub_status'
      ) {
        let facetName = facet.name;

        if (facet.category === 'citation') {
          facetName = 'Reference ID';
        }
        if (facet.name === 'dataset') {
          facetName = 'Datasets';
        }
        if (facet.name === 'nanopub_status') {
          facetName = 'Nanopub Status';
        }

        newFacets[facetName] = [];
        for (let value of facet.values) {
          let name = value.value;
          newFacets[facetName].push({
            'name': name,
            'count': value.count,
            'filter': value.filter
          });
        }
      }
    }

    return newFacets;
  }

  /**
   * Search the BELMgr database and return website ready results
   *
   * @param {String} filter - search string
   * @param {Integer} start - result page starting point (default = 0)
   * @param {Integer} size - number of results returned (default = 10)
   * @param {Integer} faceted - facet results if equals 1 (default = 1)
   * @return {Promise} data - processed search results ready to display on the search results web page
   * */
  search(start = 0, size = 10, faceted = 'yes', filters) {
    /* eslint-disable camelcase */
    let max_values_per_facet = 10;
    let getstring = `/nanopubs?start=${start}&size=${size}&faceted=${faceted}&max_values_per_facet=${max_values_per_facet}`;
    /* eslint-enable camelcase */


    if (filters) {
      for (let filter of filters) {
        getstring += `&filter=${filter}`;
      }
    }

    // logger.debug('Filters2: ', filters);
    logger.debug('Getstring1: ', getstring);

    return this.apiClient.fetch(getstring)
      .then(response => response.json())
      .then(data => {
        logger.debug('Data: ', data);
        let newData = {};
        newData.nanopubs = data.nanopub_collection;
        newData.facets = this.processFacets(data.facets);
        newData.metadata = data.metadata;
        newData.searchUrl = data._links.self.href;
        return newData;
      })
      .catch(function(reason) {
        if (reason.status === 404) {
          return {
            'nanopubs': null,
            'facets': {}
          };
        }
        if (reason.status === 401) {
          logger.info('Unauthorized request');
        }
        logger.error('Search API Error: ', reason);
      });
  }

  /**
   * Get BEL components (subject, relation, object) from a BEL statement
   * @param belStatement
   * @returns {"subject": "", "relationship": "", "object": ""}
   */
  getBelComponents(belStatement) {
    if (belStatement) {
      return this.apiClient.fetch(`/expressions/${belStatement}/components?flatten=1`)
        .then(response => response.json())
        .then(data => {
          // logger.debug('BEL Nanopub: ', data);
          return data.expression_components;
        })
        .catch(function(reason) {
          logger.error(`GET BEL Components Error: ${reason}`);
        });
    }
    let comp = {};
    return comp;
  }

  getBelNanopub(id) {

    let token = this.auth.getToken();

    return this.apiClient.fetch(`/nanopubs/${id}`)
      .then(response => response.json())
      .then(data => {
        let nanopub = data.nanopub;
        return nanopub;
      })
      .catch(function(reason) {
        logger.error(`GET BEL Nanopub Error: ${reason}`);
      });
  }

  /**
   * Load BEL Nanopub (POST or PUT)
   *
   * @param id
   * @param nanopub
   */
  loadBelNanopub(nanopub, id) {

    // Update Nanopub given an Id
    if (id) {
      return this.apiClient.fetch(`/nanopubs/${id}`, {
        method: 'put',
        headers: {
          'Accept': 'application/hal+json',
          'Content-Type': 'application/json; profile=http://next.belframework.org/schema/nanopub.schema.json'

        },
        body: JSON.stringify(nanopub)
      }).catch(response => {
        logger.error('PUT Nanopub error ', response);
      });
    }

    // Create new Nanopub
    return this.apiClient.fetch(`/nanopubs`, {
      method: 'post',
      headers: {
        'Accept': 'application/hal+json',
        'Content-Type': 'application/json; profile=http://next.belframework.org/schema/nanopub.schema.json'
      },
      body: JSON.stringify(nanopub)
    }).catch(response => {
      logger.error('POST Nanopub error ', response);
    });
  }

  deleteBelNanopub(nanopubId) {

    return this.apiClient.fetch(`/nanopubs/${nanopubId}`, {
      method: 'delete',
      headers: {
        'Accept': 'application/hal+json',
        'Content-Type': 'application/json; profile=http://next.belframework.org/schema/nanopub.schema.json'
      }
    })
    .catch(function(reason) {
      logger.error(`DELETE BEL Nanopub Error: `, reason);
    });
  }

{'fraction_non_alphanumeric': 0.14240178500278908, 'fraction_numerical': 0.0030281297314527053, 'mean_word_length': 2.460159911772815, 'pattern_counts': {'":': 6, '<': 11, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7309175', 'n_tokens_mistral': 3987, 'n_tokens_neox': 3838, 'n_words': 844}