-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
90 lines (79 loc) · 2.45 KB
/
index.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
80
81
82
83
84
85
86
87
88
89
90
"use strict";
const { fromBuffer } = require("file-type");
// Import plugins
const cors = require("@fastify/cors");
const pdfToHtml = require("../../../plugins/pdf-to-html");
const { pdfToHtmlPostSchema } = require("./schema");
// Cache supported media types so not having to navigate schema object each time
const accepts = Object.keys(pdfToHtmlPostSchema.response[200].content);
/**
* @author Frazer Smith
* @description Sets routing options for server.
* @param {import("fastify").FastifyInstance} server - Fastify instance.
* @param {object} options - Route config values.
* @param {*} [options.bearerTokenAuthKeys] - Apply `bearerToken` security scheme to route if defined.
* @param {import("@fastify/cors").FastifyCorsOptions} options.cors - CORS settings.
* @param {object} options.poppler - PDF-to-HTML plugin settings.
*/
async function route(server, options) {
if (options.bearerTokenAuthKeys) {
pdfToHtmlPostSchema.security = [{ bearerToken: [] }];
pdfToHtmlPostSchema.response[401] = {
$ref: "responses#/properties/unauthorized",
description: "Unauthorized",
};
}
server.addContentTypeParser(
pdfToHtmlPostSchema.consumes,
{ parseAs: "buffer" },
async (_req, payload) => {
if (payload.length === 0) {
throw server.httpErrors.badRequest("Body cannot be empty");
}
/**
* The Content-Type header can be spoofed so is not trusted implicitly,
* this checks for PDF specific magic numbers.
*/
const results = await fromBuffer(payload);
if (!pdfToHtmlPostSchema.consumes.includes(results?.mime)) {
throw server.httpErrors.unsupportedMediaType();
}
return payload;
}
);
// Register plugins
await server
// Enable CORS if options passed
.register(cors, {
...options.cors,
methods: ["POST"],
})
.register(pdfToHtml, options.poppler);
server.route({
method: "POST",
url: "/",
schema: pdfToHtmlPostSchema,
onRequest: async (req) => {
if (
// Catch unsupported Accept header media types
!req.accepts().type(accepts)
) {
throw server.httpErrors.notAcceptable();
}
},
handler: async (req) => {
const embeddedHtml = await server.embedHtmlImages(
req.conversionResults.body
);
const tidiedHtml = await server.tidyHtml(embeddedHtml, {
language: req.query.language,
removeAlt: req.query.removeAlt,
});
return server.tidyCss(tidiedHtml, {
fonts: req.query.fonts,
backgroundColor: req.query.backgroundColor,
});
},
});
}
module.exports = route;