in beta/scripts/generateRedirects.js [15:70]
function writeRedirectsFile(redirects, redirectsFilePath) {
if (!redirects.length) {
return null;
}
/**
* We will first read the old config to validate if the redirect already exists in the json
*/
const vercelConfigPath = resolve(__dirname, '../../vercel.json');
const vercelConfigFile = readFileSync(vercelConfigPath);
const oldConfigContent = JSON.parse(vercelConfigFile);
/**
* Map data as vercel expects it to be
*/
let vercelRedirects = {};
redirects.forEach((redirect) => {
const {fromPath, isPermanent, toPath} = redirect;
vercelRedirects[fromPath] = {
destination: toPath,
permanent: !!isPermanent,
};
});
/**
* Make sure we dont have the same redirect already
*/
oldConfigContent.redirects.forEach((data) => {
if(vercelRedirects[data.source]){
delete vercelRedirects[data.source];
}
});
/**
* Serialize the object to array of objects
*/
let newRedirects = [];
Object.keys(vercelRedirects).forEach((value) =>
newRedirects.push({
source: value,
destination: vercelRedirects[value].destination,
permanent: !!vercelRedirects[value].isPermanent,
})
);
/**
* We already have a vercel.json so we spread the new contents along with old ones
*/
const newContents = {
...oldConfigContent,
redirects: [...oldConfigContent.redirects, ...newRedirects],
};
writeFile(redirectsFilePath, JSON.stringify(newContents, null, 2));
}