1 | /*
|
2 | Kettle Test Utilities - Forms
|
3 |
|
4 | Contains facilities for submitting multipart forms
|
5 |
|
6 | Copyright 2018 OCAD University
|
7 |
|
8 | Licensed under the New BSD license. You may not use this file except in
|
9 | compliance with this License.
|
10 |
|
11 | You may obtain a copy of the License at
|
12 | https://github.com/fluid-project/kettle/blob/master/LICENSE.txt
|
13 | */
|
14 |
|
15 | ;
|
16 |
|
17 | var fluid = require("infusion"),
|
18 | kettle = fluid.registerNamespace("kettle"),
|
19 | FormData = require("form-data"),
|
20 | fs = require("fs");
|
21 |
|
22 | fluid.registerNamespace("kettle.test");
|
23 |
|
24 | // A component that sends multipart/form-data via POST
|
25 | // using the form-data module
|
26 | // Can be used to send both files and fields
|
27 | // Used currently for testing the multer-based middleware
|
28 | //
|
29 | fluid.defaults("kettle.test.request.formData", {
|
30 | gradeNames: ["kettle.test.request.http"],
|
31 | method: "POST",
|
32 | listeners: {
|
33 | "send.sendPayload": {
|
34 | funcName: "kettle.test.request.formData.sendPayload",
|
35 | args: ["{that}", "{arguments}.0"]
|
36 | }
|
37 | },
|
38 | formData: {
|
39 | // key-value structure where key will be the appended field
|
40 | // name and the value is one of
|
41 | // 1. the path to a file to be attached
|
42 | // 2. an array of file paths
|
43 | files: {
|
44 | // "file": "./LICENSE.txt"
|
45 | // "files": "./LICENSE.txt, ./README.md"
|
46 | },
|
47 | fields: {
|
48 | // key-value structure where key will be the appended field
|
49 | // name and the value is the value to be associated
|
50 | }
|
51 | }
|
52 | });
|
53 |
|
54 | kettle.test.request.formData.sendPayload = function (that) {
|
55 |
|
56 | var requestOptions = that.options;
|
57 | var req = that.nativeRequest;
|
58 | var form = new FormData();
|
59 |
|
60 | // Append all files to form
|
61 | fluid.each(requestOptions.formData.files, function (filePath, fieldKey) {
|
62 | var filePaths = fluid.makeArray(filePath);
|
63 | filePaths.forEach(function (filePath) {
|
64 | var resolved = fluid.module.resolvePath(filePath);
|
65 | form.append(fieldKey, fs.createReadStream(resolved));
|
66 | });
|
67 | });
|
68 |
|
69 | // Append all fields to form
|
70 | fluid.each(requestOptions.formData.fields, function (fieldValue, fieldKey) {
|
71 | form.append(fieldKey, fieldValue);
|
72 | });
|
73 |
|
74 | // Set the request headers from the form
|
75 | var formHeaders = form.getHeaders();
|
76 |
|
77 | fluid.each(formHeaders, function (value, name) {
|
78 | req.setHeader(name, value);
|
79 | });
|
80 |
|
81 | // Calculate the length and set the header,
|
82 | // then send the request; we need to do this
|
83 | // using the async method, as noted at
|
84 | // https://github.com/form-data/form-data#notes
|
85 |
|
86 | form.getLength(function (arg1, knownLength) {
|
87 | req.setHeader("Content-Length", knownLength);
|
88 | form.pipe(req);
|
89 | });
|
90 | };
|