|
| 1 | +/* |
| 2 | +MIT License |
| 3 | +
|
| 4 | +Copyright (c) 2022 Dmitry Dutikov |
| 5 | +
|
| 6 | +Permission is hereby granted, free of charge, to any person obtaining a copy |
| 7 | +of this software and associated documentation files (the "Software"), to deal |
| 8 | +in the Software without restriction, including without limitation the rights |
| 9 | +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 10 | +copies of the Software, and to permit persons to whom the Software is |
| 11 | +furnished to do so, subject to the following conditions: |
| 12 | +
|
| 13 | +The above copyright notice and this permission notice shall be included in all |
| 14 | +copies or substantial portions of the Software. |
| 15 | +
|
| 16 | +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 17 | +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 18 | +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 19 | +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 20 | +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, |
| 21 | +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE |
| 22 | +SOFTWARE. |
| 23 | + */ |
| 24 | + |
| 25 | +const zlib = require('zlib'); |
| 26 | +const { JSON22 } = require('json22'); |
| 27 | +const { Buffer } = require('buffer'); |
| 28 | +const { pipeline } = require('stream'); |
| 29 | +const { MediaType } = require('./media-type'); |
| 30 | +const { Json22Parser } = require('./json22-parser'); |
| 31 | + |
| 32 | +const JSON22_MEDIA_TYPE = MediaType.parse(JSON22.mimeType); |
| 33 | +const JSON_MEDIA_TYPE = MediaType.parse('application/json'); |
| 34 | +const DEFAULT_CHARSET = 'utf-8'; |
| 35 | +const SUPPORTED_CHARSETS = ['utf-8', 'utf8', 'utf-16', 'utf16', 'utf-32', 'utf32']; |
| 36 | +const SUPPORTED_ENCODINGS = ['deflate', 'gzip', 'br', 'identity']; |
| 37 | + |
| 38 | +const HTTP_PAYLOAD_TOO_LARGE = 413; |
| 39 | +const HTTP_UNSUPPORTED_MEDIA_TYPE = 415; |
| 40 | + |
| 41 | +const JSON22_WAS_HERE = Symbol(); |
| 42 | + |
| 43 | +/** |
| 44 | + * @param {Json22ExpressOptions} [options = {}] |
| 45 | + * */ |
| 46 | +function json22express(options = {}) { |
| 47 | + |
| 48 | + const SUPPORTED_MEDIA_TYPE = [JSON22_MEDIA_TYPE]; |
| 49 | + if (options.handleJson) { |
| 50 | + SUPPORTED_MEDIA_TYPE.push(JSON_MEDIA_TYPE); |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * @param {IncomingMessage} req |
| 55 | + * @param {ServerResponse} res |
| 56 | + * @param {Function} next |
| 57 | + * */ |
| 58 | + async function json22Middleware (req, res, next) { |
| 59 | + |
| 60 | + if (req[JSON22_WAS_HERE] === true) { |
| 61 | + next(new Error('Duplicated json22 middleware on the pipe')); |
| 62 | + return; |
| 63 | + } |
| 64 | + |
| 65 | + req[JSON22_WAS_HERE] = true; |
| 66 | + |
| 67 | + res.json22 = function (obj) { |
| 68 | + const serialized = JSON22.stringify(obj, options.json22StringifyOptions); |
| 69 | + res.set('Content-Type', JSON22.mimeType); |
| 70 | + return res.send(serialized); |
| 71 | + } |
| 72 | + |
| 73 | + if (options.overrideResponseJsonMethod) { |
| 74 | + res.json = function (obj) { |
| 75 | + if (arguments.length > 1) { |
| 76 | + throw new Error('Too much arguments'); |
| 77 | + } |
| 78 | + return res.json22(obj); |
| 79 | + } |
| 80 | + } |
| 81 | + |
| 82 | + if (req.headers['transfer-encoding'] == null && (req.headers['content-length'] == null || req.headers['content-length'] === '0')) { |
| 83 | + next(); |
| 84 | + return; |
| 85 | + } |
| 86 | + |
| 87 | + const contentLength = Number(req.headers['content-length']); |
| 88 | + if (options.maxContentLength != null && contentLength > options.maxContentLength) { |
| 89 | + res.status(HTTP_PAYLOAD_TOO_LARGE).send('Payload too large'); |
| 90 | + return; |
| 91 | + } |
| 92 | + |
| 93 | + const ct = MediaType.parse(req.headers['content-type'] ?? ''); |
| 94 | + if (SUPPORTED_MEDIA_TYPE.some(mt => ct.match(mt))) { |
| 95 | + const charset = ct.parameters.charset?.toLowerCase() ?? DEFAULT_CHARSET; |
| 96 | + if (Buffer.isEncoding(charset) && SUPPORTED_CHARSETS.some(enc => enc === charset)) { |
| 97 | + const encoding = req.headers['content-encoding']?.toLowerCase() ?? 'identity'; |
| 98 | + if (SUPPORTED_ENCODINGS.some(enc => enc === encoding)) { |
| 99 | + const streams = [req]; |
| 100 | + switch (encoding) { |
| 101 | + case 'deflate': streams.push(zlib.createInflate()); break; |
| 102 | + case 'gzip': streams.push(zlib.createGunzip()); break; |
| 103 | + case 'br': streams.push(zlib.createBrotliDecompress()); break; |
| 104 | + case 'identity': |
| 105 | + default: |
| 106 | + break; |
| 107 | + } |
| 108 | + streams.push(new Json22Parser(req, charset, options.maxContentLength, options.keepRawAs, options.json22ParseOptions)); |
| 109 | + await pipeline(...streams, err => { |
| 110 | + if (err == null) { |
| 111 | + next(); |
| 112 | + } else { |
| 113 | + res.status(HTTP_UNSUPPORTED_MEDIA_TYPE).send(`Wrong content encoding: ${err.code ?? err.message}`); |
| 114 | + } |
| 115 | + }); |
| 116 | + } else { |
| 117 | + res.status(HTTP_UNSUPPORTED_MEDIA_TYPE).send(`Unsupported content encoding "${encoding}"`); |
| 118 | + } |
| 119 | + } else { |
| 120 | + res.status(HTTP_UNSUPPORTED_MEDIA_TYPE).send(`Unsupported charset "${ct.parameters.charset}"`); |
| 121 | + } |
| 122 | + } else { |
| 123 | + next(); |
| 124 | + } |
| 125 | + |
| 126 | + } |
| 127 | + |
| 128 | + return json22Middleware; |
| 129 | +} |
| 130 | + |
| 131 | +module.exports = { json22express }; |
0 commit comments