axios (npm install axios
) to create functions to retrieve API results.
import { createRequire } from 'module';
const require = createRequire(globalThis._importMeta_.url);
const axios = require("axios").default;
const BASE_URL = 'https://example.com/api/v1'
const api = axios.create({
baseURL: BASE_URL,
headers: {
'X-API-KEY':'***'
},
responseType: 'json'
})
export async function fetchTest() {
const res = await api.get('/test')
return res.data.contents
}
Writes the results of the API to a JS File.
import { createRequire } from 'module';
const require = createRequire(globalThis._importMeta_.url);
import * as api from '../api/index.mjs'
const fs = require("fs");
async function fetchTest(){
const res = await api.fetchTest()
const data = `export const TEST = ${JSON.stringify(res)}`
fs.writeFile("./data/test.ts", data, (err) => {
if (err) throw err;
console.log('test api is success');
})
}
fetchTest()
Prepare a command to execute in package.json.
{
"scripts": {
"update-data": "node scripts/makeData.mjs"
}
}
When executing the program, move it like this.
$ npm run update-data