import { createWriteStream, existsSync, mkdirSync } from "fs"; import sharp from "sharp"; 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) { console.log(`${folder}/${uuid}`); const response = await fetchAsset(uuid); try { const thumbnail = sharp().resize({ height: 200 }).webp(); await streamPipeline( response.body, thumbnail, createWriteStream(`${folder}/${uuid}.webp`) ); } catch (err) { console.log(err); } } } } } // await sharp('src/assets/arbre.png').resize({ width: 440, height: 690 }).webp().toFile('public/arbre.webp') } fetchData();