UNPKG

3.35 kBJavaScriptView Raw
1'use strict';
2
3const debug = require('debug')('grown:test');
4
5const path = require('path');
6const fs = require('fs');
7
8module.exports = Grown => {
9 function _fixRequest(url, method, options) {
10 options = options || {};
11 options.url = url || options.url || '/';
12 options.method = (method || options.method || 'get').toUpperCase();
13 options.headers = options.headers || {};
14
15 if (options.headers['content-type']) {
16 options.body = options.body || '';
17
18 if (options.body && typeof options.body === 'object' && options.headers['content-type'] === 'multipart/form-data') {
19 const _boundary = Math.random().toString(36);
20
21 options.headers['content-type'] = `multipart/form-data; boundary=${_boundary}`;
22
23 const _input = Object.keys(options.body).map(key => ({ key, value: options.body[key] }))
24 .concat((options.attachments || []).map(file => ({ key: file.name, value: file.path, upload: true })));
25
26 options.body = _input.map(field => {
27 if (field.upload) {
28 const filename = path.basename(field.value);
29
30 return Buffer.concat([
31 Buffer.from(`--${_boundary}\r\nContent-Disposition: form-data; name="${field.key}"; filename="${filename}"\r\n`, 'ascii'),
32 Buffer.from(`Content-Type: ${field.type || 'binary/octet-stream'}\r\n\r\n`, 'ascii'),
33 Buffer.from(fs.readFileSync(field.value), 'ascii'),
34 ]);
35 }
36
37 return Buffer.from(`--${_boundary}\r\nContent-Disposition: form-data; name="${field.key}"\r\n\r\n${
38 typeof field.value === 'object' ? JSON.stringify(field.value) : field.value
39 }`, 'ascii');
40 }).join('\r\n');
41
42 options.body += `\r\n--${_boundary}--`;
43 }
44
45 if (options.body && options.headers['content-type'] === 'application/json') {
46 options.body = typeof options.body !== 'string' ? JSON.stringify(options.body) : options.body;
47 }
48
49 if (options.body) {
50 options.headers['content-length'] = options.body.length;
51 }
52 }
53
54 return options;
55 }
56
57 return Grown('Test.Request', {
58 // export heleprs
59 _fixRequest,
60
61 $install(ctx) {
62 return {
63 methods: {
64 request(url, method, options, callback) {
65 if (typeof url === 'function') {
66 callback = url;
67 url = undefined;
68 }
69
70 if (typeof url === 'object') {
71 options = url;
72 url = undefined;
73 }
74
75 if (typeof method === 'function') {
76 callback = method;
77 method = undefined;
78 }
79
80 if (typeof method === 'object') {
81 callback = options;
82 options = method;
83 method = options.method || 'GET';
84 }
85
86 if (typeof options === 'function') {
87 callback = options;
88 options = undefined;
89 }
90
91 if (typeof callback !== 'function') {
92 throw new Error(`Expecting a function, given '${JSON.stringify(callback)}'`);
93 }
94
95 debug('#%s Request %s %s', process.pid, (method || 'GET').toUpperCase(), url);
96
97 options = this._fixRequest(url, method, options);
98
99 return ctx.run(options, callback);
100 },
101 },
102 };
103 },
104 });
105};