-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
104 lines (92 loc) · 2.85 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const path = require("path");
const fs = require("fs");
// Disable gatsby files serving, for example when building the site
const args = process.argv.slice(2);
const disableGatsby = args.includes("--no-gatsby");
/**
* 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" }, cb) {
const config = JSON.parse(fs.readFileSync(path.resolve("./public", "gatsby-plugin-node.json")));
function forFramework(handlers) {
return (
handlers[framework] ||
function () {
throw new Error(`Uncompatible framework: ${framework}`);
}
);
}
function withPrefix(path) {
return (config.pathPrefix || "") + path;
}
if (!disableGatsby) {
// Serve static Gatsby files
forFramework({
express: () => {
const express = require("express");
app.use(withPrefix("/"), express.static("public"));
},
fastify: () => {
app.ignoreTrailingSlash = true;
app.register(require("fastify-static"), {
root: path.resolve("./public"),
prefix: withPrefix("/"),
});
},
})();
// Gatsby redirects
for (const r of config.redirects) {
forFramework({
express: () => {
app.get(withPrefix(r.fromPath), (req, res) => {
const toPath = /https?:\/\//.test(r.toPath) ? r.toPath : withPrefix(r.toPath);
res.status(r.statusCode || r.isPermanent ? 301 : 302).redirect(toPath);
});
},
fastify: () => {
app.get(withPrefix(r.fromPath), (req, reply) => {
const toPath = /https?:\/\//.test(r.toPath) ? r.toPath : withPrefix(r.toPath);
reply.code(r.statusCode || r.isPermanent ? 301 : 302).redirect(toPath);
});
},
})();
}
// Client paths
for (const p of config.paths.filter((p) => p.matchPath)) {
forFramework({
express: () => {
app.get(withPrefix(p.matchPath), (req, res) => {
res.sendFile(path.resolve("./public", p.path.replace("/", ""), "index.html"));
});
},
fastify: () => {
app.get(withPrefix(p.matchPath), (req, reply) => {
reply.sendFile(path.resolve("./public", p.path.replace("/", ""), "index.html"));
});
},
})();
}
}
// User-defined routes
cb();
if (!disableGatsby) {
// Gatsby 404 page
forFramework({
express: () => {
app.use((req, res) => {
res.status(404).sendFile(path.resolve("./public", "404.html"));
});
},
fastify: () => {
app.setNotFoundHandler((req, reply) => {
reply.sendFile(path.resolve("./public", "404.html"));
});
},
})();
}
}
module.exports = {
prepare,
};