Files
30-seconds-of-code/node_modules/gatsby-plugin-netlify/create-redirects.js
2019-08-20 15:52:05 +02:00

71 lines
2.4 KiB
JavaScript

"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
exports.__esModule = true;
exports.default = writeRedirectsFile;
var _objectWithoutPropertiesLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutPropertiesLoose"));
var _constants = require("./constants");
var _fsExtra = require("fs-extra");
async function writeRedirectsFile(pluginData, redirects, rewrites) {
const {
publicFolder
} = pluginData;
if (!redirects.length && !rewrites.length) return null;
const FILE_PATH = publicFolder(`_redirects`); // Map redirect data to the format Netlify expects
// https://www.netlify.com/docs/redirects/
redirects = redirects.map(redirect => {
const {
fromPath,
isPermanent,
// eslint-disable-line no-unused-vars
force,
toPath,
statusCode
} = redirect,
rest = (0, _objectWithoutPropertiesLoose2.default)(redirect, ["fromPath", "isPermanent", "redirectInBrowser", "force", "toPath", "statusCode"]);
let status = isPermanent ? `301` : `302`;
if (statusCode) status = statusCode;
if (force) status = status.concat(`!`); // The order of the first 3 parameters is significant.
// The order for rest params (key-value pairs) is arbitrary.
const pieces = [fromPath, toPath, status];
for (let key in rest) {
const value = rest[key];
if (typeof value === `string` && value.indexOf(` `) >= 0) {
console.warn(`Invalid redirect value "${value}" specified for key "${key}". ` + `Values should not contain spaces.`);
} else {
pieces.push(`${key}=${value}`);
}
}
return pieces.join(` `);
});
rewrites = rewrites.map(({
fromPath,
toPath
}) => `${fromPath} ${toPath} 200`);
let appendToFile = false; // Websites may also have statically defined redirects
// In that case we should append to them (not overwrite)
// Make sure we aren't just looking at previous build results though
const fileExists = await (0, _fsExtra.exists)(FILE_PATH);
if (fileExists) {
const fileContents = await (0, _fsExtra.readFile)(FILE_PATH);
if (fileContents.indexOf(_constants.HEADER_COMMENT) < 0) {
appendToFile = true;
}
}
const data = `${_constants.HEADER_COMMENT}\n\n${[...redirects, ...rewrites].join(`\n`)}`;
return appendToFile ? (0, _fsExtra.appendFile)(FILE_PATH, `\n\n${data}`) : (0, _fsExtra.writeFile)(FILE_PATH, data);
}