Hi guys. Iam writing a function for migration of some bigger chunk of data from one repo to other.
Iam trying to use approach mentioned in the pitch "presentation"
So Iam basically getting JSON file for every record with fetchDataJsonFromHref
function but Iam not really sure where to put it or how to use in the request. request body sounds like a logical option, but Iam constantly getting error about invalid JSON even tho the response Iam getting from const json = await fetchDataJsonFromHref(chapter.href)
suppose to be valid JSON by json validator.
import {createClient} from '@prismicio/client'
import fetch from 'node-fetch'
async function fetchDataJsonFromHref(href) {
try {
const response = await fetch(href);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
return await response.text();
} catch (error) {
console.error(`Failed to fetch data from ${href}: ${error}`);
return null;
}
}
async function createDocument() {
const copyFromRepository = 'abc'
const writeToRepository = 'def'
const email = process.env.PRISMIC_EMAIL
const password = process.env.PRISMIC_PASSWORD
const demoApiKey = process.env.DEMO_KEY
const client = createClient(copyFromRepository, { fetch })
const authResponse = await fetch('https://auth.prismic.io/login', {
headers: {
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify({
email,
password,
}),
});
const url = `https://migration.prismic.io/documents`;
const token = await authResponse.text();
const chapterData = await client.getAllByType('chapter')
for (const chapter of chapterData) {
const jsonData = await fetchDataJsonFromHref(chapter.href);
const parsedJsonData = JSON.parse(jsonData);
parsedJsonData.title = chapter.data.chapter_title;
parsedJsonData.type = 'chapter';
parsedJsonData.lang = 'de-ch';
console.log(JSON.stringify(parsedJsonData));
const chapterResponse = await fetch(url, {
headers: {
Authorization: `Bearer ${token}`,
'x-api-key': demoApiKey,
'Content-Type': 'application/json',
'repository': `${writeToRepository}`,
},
method: 'POST',
body: JSON.stringify(parsedJsonData),
});
console.log(await chapterResponse.json());
}
}
createDocument()
Maybe my approach is completely wrong, I would be happy to learn how to do it correctly. Thanks!
Additional info:
The real issue is that if I directly use const jsonData = await fetchDataJsonFromHref(chapter.href);
in a body I dont get error about invalid Json but Iam getting this "error" that title, type and lang has to be strings
if I parse the reponse and add those and strigify again, booom Json is not valid...