Skip to content

Commit

Permalink
express.js client paths and redirects
Browse files Browse the repository at this point in the history
  • Loading branch information
AdamSiekierski committed Jul 3, 2020
1 parent 6d9a52a commit 83c8112
Showing 1 changed file with 26 additions and 4 deletions.
30 changes: 26 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,47 @@ const path = require("path");
const fs = require("fs");

function forFramework(framework, handlers) {
handlers[framework]();
return handlers[framework];
}

/**
* Prepares app for Gatsby enviroment
* @param {object} config - server client configuration of gatsby-plugin-nodejs
* @param {function} cb - callback with rest of app logic inside
*/
function prepare({ app, framework = "express", pathPrefix = "/" }, cb) {
function prepare({ app, framework = "express" }, cb) {
// Serve static Gatsby files
forFramework(framework, {
express: () => {
const express = require("express");
app.use(pathPrefix, express.static("public"));
},
});
})();

const config = JSON.parse(fs.readFileSync(path.resolve("./public", "gatsby-plugin-node.json")));

// Gatsby redirects
for (const r of config.redirects) {
forFramework(framework, {
express: () => {
app.get(r.fromPath, (req, res) =>
res.status(r.statusCode || r.isPermanent ? 301 : 302).redirect(r.toPath),
);
},
})();
}

// Client paths
for (const p of config.paths.filter((p) => p.matchPath)) {
forFramework(framework, {
express: () => {
app.get(p.matchPath, (req, res) =>
res.sendFile(path.resolve("./public", p.path, "index.html")),
);
},
});
}

// User-defined routes
cb();

Expand All @@ -31,7 +53,7 @@ function prepare({ app, framework = "express", pathPrefix = "/" }, cb) {
res.sendFile(path.resolve("./public", "404.html"));
});
},
});
})();
}

module.exports = {
Expand Down

0 comments on commit 83c8112

Please sign in to comment.