import { createWriteStream, existsSync, mkdirSync } from "fs"; import fs from "fs/promises"; import { pipeline } from "stream"; import { promisify } from "util"; const streamPipeline = promisify(pipeline); const apiUrl = "https://admin.ceiba-conseil.com"; async function fetchJSONApi(path) { const url = `${apiUrl}${path}`; const options = { method: "GET", headers: { "content-type": "application/json", }, }; console.log(`fetchJSONApi: ${url}`); const response = await fetch(url, options); if (!response.ok) { const errors = await response.json(); throw errors.errors[0].message; } return response.json(); } async function fetchAsset(uuid) { const url = `${apiUrl}/assets/${uuid}`; return fetch(url); } async function fetchData() { const fields = [ "*", "translations.*", "questions.sort", "questions.questions_id.*", "questions.questions_id.translations.*", "questions.questions_id.answers.*", "questions.questions_id.answers.answers_id.*", "questions.questions_id.answers.answers_id.translations.*", "results.*", "results.results_id.*", "results.results_id.translations.*", ]; const url = `/items/scores?${fields .map((item) => `fields[]=${item}`) .join("&")}`; const data = (await fetchJSONApi(url)).data; await fs.writeFile("./src/data.json", JSON.stringify(data), "utf8"); const folder = "public/answers"; if (!existsSync(folder)) mkdirSync(folder); for (const score of data) { for (const question of score.questions) { for (const answer of question.questions_id.answers) { const uuid = answer.answers_id.image; if (uuid) { const response = await fetchAsset(uuid); await streamPipeline( response.body, createWriteStream(`${folder}/${uuid}.png`) ); } } } } } fetchData();