-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathindex.js
70 lines (61 loc) · 2.09 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
'use strict';
const fp = require('fastify-plugin');
const fxp = require('fast-xml-parser');
const defaults = {
contentType: ["text/xml", "application/xml", "application/rss+xml"],
validate: false
}
function xmlBodyParserPlugin(fastify, options, next) {
const opts = Object.assign({}, defaults, options || {})
function contentParser(req, payload, done) {
const xmlParser = new fxp.XMLParser(opts);
const parsingOpts = opts;
let body = ''
payload.on('error', errorListener)
payload.on('data', dataListener)
payload.on('end', endListener)
function errorListener (err) {
done(err)
}
function endListener () {
if (parsingOpts.validate) {
const result = fxp.XMLValidator.validate(body, parsingOpts);
if (result.err) {
const invalidFormat = new Error('Invalid Format: ' + result.err.msg);
invalidFormat.statusCode = 400;
payload.removeListener('error', errorListener);
payload.removeListener('data', dataListener);
payload.removeListener('end', endListener);
done(invalidFormat);
} else {
handleParseXml(body);
}
} else {
handleParseXml(body);
}
}
function dataListener(data) {
body = body + data;
}
function handleParseXml(body) {
try {
done(null, xmlParser.parse(body));
} catch (err) {
done(err);
}
}
}
if(typeof opts.contentType === "string"){
fastify.addContentTypeParser(opts.contentType, contentParser);
//console.log(fastify.hasContentTypeParser(opts.contentType));
}else{
for(var i=0; i< opts.contentType.length; i++){
fastify.addContentTypeParser(opts.contentType[i], contentParser);
}
}
next();
}
module.exports = fp(xmlBodyParserPlugin, {
fastify: '>=3.0.0',
name: 'fastify-xml-body-parser'
})