const axios = require('axios');
const ui = require('../ui/common');
const utils = require('../utils');
const status_codes = require('http-status-codes');
const STATUS_CODES = status_codes.StatusCodes;
const methods = ["get", "post", "delete"].reduce((exp, method) => ({
...exp,
[method]: function (path, data, options) {
options = Object.assign({
acceptable_status_codes: [STATUS_CODES.OK]
}, options || {});
console.log(method, "to /api" + path, "with options", options);
return axios[method](`/api${path}`, data).catch(function (axios_error) {
logger.error(axios_error);
return Promise.reject({
message: axios_error.response.data || "Server Error",
color: "red"
});
}).then(function (response) {
console.log(response.data);
if (options.acceptable_status_codes.includes(response.data.status)) {
return response.data;
}
return Promise.reject(response.data);
});
}
}), {
status: STATUS_CODES,
handle_error_message: function (error) {
if (typeof error === "string") {
ui.show_banner({
message: error,
color: "red"
});
} else {
ui.show_banner(error);
}
}
});
module.exports = {
...methods,
on_submit: function (path, field_wrappers, value_conversions, value_validators, on_response) {
on_response = on_response || (x => x);
field_wrappers.forEach(function ($field_wrapper) {
$field_wrapper.find('button:not([disabled])').on('click', function () {
const data = {};
$field_wrapper.find('input,select').each(function (i, input) {
let value_conversion = value_conversions[input.name] || (x => x);
if (input.name === "id") {
if (input.value === "") {
return;
}
value_conversion = x => parseInt(x);
}
data[input.name] = value_conversion(input.value);
});
utils.validate.keys(data, value_validators).then(function (data) {
return methods.post(path, data);
}).then(function (data) {
ui.show_banner({
message: data.message
});
return data;
}).then(on_response).catch(methods.handle_error_message);
});
});
}
};