-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.js
73 lines (65 loc) · 2.06 KB
/
app.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
const express = require('express');
const logger = require('morgan');
const multer = require('multer');
const PDFImage = require('pdf-image').PDFImage;
const Joi = require('joi');
const fs = require('fs').promises;
const CronJob = require('cron').CronJob;
const app = express();
app.use(logger('dev'));
const partUpload = multer({dest: './tmp'});
app.post('/', partUpload.single('pdf'), async function (req, res) {
try {
const pdf = new PDFImage(req.file.path);
const paths = await pdf.convertFile();
res.send({
requestId: req.file.filename,
pages: paths.length
});
} catch (err) {
console.error(err);
res.status(500).send({message: 'An error has occurred.'})
}
});
app.get('/:id/:index', async function (req, res) {
const schema = Joi.object({
id: Joi.string()
.length(32)
.hex()
.required(),
index: Joi.number()
.integer()
.required()
});
try {
const {id, index} = await schema.validate(req.params);
await fs.open(`./tmp/${id}-${index}.png`, 'r');
res.sendFile(`./tmp/${id}-${index}.png`, {
root: '.'
});
} catch (err) {
if (err.isJoi && err.name === 'ValidationError') {
return res.status(400).send({message: err.message});
}
if (err.code === 'ENOENT') {
return res.status(400).send({message: 'Incorrect ID or index'});
}
console.error(err);
return res.status(500).send({message: 'An error occurred while retrieving the PDF.'});
}
});
new CronJob({
cronTime: process.env.CLEANUP_CRON || '0 0 * * * *',
onTick: async function () {
const dir = await fs.readdir('./tmp');
for (let file of dir) {
const stat = await fs.stat(`./tmp/${file}`);
if ((Date.now() - stat.birthtime) >= (process.env.TTL || 3600000)) {
await fs.unlink(`./tmp/${file}`)
}
}
},
start: true,
runOnInit: true
});
module.exports = app;