Skip to content

Instantly share code, notes, and snippets.

@manabuyasuda
Last active September 9, 2021 07:47
Show Gist options
  • Select an option

  • Save manabuyasuda/4194b278c00036312ea413cdd787c784 to your computer and use it in GitHub Desktop.

Select an option

Save manabuyasuda/4194b278c00036312ea413cdd787c784 to your computer and use it in GitHub Desktop.
npmスクリプトで、APIからJSONファイルを生成する。
require('dotenv').config({
path: '.env.local',
})
const Client = require('node-rest-client').Client
const fs = require('fs')
const CMS_ROOT_ENDPOINT = `${process.env.CMS_ROOT_ENDPOINT}`
const CMC_API_KEY = `${process.env.CMC_API_KEY}`
const client = new Client()
const commonOptions = {
headers: {
'Content-type': 'application/json',
'X-API-KEY': CMC_API_KEY,
},
}
const generateJsonFromAPI = (url, output, options = commonOptions) => {
console.log(`Starts the generation of '${url}'.`)
client.get(url, options, (data, response) => {
const statusCode = response.statusCode
if (statusCode !== 200) {
console.log(`statusCode: ${statusCode}`)
throw new Error('Request failed.')
}
const result = JSON.stringify(data)
// TODO: Does not work if the directory does not exist.
fs.writeFile(output, result, (error) => {
if (error) {
throw error
}
console.log(`✨ '${output}' has been generated.`)
})
})
}
generateJsonFromAPI(`${CMS_ROOT_ENDPOINT}news`, './public/json/news.json')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment