From 83c81120b072d290f72beb93d01ef4e2e4e578d8 Mon Sep 17 00:00:00 2001 From: Adam Siekierski Date: Fri, 3 Jul 2020 12:34:49 +0200 Subject: [PATCH] express.js client paths and redirects --- index.js | 30 ++++++++++++++++++++++++++---- 1 file changed, 26 insertions(+), 4 deletions(-) diff --git a/index.js b/index.js index 4056d1f..6504172 100644 --- a/index.js +++ b/index.js @@ -2,7 +2,7 @@ const path = require("path"); const fs = require("fs"); function forFramework(framework, handlers) { - handlers[framework](); + return handlers[framework]; } /** @@ -10,17 +10,39 @@ function forFramework(framework, handlers) { * @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(); @@ -31,7 +53,7 @@ function prepare({ app, framework = "express", pathPrefix = "/" }, cb) { res.sendFile(path.resolve("./public", "404.html")); }); }, - }); + })(); } module.exports = {