Commit f8dd398a authored by Filipa Lacerda's avatar Filipa Lacerda

Merge branch 'ph-more-axios' into 'master'

More conversions of $.ajax to axios

See merge request gitlab-org/gitlab-ce!16731
parents 33517d54 cf4fb53f
/* eslint-disable func-names, space-before-function-paren, wrap-iife, quotes, no-var, object-shorthand, consistent-return, no-unused-vars, comma-dangle, vars-on-top, prefer-template, max-len */ /* eslint-disable func-names, space-before-function-paren, wrap-iife, quotes, no-var, object-shorthand, consistent-return, no-unused-vars, comma-dangle, vars-on-top, prefer-template, max-len */
import { localTimeAgo } from './lib/utils/datetime_utility'; import { localTimeAgo } from './lib/utils/datetime_utility';
import axios from './lib/utils/axios_utils';
export default class Compare { export default class Compare {
constructor(opts) { constructor(opts) {
...@@ -41,17 +42,14 @@ export default class Compare { ...@@ -41,17 +42,14 @@ export default class Compare {
} }
getTargetProject() { getTargetProject() {
return $.ajax({ $('.mr_target_commit').empty();
url: this.opts.targetProjectUrl,
data: { return axios.get(this.opts.targetProjectUrl, {
target_project_id: $("input[name='merge_request[target_project_id]']").val() params: {
}, target_project_id: $("input[name='merge_request[target_project_id]']").val(),
beforeSend: function() {
return $('.mr_target_commit').empty();
}, },
success: function(html) { }).then(({ data }) => {
return $('.js-target-branch-dropdown .dropdown-content').html(html); $('.js-target-branch-dropdown .dropdown-content').html(data);
}
}); });
} }
...@@ -68,22 +66,19 @@ export default class Compare { ...@@ -68,22 +66,19 @@ export default class Compare {
}); });
} }
static sendAjax(url, loading, target, data) { static sendAjax(url, loading, target, params) {
var $target; const $target = $(target);
$target = $(target);
return $.ajax({ loading.show();
url: url, $target.empty();
data: data,
beforeSend: function() { return axios.get(url, {
loading.show(); params,
return $target.empty(); }).then(({ data }) => {
}, loading.hide();
success: function(html) { $target.html(data);
loading.hide(); const className = '.' + $target[0].className.replace(' ', '.');
$target.html(html); localTimeAgo($('.js-timeago', className));
var className = '.' + $target[0].className.replace(' ', '.');
localTimeAgo($('.js-timeago', className));
}
}); });
} }
} }
/* eslint-disable func-names, space-before-function-paren, one-var, no-var, one-var-declaration-per-line, object-shorthand, comma-dangle, prefer-arrow-callback, no-else-return, newline-per-chained-call, wrap-iife, max-len */ /* eslint-disable func-names, space-before-function-paren, one-var, no-var, one-var-declaration-per-line, object-shorthand, comma-dangle, prefer-arrow-callback, no-else-return, newline-per-chained-call, wrap-iife, max-len */
import { __ } from './locale';
import axios from './lib/utils/axios_utils';
import flash from './flash';
export default function initCompareAutocomplete() { export default function initCompareAutocomplete() {
$('.js-compare-dropdown').each(function() { $('.js-compare-dropdown').each(function() {
...@@ -10,15 +13,14 @@ export default function initCompareAutocomplete() { ...@@ -10,15 +13,14 @@ export default function initCompareAutocomplete() {
const $filterInput = $('input[type="search"]', $dropdownContainer); const $filterInput = $('input[type="search"]', $dropdownContainer);
$dropdown.glDropdown({ $dropdown.glDropdown({
data: function(term, callback) { data: function(term, callback) {
return $.ajax({ axios.get($dropdown.data('refsUrl'), {
url: $dropdown.data('refs-url'), params: {
data: {
ref: $dropdown.data('ref'), ref: $dropdown.data('ref'),
search: term, search: term,
} },
}).done(function(refs) { }).then(({ data }) => {
return callback(refs); callback(data);
}); }).catch(() => flash(__('Error fetching refs')));
}, },
selectable: true, selectable: true,
filterable: true, filterable: true,
......
/* eslint-disable no-new */ /* eslint-disable no-new */
import _ from 'underscore'; import _ from 'underscore';
import axios from './lib/utils/axios_utils';
import Flash from './flash'; import Flash from './flash';
import DropLab from './droplab/drop_lab'; import DropLab from './droplab/drop_lab';
import ISetter from './droplab/plugins/input_setter'; import ISetter from './droplab/plugins/input_setter';
...@@ -74,60 +75,52 @@ export default class CreateMergeRequestDropdown { ...@@ -74,60 +75,52 @@ export default class CreateMergeRequestDropdown {
} }
checkAbilityToCreateBranch() { checkAbilityToCreateBranch() {
return $.ajax({ this.setUnavailableButtonState();
type: 'GET',
dataType: 'json', axios.get(this.canCreatePath)
url: this.canCreatePath, .then(({ data }) => {
beforeSend: () => this.setUnavailableButtonState(), this.setUnavailableButtonState(false);
})
.done((data) => { if (data.can_create_branch) {
this.setUnavailableButtonState(false); this.available();
this.enable();
if (data.can_create_branch) {
this.available(); if (!this.droplabInitialized) {
this.enable(); this.droplabInitialized = true;
this.initDroplab();
if (!this.droplabInitialized) { this.bindEvents();
this.droplabInitialized = true; }
this.initDroplab(); } else if (data.has_related_branch) {
this.bindEvents(); this.hide();
} }
} else if (data.has_related_branch) { })
this.hide(); .catch(() => {
} this.unavailable();
}).fail(() => { this.disable();
this.unavailable(); Flash('Failed to check if a new branch can be created.');
this.disable(); });
new Flash('Failed to check if a new branch can be created.');
});
} }
createBranch() { createBranch() {
return $.ajax({ this.isCreatingBranch = true;
method: 'POST',
dataType: 'json', return axios.post(this.createBranchPath)
url: this.createBranchPath, .then(({ data }) => {
beforeSend: () => (this.isCreatingBranch = true), this.branchCreated = true;
}) window.location.href = data.url;
.done((data) => { })
this.branchCreated = true; .catch(() => Flash('Failed to create a branch for this issue. Please try again.'));
window.location.href = data.url;
})
.fail(() => new Flash('Failed to create a branch for this issue. Please try again.'));
} }
createMergeRequest() { createMergeRequest() {
return $.ajax({ this.isCreatingMergeRequest = true;
method: 'POST',
dataType: 'json', return axios.post(this.createMrPath)
url: this.createMrPath, .then(({ data }) => {
beforeSend: () => (this.isCreatingMergeRequest = true), this.mergeRequestCreated = true;
}) window.location.href = data.url;
.done((data) => { })
this.mergeRequestCreated = true; .catch(() => Flash('Failed to create Merge Request. Please try again.'));
window.location.href = data.url;
})
.fail(() => new Flash('Failed to create Merge Request. Please try again.'));
} }
disable() { disable() {
...@@ -200,39 +193,33 @@ export default class CreateMergeRequestDropdown { ...@@ -200,39 +193,33 @@ export default class CreateMergeRequestDropdown {
getRef(ref, target = 'all') { getRef(ref, target = 'all') {
if (!ref) return false; if (!ref) return false;
return $.ajax({ return axios.get(this.refsPath + ref)
method: 'GET', .then(({ data }) => {
dataType: 'json', const branches = data[Object.keys(data)[0]];
url: this.refsPath + ref, const tags = data[Object.keys(data)[1]];
beforeSend: () => { let result;
this.isGettingRef = true;
}, if (target === 'branch') {
}) result = CreateMergeRequestDropdown.findByValue(branches, ref);
.always(() => { } else {
this.isGettingRef = false; result = CreateMergeRequestDropdown.findByValue(branches, ref, true) ||
}) CreateMergeRequestDropdown.findByValue(tags, ref, true);
.done((data) => { this.suggestedRef = result;
const branches = data[Object.keys(data)[0]]; }
const tags = data[Object.keys(data)[1]];
let result;
if (target === 'branch') { this.isGettingRef = false;
result = CreateMergeRequestDropdown.findByValue(branches, ref);
} else {
result = CreateMergeRequestDropdown.findByValue(branches, ref, true) ||
CreateMergeRequestDropdown.findByValue(tags, ref, true);
this.suggestedRef = result;
}
return this.updateInputState(target, ref, result); return this.updateInputState(target, ref, result);
}) })
.fail(() => { .catch(() => {
this.unavailable(); this.unavailable();
this.disable(); this.disable();
new Flash('Failed to get ref.'); new Flash('Failed to get ref.');
return false; this.isGettingRef = false;
});
return false;
});
} }
getTargetData(target) { getTargetData(target) {
...@@ -332,12 +319,12 @@ export default class CreateMergeRequestDropdown { ...@@ -332,12 +319,12 @@ export default class CreateMergeRequestDropdown {
xhr = this.createBranch(); xhr = this.createBranch();
} }
xhr.fail(() => { xhr.catch(() => {
this.isCreatingMergeRequest = false; this.isCreatingMergeRequest = false;
this.isCreatingBranch = false; this.isCreatingBranch = false;
});
xhr.always(() => this.enable()); this.enable();
});
this.disable(); this.disable();
} }
......
...@@ -2,6 +2,7 @@ import Dropzone from 'dropzone'; ...@@ -2,6 +2,7 @@ import Dropzone from 'dropzone';
import _ from 'underscore'; import _ from 'underscore';
import './preview_markdown'; import './preview_markdown';
import csrf from './lib/utils/csrf'; import csrf from './lib/utils/csrf';
import axios from './lib/utils/axios_utils';
Dropzone.autoDiscover = false; Dropzone.autoDiscover = false;
...@@ -235,25 +236,21 @@ export default function dropzoneInput(form) { ...@@ -235,25 +236,21 @@ export default function dropzoneInput(form) {
uploadFile = (item, filename) => { uploadFile = (item, filename) => {
const formData = new FormData(); const formData = new FormData();
formData.append('file', item, filename); formData.append('file', item, filename);
return $.ajax({
url: uploadsPath, showSpinner();
type: 'POST', closeAlertMessage();
data: formData,
dataType: 'json', axios.post(uploadsPath, formData)
processData: false, .then(({ data }) => {
contentType: false, const md = data.link.markdown;
headers: csrf.headers,
beforeSend: () => {
showSpinner();
return closeAlertMessage();
},
success: (e, text, response) => {
const md = response.responseJSON.link.markdown;
insertToTextArea(filename, md); insertToTextArea(filename, md);
}, closeSpinner();
error: response => showError(response.responseJSON.message), })
complete: () => closeSpinner(), .catch((e) => {
}); showError(e.response.data.message);
closeSpinner();
});
}; };
updateAttachingMessage = (files, messageContainer) => { updateAttachingMessage = (files, messageContainer) => {
......
/* global dateFormat */ /* global dateFormat */
import Pikaday from 'pikaday'; import Pikaday from 'pikaday';
import axios from './lib/utils/axios_utils';
import { parsePikadayDate, pikadayToString } from './lib/utils/datefix'; import { parsePikadayDate, pikadayToString } from './lib/utils/datefix';
class DueDateSelect { class DueDateSelect {
...@@ -125,37 +126,30 @@ class DueDateSelect { ...@@ -125,37 +126,30 @@ class DueDateSelect {
} }
submitSelectedDate(isDropdown) { submitSelectedDate(isDropdown) {
return $.ajax({ const selectedDateValue = this.datePayload[this.abilityName].due_date;
type: 'PUT', const displayedDateStyle = this.displayedDate !== 'No due date' ? 'bold' : 'no-value';
url: this.issueUpdateURL,
data: this.datePayload,
dataType: 'json',
beforeSend: () => {
const selectedDateValue = this.datePayload[this.abilityName].due_date;
const displayedDateStyle = this.displayedDate !== 'No due date' ? 'bold' : 'no-value';
this.$loading.removeClass('hidden').fadeIn(); this.$loading.removeClass('hidden').fadeIn();
if (isDropdown) { if (isDropdown) {
this.$dropdown.trigger('loading.gl.dropdown'); this.$dropdown.trigger('loading.gl.dropdown');
this.$selectbox.hide(); this.$selectbox.hide();
} }
this.$value.css('display', ''); this.$value.css('display', '');
this.$valueContent.html(`<span class='${displayedDateStyle}'>${this.displayedDate}</span>`); this.$valueContent.html(`<span class='${displayedDateStyle}'>${this.displayedDate}</span>`);
this.$sidebarValue.html(this.displayedDate); this.$sidebarValue.html(this.displayedDate);
return selectedDateValue.length ? $('.js-remove-due-date-holder').toggleClass('hidden', selectedDateValue.length);
$('.js-remove-due-date-holder').removeClass('hidden') :
$('.js-remove-due-date-holder').addClass('hidden'); return axios.put(this.issueUpdateURL, this.datePayload)
}, .then(() => {
}).done(() => { if (isDropdown) {
if (isDropdown) { this.$dropdown.trigger('loaded.gl.dropdown');
this.$dropdown.trigger('loaded.gl.dropdown'); this.$dropdown.dropdown('toggle');
this.$dropdown.dropdown('toggle'); }
} return this.$loading.fadeOut();
return this.$loading.fadeOut(); });
});
} }
} }
......
import _ from 'underscore'; import _ from 'underscore';
import axios from './lib/utils/axios_utils';
/** /**
* Makes search request for content when user types a value in the search input. * Makes search request for content when user types a value in the search input.
...@@ -54,32 +55,26 @@ export default class FilterableList { ...@@ -54,32 +55,26 @@ export default class FilterableList {
this.listFilterElement.removeEventListener('input', this.debounceFilter); this.listFilterElement.removeEventListener('input', this.debounceFilter);
} }
filterResults(queryData) { filterResults(params) {
if (this.isBusy) { if (this.isBusy) {
return false; return false;
} }
$(this.listHolderElement).fadeTo(250, 0.5); $(this.listHolderElement).fadeTo(250, 0.5);
return $.ajax({ this.isBusy = true;
url: this.getFilterEndpoint(),
data: queryData, return axios.get(this.getFilterEndpoint(), {
type: 'GET', params,
dataType: 'json', }).then((res) => {
context: this, this.onFilterSuccess(res, params);
complete: this.onFilterComplete, this.onFilterComplete();
beforeSend: () => { }).catch(() => this.onFilterComplete());
this.isBusy = true;
},
success: (response, textStatus, xhr) => {
this.onFilterSuccess(response, xhr, queryData);
},
});
} }
onFilterSuccess(response, xhr, queryData) { onFilterSuccess(response, queryData) {
if (response.html) { if (response.data.html) {
this.listHolderElement.innerHTML = response.html; this.listHolderElement.innerHTML = response.data.html;
} }
// Change url so if user reload a page - search results are saved // Change url so if user reload a page - search results are saved
......
import FilterableList from '~/filterable_list'; import FilterableList from '~/filterable_list';
import eventHub from './event_hub'; import eventHub from './event_hub';
import { getParameterByName } from '../lib/utils/common_utils'; import { normalizeHeaders, getParameterByName } from '../lib/utils/common_utils';
export default class GroupFilterableList extends FilterableList { export default class GroupFilterableList extends FilterableList {
constructor({ form, filter, holder, filterEndpoint, pagePath, dropdownSel, filterInputField }) { constructor({ form, filter, holder, filterEndpoint, pagePath, dropdownSel, filterInputField }) {
...@@ -94,23 +94,14 @@ export default class GroupFilterableList extends FilterableList { ...@@ -94,23 +94,14 @@ export default class GroupFilterableList extends FilterableList {
this.form.querySelector(`[name="${this.filterInputField}"]`).value = ''; this.form.querySelector(`[name="${this.filterInputField}"]`).value = '';
} }
onFilterSuccess(data, xhr, queryData) { onFilterSuccess(res, queryData) {
const currentPath = this.getPagePath(queryData); const currentPath = this.getPagePath(queryData);
const paginationData = {
'X-Per-Page': xhr.getResponseHeader('X-Per-Page'),
'X-Page': xhr.getResponseHeader('X-Page'),
'X-Total': xhr.getResponseHeader('X-Total'),
'X-Total-Pages': xhr.getResponseHeader('X-Total-Pages'),
'X-Next-Page': xhr.getResponseHeader('X-Next-Page'),
'X-Prev-Page': xhr.getResponseHeader('X-Prev-Page'),
};
window.history.replaceState({ window.history.replaceState({
page: currentPath, page: currentPath,
}, document.title, currentPath); }, document.title, currentPath);
eventHub.$emit('updateGroups', data, Object.prototype.hasOwnProperty.call(queryData, this.filterInputField)); eventHub.$emit('updateGroups', res.data, Object.prototype.hasOwnProperty.call(queryData, this.filterInputField));
eventHub.$emit('updatePagination', paginationData); eventHub.$emit('updatePagination', normalizeHeaders(res.headers));
} }
} }
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment