-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
79 lines (67 loc) · 2.18 KB
/
main.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
const fastify = require("fastify")({ logger: true });
const { Server, Metadata } = require("@tus/server");
const { FileStore } = require("@tus/file-store");
const crypto = require("node:crypto");
const mime_types = require("mime-types");
const CONSTANTS = {
proto: "https",
};
function ParseForwardedHeader(value) {
return value.replace(/ /g, "").split(",");
}
function getFileIdFromRequest(req) {
const reExtractFileID = /([^/]+)\/?$/;
const match = reExtractFileID.exec(req.url);
if (!match) {
return;
}
return match[1];
}
const tusServer = new Server({
path: "/files",
datastore: new FileStore({ directory: "./files" }),
// relativeLocation: true,
// respectForwardedHeaders: true,
namingFunction(req, metadata) {
const id = crypto.randomBytes(16).toString("hex");
return `${id}.${mime_types.extension(metadata.filetype)}`;
},
generateUrl(req, options) {
const { proto, host, path, id } = options;
const x_forwarded = {
host: req.headers["x-forwarded-host"],
proto: req.headers["x-forwarded-proto"],
port: req.headers["x-forwarded-port"],
metadata: req.headers["upload-metadata"],
};
if (x_forwarded.host) {
return `${ParseForwardedHeader(x_forwarded.proto)[0]}://${
ParseForwardedHeader(x_forwarded.host)[0]
}/api/drop${path}/${id}`;
}
return `${proto}://${host}${path}/${id}`;
},
});
// fastify.register(require("@fastify/cors"), {
// origin: "*",
// methods: ["GET", "POST", "PATCH", "DELETE", "OPTION"]
// });
fastify.addContentTypeParser(
"application/offset+octet-stream",
(request, payload, done) => done(null)
);
fastify.all("/files", (req, res) => {
// req.headers["x-forwarded-proto"] = CONSTANTS.proto;
tusServer.handle(req.raw, res.raw);
});
fastify.all("/files/*", async (req, res) => {
// req.headers["x-forwarded-proto"] = CONSTANTS.proto;
const extension = getFileIdFromRequest(req).split(".")[1];
const filetype = mime_types.contentType(extension);
res.header("Content-Type", filetype);
await tusServer.handle(req.raw, res.raw);
});
fastify.get("/", async (req, res) => {
return `Drop some file please ${JSON.stringify(CONSTANTS)}`;
});
exports.default = fastify;