|
1 | 1 | const axios = require('axios'); |
| 2 | +const contentTypeParser = require('content-type'); |
2 | 3 | const { maybeParseBody } = require('./body_parser'); |
3 | 4 | const { |
4 | 5 | isNode, |
@@ -28,10 +29,46 @@ class InvalidResponseBodyError extends Error { |
28 | 29 | */ |
29 | 30 | function serializeRequest(config) { |
30 | 31 | const [defaultTransform] = axios.defaults.transformRequest; |
31 | | - config.data = defaultTransform(config.data, config.headers); |
| 32 | + |
| 33 | + // The function not only serializes data, but it also adds correct headers. |
| 34 | + const data = defaultTransform(config.data, config.headers); |
| 35 | + |
| 36 | + // Actor inputs can include functions and we don't want to omit those, |
| 37 | + // because it's convenient for users. JSON.stringify removes them. |
| 38 | + // It's a bit inefficient that we serialize the JSON twice, but I feel |
| 39 | + // it's a small price to pay. The axios default transform does a lot |
| 40 | + // of body type checks and we would have to copy all of them to the resource clients. |
| 41 | + if (config.stringifyFunctions) { |
| 42 | + const contentTypeHeader = config.headers['Content-Type'] || config.headers['content-type']; |
| 43 | + try { |
| 44 | + const { type } = contentTypeParser.parse(contentTypeHeader); |
| 45 | + if (type === 'application/json') { |
| 46 | + config.data = stringifyWithFunctions(config.data); |
| 47 | + } else { |
| 48 | + config.data = data; |
| 49 | + } |
| 50 | + } catch (err) { |
| 51 | + config.data = data; |
| 52 | + } |
| 53 | + } else { |
| 54 | + config.data = data; |
| 55 | + } |
| 56 | + |
32 | 57 | return config; |
33 | 58 | } |
34 | 59 |
|
| 60 | +/** |
| 61 | + * JSON.stringify() that serializes functions to string instead |
| 62 | + * of replacing them with null or removing them. |
| 63 | + * @param {object} obj |
| 64 | + * @return {string} |
| 65 | + */ |
| 66 | +function stringifyWithFunctions(obj) { |
| 67 | + return JSON.stringify(obj, (key, value) => { |
| 68 | + return typeof value === 'function' ? value.toString() : value; |
| 69 | + }); |
| 70 | +} |
| 71 | + |
35 | 72 | /** |
36 | 73 | * @param {object} config |
37 | 74 | * @return {Promise<object>} |
|
0 commit comments