|
1 | 1 | import { FastifyInstance } from "fastify"
|
2 | 2 | import fastifyStatic from "fastify-static"
|
| 3 | +import globby from "globby" |
3 | 4 | import path from "path"
|
4 | 5 |
|
5 |
| -import { Config } from "./types" |
| 6 | +import { Config, StaticFallbacks } from "./types" |
| 7 | + |
| 8 | +// |
| 9 | +// Unfortunately I couldn't make fastify-static add a fallback to /path/index.html when /path is requested. |
| 10 | +// Therefore this collects those fallbacks once on startup. |
| 11 | +// |
| 12 | +function collectFallbacks(staticDir: string) { |
| 13 | + const files = globby.sync("", { cwd: staticDir, onlyFiles: true }) |
| 14 | + |
| 15 | + const fallbacks = files.reduce((result, filename) => { |
| 16 | + if (!filename.includes("/")) { |
| 17 | + return result |
| 18 | + } |
| 19 | + if (!filename.endsWith(".html") && !filename.endsWith(".htm")) { |
| 20 | + return result |
| 21 | + } |
| 22 | + |
| 23 | + const directory = path.dirname(filename) |
| 24 | + const url = "/" + directory |
| 25 | + |
| 26 | + if (result[url]) { |
| 27 | + return result |
| 28 | + } |
| 29 | + |
| 30 | + if (!result[directory]) { |
| 31 | + const fallbackDir = path.resolve(staticDir, directory) |
| 32 | + result["/" + directory] = fallbackDir |
| 33 | + } |
| 34 | + |
| 35 | + return result |
| 36 | + }, {} as StaticFallbacks) |
| 37 | + |
| 38 | + return fallbacks |
| 39 | +} |
6 | 40 |
|
7 | 41 | //
|
8 | 42 | // https://github.com/fastify/fastify-static#fastify-static
|
9 | 43 | //
|
10 | 44 | export function registerServeStatic(server: FastifyInstance, config: Config) {
|
| 45 | + const fallbacks = collectFallbacks(config.staticDir) |
| 46 | + |
11 | 47 | server.setNotFoundHandler(async (req, res) => {
|
12 |
| - res.sendFile("index.html", config.staticDir) |
| 48 | + const fallbackDir = fallbacks[req.url] |
| 49 | + if (fallbackDir) { |
| 50 | + res.sendFile("index.html", fallbackDir) |
| 51 | + } else { |
| 52 | + res.sendFile("index.html", config.staticDir) |
| 53 | + } |
13 | 54 | })
|
| 55 | + |
14 | 56 | server.register(fastifyStatic, {
|
15 | 57 | root: path.resolve(config.staticDir),
|
16 | 58 | extensions: ["html", "htm"],
|
|
0 commit comments