aboutsummaryrefslogtreecommitdiff
path: root/packages/server/src/app.ts
blob: 33c5a5a0fdcab685a837082d4b46477a787c31da (plain)
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
import api from "./routes/api/v1";
import { fastify as fastifyFactory, FastifyInstance } from "fastify";
import fastifyStatic from "fastify-static";
import { Settings } from "./types";
import repo from "./routes/repo";
import { join } from "path";
import { readdir } from "fs/promises";
import { exit } from "process";
import { ServerCache } from "./cache";

export default async function buildApp(settings: Settings, cache: ServerCache | null): Promise<FastifyInstance> {
	const fastify = fastifyFactory();

	fastify.setErrorHandler((err, req, reply) => {
		if(err.validation) {
			reply.code(400).send(`${err.validation[0].dataPath} ${err.validation[0].message}`);
			return;
		}

		console.log(err);
		reply.code(500).send("Internal server error!");
	});

	fastify.setNotFoundHandler({}, (req, reply) => {
		reply.code(404).send("Page not found!");
	});

	if(!settings.dev) {
		const dist_dir = join(__dirname, "/../../client/dist");

		await readdir(dist_dir).catch(() => {
			console.error("Error: Client dist directory doesn't exist!");
			exit(1);
		});

		fastify.register(fastifyStatic, { root: dist_dir });

		fastify.route({
			method: "GET",
			url: "/",
			handler: (req, reply) => {
				reply.sendFile("index.html");
			}
		});
	}

	fastify.addContentTypeParser("application/x-git-upload-pack-request", (req, payload, done) => done(null, payload));
	fastify.addContentTypeParser("application/x-git-receive-pack-request", (req, payload, done) => done(null, payload));

	fastify.register(api, { prefix: "/api/v1", config: { settings: settings, cache: cache } });
	fastify.register(repo, { prefix: "/:repo([a-zA-Z0-9\\.\\-_]+)", config: { settings: settings, cache: cache } });

	return fastify;
}