react-web-native-sketch
Version:
[TODO: We need an overview of how this can be used via npm vs as a local package]
70 lines • 3.54 kB
JavaScript
;
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
require("whatwg-fetch");
var navigation_1 = require("./reducers/navigation");
exports.postFormDataMiddleware = function (baseUrl, baseHeaders) {
if (baseHeaders === void 0) { baseHeaders = {}; }
return function (_a) {
var dispatch = _a.dispatch, getState = _a.getState;
return function (next) { return function (action) {
var formTypes = action.formTypes, _a = action.payload, payload = _a === void 0 ? {} : _a, _b = action.data, data = _b === void 0 ? {} : _b, _c = action.requestPayload, requestPayload = _c === void 0 ? {} : _c, _d = action.successPayload, successPayload = _d === void 0 ? {} : _d, dispatchOnSuccess = action.dispatchOnSuccess, _e = action.failurePayload, failurePayload = _e === void 0 ? {} : _e, dispatchOnFailure = action.dispatchOnFailure;
if (!formTypes) {
// Normal action: pass it on
return next(action);
}
if (!Array.isArray(formTypes) ||
formTypes.length !== 3 || !formTypes.every(function (type) { return typeof type === 'string'; })) {
throw new Error('Expected an array of three string types.');
}
var requestType = formTypes[0], successType = formTypes[1], failureType = formTypes[2];
dispatch(Object.assign({}, payload, __assign({ type: requestType }, requestPayload)));
var headers = {};
var formData = new FormData();
for (var name_1 in data) {
formData.append(name_1, data[name_1]);
}
var fetchParams = {
// mode: 'no-cors',
method: 'POST',
headers: headers,
body: formData,
};
return fetch(baseUrl, fetchParams)
.then(function (response) {
var actionType = failureType, payload = failurePayload;
if (response.status >= 200 && response.status < 300) {
actionType = successType;
payload = successPayload;
dispatchOnSuccess && dispatch(dispatchOnSuccess);
}
else {
dispatch(navigation_1.showAlert('API_ERROR'));
dispatchOnFailure && dispatch(dispatchOnFailure);
}
var responseData = {
error: actionType !== successType ? 'FAILED_TO_UPLOAD_S3' : '',
// formName: formName,
// fieldName: fieldName,
// url: AWS_S3 + data['key'],
url: data['key'],
};
dispatch(Object.assign({}, payload, __assign({ response: responseData, type: actionType }, payload)));
}).catch(function (error) {
// TODO add bugsnag here
console.log('error');
console.log(error);
dispatch(__assign({ type: failureType, response: { error: error } }, failurePayload));
dispatchOnFailure && dispatch(dispatchOnFailure);
});
}; };
};
};
//# sourceMappingURL=postFormDataMiddleware.js.map