summaryrefslogtreecommitdiff
path: root/node_modules/snekfetch/src/node/FormData.js
blob: f8270e237a8c4d5620f30081fc892f15fae5d554 (plain) (blame)
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
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;