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
|
import { FastifyPluginCallback } from "fastify";
import { Repository } from "../../../git/repository";
import { FastifyPluginOptions, Route } from "../../../types/fastify";
import repo from "./repo";
import { verifyRepoName } from "../util";
import { Info as APIInfo } from "api";
import { ServerError } from "../../../git/error";
import { getRepositories, getRepository } from "./data";
import { sources } from "../../../cache";
const reposEndpoints: FastifyPluginCallback<FastifyPluginOptions> = (fastify, opts, done) => {
fastify.route({
method: "GET",
url: "/repos",
handler: async(req, reply) => {
const repositories = await Repository.openAll(opts.config.settings.git_dir);
reply.send({
data: await (opts.config.cache
? opts.config.cache.receive(sources.RepositoriesSource, repositories)
: getRepositories(repositories))
});
}
});
fastify.route<Route>({
method: "GET",
url: "/repos/:repo",
schema: {
params: {
repo: { type: "string" }
}
},
handler: async(req, reply) => {
if(!verifyRepoName(req.params.repo)) {
reply.code(400).send({ error: "Bad request" });
return;
}
const repository = await Repository.open(opts.config.settings.git_dir, req.params.repo).catch((err: ServerError) => err);
if(repository instanceof ServerError) {
reply.code(repository.code).send({ error: repository.message });
return;
}
reply.send({
data: await (opts.config.cache
? opts.config.cache.receive(sources.RepositorySource, repository)
: getRepository(repository))
});
}
});
done();
};
const api: FastifyPluginCallback<FastifyPluginOptions> = (fastify, opts, done) => {
fastify.setErrorHandler((err, req, reply) => {
if(err.validation) {
reply.code(400).send({ error: `${err.validation[0].dataPath} ${err.validation[0].message}` });
return;
}
console.log(err);
reply.code(500).send({ error: "Internal server error!" });
});
fastify.setNotFoundHandler((req, reply) => {
reply.code(404).send({ error: "Endpoint not found!" });
});
fastify.route({
method: "GET",
url: "/info",
handler: (req, reply) => {
const data: APIInfo = {
title: opts.config.settings.title,
about: opts.config.settings.about
};
reply.send({ data: data });
}
});
fastify.register(reposEndpoints, { config: opts.config });
fastify.register(repo, { prefix: "/repos/:repo", config: opts.config });
done();
};
export default api;
|