diff options
| author | 8cy <[email protected]> | 2020-04-03 02:37:42 -0700 |
|---|---|---|
| committer | 8cy <[email protected]> | 2020-04-03 02:37:42 -0700 |
| commit | 60867fb030bae582082340ead7dbc7efdc2f5398 (patch) | |
| tree | 4c6a7356351be2e4914e15c4703172597c45656e /node_modules/snekfetch/src/node/FormData.js | |
| parent | commenting (diff) | |
| download | s5nical-60867fb030bae582082340ead7dbc7efdc2f5398.tar.xz s5nical-60867fb030bae582082340ead7dbc7efdc2f5398.zip | |
2020/04/03, 02:34, v1.2.0
Diffstat (limited to 'node_modules/snekfetch/src/node/FormData.js')
| -rw-r--r-- | node_modules/snekfetch/src/node/FormData.js | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/node_modules/snekfetch/src/node/FormData.js b/node_modules/snekfetch/src/node/FormData.js new file mode 100644 index 0000000..f8270e2 --- /dev/null +++ b/node_modules/snekfetch/src/node/FormData.js @@ -0,0 +1,51 @@ +const path = require('path'); +const mime = require('./mime'); + +class FormData { + constructor() { + this.boundary = `--snekfetch--${Math.random().toString().slice(2, 7)}`; + this.buffers = []; + } + + append(name, data, filename) { + if (typeof data === 'undefined') + return; + let str = `\r\n--${this.boundary}\r\nContent-Disposition: form-data; name="${name}"`; + let mimetype = null; + if (filename) { + str += `; filename="${filename}"`; + mimetype = 'application/octet-stream'; + const extname = path.extname(filename).slice(1); + if (extname) + mimetype = mime.lookup(extname); + } + + if (data instanceof Buffer) { + mimetype = mime.buffer(data); + } else if (typeof data === 'object') { + mimetype = 'application/json'; + data = Buffer.from(JSON.stringify(data)); + } else { + data = Buffer.from(String(data)); + } + + if (mimetype) + str += `\r\nContent-Type: ${mimetype}`; + this.buffers.push(Buffer.from(`${str}\r\n\r\n`)); + this.buffers.push(data); + } + + getBoundary() { + return this.boundary; + } + + end() { + return Buffer.concat([...this.buffers, Buffer.from(`\r\n--${this.boundary}--`)]); + } + + get length() { + return this.buffers.reduce((sum, b) => sum + Buffer.byteLength(b), 0); + } +} + +module.exports = FormData; |