|
1 | | -import { FastifyInstance } from "fastify" |
2 | 1 | import fastifyStatic from "@fastify/static" |
3 | | -import globby from "globby" |
| 2 | +import { FastifyInstance } from "fastify" |
4 | 3 | import path from "path" |
5 | 4 |
|
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 | | -} |
| 5 | +import { Config } from "./types" |
40 | 6 |
|
41 | 7 | // |
42 | 8 | // https://github.com/fastify/fastify-static#fastify-static |
43 | 9 | // |
44 | 10 | export function registerServeStatic(server: FastifyInstance, config: Config) { |
45 | | - const fallbacks = collectFallbacks(config.staticDir) |
46 | | - |
47 | | - server.setNotFoundHandler(async (req, res) => { |
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 | | - } |
54 | | - }) |
55 | | - |
56 | 11 | server.register(fastifyStatic, { |
57 | 12 | root: path.resolve(config.staticDir), |
58 | | - extensions: ["html", "htm"], |
| 13 | + }) |
| 14 | + |
| 15 | + server.setNotFoundHandler(function (request, reply) { |
| 16 | + reply.sendFile("index.html") |
59 | 17 | }) |
60 | 18 | } |
0 commit comments