@plantinformatics/vcf-genotype-brapi
Version:
Client and server functions to access genotype data from VCF via a custom web API and BrAPI
62 lines (47 loc) • 1.95 kB
JavaScript
/** Generated by ChatGPT from this prompt :
### For a JavaScript web application, show how functions making web API requests can be written to be used either in the frontend (web browser) or backend (node.js server).
---
To write functions for making web API requests that can be used in both the frontend (web browser) and backend (Node.js server), you can use the Fetch API, which is available in browsers, and you can also use it in Node.js by using the `node-fetch` library.
*/
/* global require */ // defined in Node.js server only
// Import fetch depending on the environment
// const fetch = typeof window === 'undefined' ? require('node-fetch') : window.fetch;
let fetch = typeof window === 'undefined' ? import('node-fetch').then(module => fetch = module.default) : window.fetch;
/**
* Make an API request.
* @param {string} url - The API endpoint.
* @param {Object} options - Fetch options (method, headers, body, etc.).
* @returns {Promise<Object>} - The response data.
*/
async function apiRequest(url, options = {}) {
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('API request failed:', error);
throw error;
}
}
//------------------------------------------------------------------------------
export { apiRequest };
/** Usage
* Usage is the same in either the frontend or backend.
*
* Installation (backend Node.js) : npm install node-fetch
*/
if (false) {
// import apiRequest from './api-request.js';
async function fetchData() {
try {
const data = await apiRequest('https://api.example.com/data');
console.log(data);
} catch (error) {
console.error('Error fetching data:', error);
}
}
}
//------------------------------------------------------------------------------