-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
64 lines (56 loc) · 1.76 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
import Fastify from 'fastify'
import formBodyPlugin from '@fastify/formbody'
import fs from 'fs'
import { exec } from 'child_process'
import { v4 as uuidv4 } from 'uuid';
console.log('[xslt] START')
const fastify = Fastify({
logger: false
})
fastify.register(formBodyPlugin)
await fastify.register(import('@fastify/rate-limit'), {
max: 10,
timeWindow: '1 minute'
})
if (!fs.existsSync('cache')) {
fs.mkdirSync('cache');
}
function clear(uuid) {
try { fs.unlinkSync(`cache/${uuid}.xml`) } catch (e) { }
try { fs.unlinkSync(`cache/${uuid}.xslt`) } catch (e) { }
try { fs.unlinkSync(`cache/${uuid}.out`) } catch (e) { }
}
fastify.post('/transform', function (req, reply) {
var uuid = uuidv4()
if (!req.body.xml || !req.body.xslt) {
reply.statusCode = 400
reply.send('Missing XML or XSLT')
return
}
fs.writeFile(`cache/${uuid}.xml`, req.body.xml, (err, file) => {
fs.writeFile(`cache/${uuid}.xslt`, req.body.xslt, (err, file) => {
if (err) {
clear()
return;
}
exec(`npx xslt3 -s:"cache/${uuid}.xml" -xsl:"cache/${uuid}.xslt" -o:"cache/${uuid}.out"`, (error, stout, stderr) => {
if (error) {
reply.statusCode = 400
reply.send(stderr.split('\n').splice(2).join('\n').trim())
clear(uuid)
return;
}
fs.readFile(`cache/${uuid}.out`, 'utf8', (err, data) => {
reply.send(data)
clear(uuid)
})
})
})
})
})
fastify.listen({ host: '0.0.0.0', port: 8080 }, function (err, address) {
if (err) {
fastify.log.error(err)
process.exit(1)
}
})