refactor: api module returns promise, error-first cb if cb passed in

no more separate onSuccess onError callbacks

/cc @baris
v1.18.x
Julian Lam 4 years ago
parent d52992de1b
commit a784d10fff

@ -44,7 +44,7 @@ define('admin/manage/admins-mods', [
}); });
autocomplete.user($('#global-mod-search'), function (ev, ui) { autocomplete.user($('#global-mod-search'), function (ev, ui) {
api.put('/groups/global-moderators/membership/' + ui.item.user.uid, undefined, () => { api.put('/groups/global-moderators/membership/' + ui.item.user.uid, () => {
app.alertSuccess('[[admin/manage/users:alerts.make-global-mod-success]]'); app.alertSuccess('[[admin/manage/users:alerts.make-global-mod-success]]');
$('#global-mod-search').val(''); $('#global-mod-search').val('');
@ -56,7 +56,7 @@ define('admin/manage/admins-mods', [
$('.global-moderator-area').prepend(html); $('.global-moderator-area').prepend(html);
$('#no-global-mods-warning').addClass('hidden'); $('#no-global-mods-warning').addClass('hidden');
}); });
}, 'default'); });
}); });
$('.global-moderator-area').on('click', '.remove-user-icon', function () { $('.global-moderator-area').on('click', '.remove-user-icon', function () {
@ -65,13 +65,13 @@ define('admin/manage/admins-mods', [
bootbox.confirm('[[admin/manage/users:alerts.confirm-remove-global-mod]]', function (confirm) { bootbox.confirm('[[admin/manage/users:alerts.confirm-remove-global-mod]]', function (confirm) {
if (confirm) { if (confirm) {
api.del('/groups/global-moderators/membership/' + uid, undefined, () => { api.del('/groups/global-moderators/membership/' + uid).then(() => {
app.alertSuccess('[[admin/manage/users:alerts.remove-global-mod-success]]'); app.alertSuccess('[[admin/manage/users:alerts.remove-global-mod-success]]');
userCard.remove(); userCard.remove();
if (!$('.global-moderator-area').children().length) { if (!$('.global-moderator-area').children().length) {
$('#no-global-mods-warning').removeClass('hidden'); $('#no-global-mods-warning').removeClass('hidden');
} }
}, 'default'); });
} }
}); });
}); });

@ -196,15 +196,9 @@ define('admin/manage/categories', [
}; };
Categories.toggle = function (cids, disabled) { Categories.toggle = function (cids, disabled) {
var requests = cids.map(function (cid) { Promise.all(cids.map(cid => api.put('/categories/' + cid, {
return api.put('/categories/' + cid, { disabled: disabled ? 1 : 0,
disabled: disabled ? 1 : 0, })));
});
});
$.when(requests).fail(function (ev) {
app.alertError(ev.responseJSON.status.message);
});
}; };
function itemDidAdd(e) { function itemDidAdd(e) {
@ -234,9 +228,7 @@ define('admin/manage/categories', [
newCategoryId = -1; newCategoryId = -1;
Object.keys(modified).forEach(function (cid) { Object.keys(modified).map(cid => api.put('/categories/' + cid, modified[cid]));
api.put('/categories/' + cid, modified[cid]);
});
} }
} }

@ -49,17 +49,15 @@ define('admin/manage/category', [
} }
var cid = ajaxify.data.category.cid; var cid = ajaxify.data.category.cid;
api.put('/categories/' + cid, updateHash, (res) => { api.put('/categories/' + cid, updateHash).then((res) => {
app.flags._unsaved = false; app.flags._unsaved = false;
app.alert({ app.alert({
title: 'Updated Categories', title: 'Updated Categories',
message: 'Category "' + res.name + '" was successfully updated.', message: 'Category "' + res.name + '" was successfully updated.',
type: 'success', type: 'success',
timeout: 2000, timeout: 5000,
}); });
updateHash = {}; updateHash = {};
}, (err) => {
app.alertError(err.status.message);
}); });
return false; return false;
@ -98,15 +96,13 @@ define('admin/manage/category', [
}); });
}, 1000); }, 1000);
api.del('/categories/' + ajaxify.data.category.cid, undefined, () => { api.del('/categories/' + ajaxify.data.category.cid).then(() => {
if (intervalId) { if (intervalId) {
clearInterval(intervalId); clearInterval(intervalId);
} }
modal.modal('hide'); modal.modal('hide');
app.alertSuccess('[[admin/manage/categories:alert.purge-success]]'); app.alertSuccess('[[admin/manage/categories:alert.purge-success]]');
ajaxify.go('admin/manage/categories'); ajaxify.go('admin/manage/categories');
}, (err) => {
app.alertError(err.status.message);
}); });
return false; return false;
@ -215,12 +211,10 @@ define('admin/manage/category', [
$('button[data-action="removeParent"]').on('click', function () { $('button[data-action="removeParent"]').on('click', function () {
api.put('/categories/' + ajaxify.data.category.cid, { api.put('/categories/' + ajaxify.data.category.cid, {
parentCid: 0, parentCid: 0,
}, () => { }).then(() => {
$('button[data-action="removeParent"]').parent().addClass('hide'); $('button[data-action="removeParent"]').parent().addClass('hide');
$('button[data-action="changeParent"]').parent().addClass('hide'); $('button[data-action="changeParent"]').parent().addClass('hide');
$('button[data-action="setParent"]').removeClass('hide'); $('button[data-action="setParent"]').removeClass('hide');
}, (err) => {
app.alertError(err.message);
}); });
}); });
$('button[data-action="toggle"]').on('click', function () { $('button[data-action="toggle"]').on('click', function () {
@ -228,12 +222,10 @@ define('admin/manage/category', [
var disabled = $this.attr('data-disabled') === '1'; var disabled = $this.attr('data-disabled') === '1';
api.put('/categories/' + ajaxify.data.category.cid, { api.put('/categories/' + ajaxify.data.category.cid, {
disabled: disabled ? 0 : 1, disabled: disabled ? 0 : 1,
}, () => { }).then(() => {
$this.translateText(!disabled ? '[[admin/manage/categories:enable]]' : '[[admin/manage/categories:disable]]'); $this.translateText(!disabled ? '[[admin/manage/categories:enable]]' : '[[admin/manage/categories:disable]]');
$this.toggleClass('btn-primary', !disabled).toggleClass('btn-danger', disabled); $this.toggleClass('btn-primary', !disabled).toggleClass('btn-danger', disabled);
$this.attr('data-disabled', disabled ? 0 : 1); $this.attr('data-disabled', disabled ? 0 : 1);
}, (err) => {
app.alertError(err.message);
}); });
}); });
}; };
@ -285,7 +277,7 @@ define('admin/manage/category', [
categorySelector.modal(categories, function (parentCid) { categorySelector.modal(categories, function (parentCid) {
api.put('/categories/' + ajaxify.data.category.cid, { api.put('/categories/' + ajaxify.data.category.cid, {
parentCid: parentCid, parentCid: parentCid,
}, () => { }).then(() => {
var parent = allCategories.filter(function (category) { var parent = allCategories.filter(function (category) {
return category && parseInt(category.cid, 10) === parseInt(parentCid, 10); return category && parseInt(category.cid, 10) === parseInt(parentCid, 10);
}); });
@ -295,8 +287,6 @@ define('admin/manage/category', [
$('button[data-action="setParent"]').addClass('hide'); $('button[data-action="setParent"]').addClass('hide');
var buttonHtml = '<i class="fa ' + parent.icon + '"></i> ' + parent.name; var buttonHtml = '<i class="fa ' + parent.icon + '"></i> ' + parent.name;
$('button[data-action="changeParent"]').html(buttonHtml).parent().removeClass('hide'); $('button[data-action="changeParent"]').html(buttonHtml).parent().removeClass('hide');
}, (err) => {
app.alertError(err.message);
}); });
}); });
}); });

@ -128,9 +128,9 @@ define('admin/manage/group', [
if (!confirm) { if (!confirm) {
return; return;
} }
api.del('/groups/' + ajaxify.data.group.slug + '/membership/' + uid, undefined, () => { api.del('/groups/' + ajaxify.data.group.slug + '/membership/' + uid).then(() => {
userRow.slideUp().remove(); userRow.slideUp().remove();
}, 'default'); });
}); });
break; break;
default: default:

@ -44,7 +44,7 @@ define('admin/manage/groups', [
ajaxify.go('admin/manage/groups/' + response.name); ajaxify.go('admin/manage/groups/' + response.name);
}); });
createModal.modal('hide'); createModal.modal('hide');
}, (err) => { }).catch((err) => {
if (!utils.hasLanguageKey(err.status.message)) { if (!utils.hasLanguageKey(err.status.message)) {
err.status.message = '[[admin/manage/groups:alerts.create-failure]]'; err.status.message = '[[admin/manage/groups:alerts.create-failure]]';
} }

@ -24,9 +24,9 @@ define('admin/manage/uploads', ['uploader', 'api'], function (uploader, api) {
api.del('/files', { api.del('/files', {
path: file.attr('data-path'), path: file.attr('data-path'),
}, () => { }).then(() => {
file.remove(); file.remove();
}, 'default'); });
}); });
}); });
}; };

@ -40,7 +40,7 @@ define('admin/manage/users', [
$('.users-table [component="user/select/single"]:checked').parents('.user-row').remove(); $('.users-table [component="user/select/single"]:checked').parents('.user-row').remove();
} }
// use onSuccess/onFail instead // use onSuccess instead
function done(successMessage, className, flag) { function done(successMessage, className, flag) {
return function (err) { return function (err) {
if (err) { if (err) {
@ -62,10 +62,6 @@ define('admin/manage/users', [
unselectAll(); unselectAll();
} }
function onFail(err) {
app.alertError(err.message);
}
$('[component="user/select/all"]').on('click', function () { $('[component="user/select/all"]').on('click', function () {
$('.users-table [component="user/select/single"]').prop('checked', $(this).is(':checked')); $('.users-table [component="user/select/single"]').prop('checked', $(this).is(':checked'));
}); });
@ -89,12 +85,12 @@ define('admin/manage/users', [
modal.on('shown.bs.modal', function () { modal.on('shown.bs.modal', function () {
autocomplete.group(modal.find('.group-search'), function (ev, ui) { autocomplete.group(modal.find('.group-search'), function (ev, ui) {
var uid = $(ev.target).attr('data-uid'); var uid = $(ev.target).attr('data-uid');
api.put('/groups/' + ui.item.group.slug + '/membership/' + uid, undefined, () => { api.put('/groups/' + ui.item.group.slug + '/membership/' + uid, undefined).then(() => {
ui.item.group.nameEscaped = translator.escape(ui.item.group.displayName); ui.item.group.nameEscaped = translator.escape(ui.item.group.displayName);
app.parseAndTranslate('admin/partials/manage_user_groups', { users: [{ groups: [ui.item.group] }] }, function (html) { app.parseAndTranslate('admin/partials/manage_user_groups', { users: [{ groups: [ui.item.group] }] }, function (html) {
$('[data-uid=' + uid + '] .group-area').append(html.find('.group-area').html()); $('[data-uid=' + uid + '] .group-area').append(html.find('.group-area').html());
}); });
}, 'default'); });
}); });
}); });
modal.on('click', '.group-area a', function () { modal.on('click', '.group-area a', function () {
@ -104,9 +100,9 @@ define('admin/manage/users', [
var groupCard = $(this).parents('[data-group-name]'); var groupCard = $(this).parents('[data-group-name]');
var groupName = groupCard.attr('data-group-name'); var groupName = groupCard.attr('data-group-name');
var uid = $(this).parents('[data-uid]').attr('data-uid'); var uid = $(this).parents('[data-uid]').attr('data-uid');
api.del('/groups/' + slugify(groupName) + '/membership/' + uid, undefined, () => { api.del('/groups/' + slugify(groupName) + '/membership/' + uid).then(() => {
groupCard.remove(); groupCard.remove();
}, 'default'); });
return false; return false;
}); });
}); });
@ -122,17 +118,11 @@ define('admin/manage/users', [
bootbox.confirm((uids.length > 1 ? '[[admin/manage/users:alerts.confirm-ban-multi]]' : '[[admin/manage/users:alerts.confirm-ban]]'), function (confirm) { bootbox.confirm((uids.length > 1 ? '[[admin/manage/users:alerts.confirm-ban-multi]]' : '[[admin/manage/users:alerts.confirm-ban]]'), function (confirm) {
if (confirm) { if (confirm) {
var requests = uids.map(function (uid) { Promise.all(uids.map(function (uid) {
return api.put('/users/' + uid + '/ban'); return api.put('/users/' + uid + '/ban');
})).then(() => {
onSuccess('[[admin/manage/users:alerts.ban-success]]', '.ban', true);
}); });
$.when(requests)
.done(function () {
onSuccess('[[admin/manage/users:alerts.ban-success]]', '.ban', true);
})
.fail(function (ev) {
onFail(ev.responseJSON.status);
});
} }
}); });
}); });
@ -164,19 +154,14 @@ define('admin/manage/users', [
}, {}); }, {});
var until = formData.length > 0 ? (Date.now() + (formData.length * 1000 * 60 * 60 * (parseInt(formData.unit, 10) ? 24 : 1))) : 0; var until = formData.length > 0 ? (Date.now() + (formData.length * 1000 * 60 * 60 * (parseInt(formData.unit, 10) ? 24 : 1))) : 0;
var requests = uids.map(function (uid) { Promise.all(uids.map(function (uid) {
return api.put('/users/' + uid + '/ban', { return api.put('/users/' + uid + '/ban', {
until: until, until: until,
reason: formData.reason, reason: formData.reason,
}); });
})).then(() => {
onSuccess('[[admin/manage/users:alerts.ban-success]]', '.ban', true);
}); });
$.when(requests)
.done(function () {
onSuccess('[[admin/manage/users:alerts.ban-success]]', '.ban', true);
}).fail(function (ev) {
onFail(ev.responseJSON.status);
});
}, },
}, },
}, },
@ -191,16 +176,11 @@ define('admin/manage/users', [
return false; // specifically to keep the menu open return false; // specifically to keep the menu open
} }
var requests = uids.map(function (uid) { Promise.all(uids.map(function (uid) {
return api.delete('/users/' + uid + '/ban'); return api.delete('/users/' + uid + '/ban');
})).then(() => {
onSuccess('[[admin/manage/users:alerts.unban-success]]', '.ban', false);
}); });
$.when(requests)
.done(function () {
onSuccess('[[admin/manage/users:alerts.unban-success]]', '.ban', false);
}).fail(function (ev) {
onFail(ev.responseJSON.status);
});
}); });
$('.reset-lockout').on('click', function () { $('.reset-lockout').on('click', function () {
@ -388,13 +368,15 @@ define('admin/manage/users', [
password: password, password: password,
}; };
api.post('/users', user, () => { api.post('/users', user)
modal.modal('hide'); .then(() => {
modal.on('hidden.bs.modal', function () { modal.modal('hide');
ajaxify.refresh(); modal.on('hidden.bs.modal', function () {
}); ajaxify.refresh();
app.alertSuccess('[[admin/manage/users:alerts.create-success]]'); });
}, err => errorEl.translateHtml('[[admin/manage/users:alerts.error-x, ' + err.status.message + ']]').removeClass('hidden')); app.alertSuccess('[[admin/manage/users:alerts.create-success]]');
})
.catch(err => errorEl.translateHtml('[[admin/manage/users:alerts.error-x, ' + err.status.message + ']]').removeClass('hidden'));
} }
handleSearch(); handleSearch();

@ -47,7 +47,7 @@ define('forum/account/edit', [
$(window).trigger('action:profile.update', userData); $(window).trigger('action:profile.update', userData);
api.put('/users/' + userData.uid, userData, (res) => { api.put('/users/' + userData.uid, userData).then((res) => {
app.alertSuccess('[[user:profile-update-success]]'); app.alertSuccess('[[user:profile-update-success]]');
if (res.picture) { if (res.picture) {
@ -55,7 +55,7 @@ define('forum/account/edit', [
} }
updateHeader(res.picture); updateHeader(res.picture);
}, 'default'); });
return false; return false;
} }

@ -26,10 +26,10 @@ define('forum/account/edit/email', ['forum/account/header', 'api'], function (he
var btn = $(this); var btn = $(this);
btn.addClass('disabled').find('i').removeClass('hide'); btn.addClass('disabled').find('i').removeClass('hide');
api.put('/users/' + userData.uid, userData, (res) => { api.put('/users/' + userData.uid, userData).then((res) => {
btn.removeClass('disabled').find('i').addClass('hide'); btn.removeClass('disabled').find('i').addClass('hide');
ajaxify.go('user/' + res.userslug + '/edit'); ajaxify.go('user/' + res.userslug + '/edit');
}, 'default'); });
return false; return false;
}); });

@ -71,22 +71,24 @@ define('forum/account/edit/password', [
api.put('/users/' + ajaxify.data.theirid + '/password', { api.put('/users/' + ajaxify.data.theirid + '/password', {
currentPassword: currentPassword.val(), currentPassword: currentPassword.val(),
newPassword: password.val(), newPassword: password.val(),
}, () => { })
if (parseInt(app.user.uid, 10) === parseInt(ajaxify.data.uid, 10)) { .then(() => {
window.location.href = config.relative_path + '/login'; if (parseInt(app.user.uid, 10) === parseInt(ajaxify.data.uid, 10)) {
} else { window.location.href = config.relative_path + '/login';
ajaxify.go('user/' + ajaxify.data.userslug + '/edit'); } else {
} ajaxify.go('user/' + ajaxify.data.userslug + '/edit');
}, 'default').always(() => { }
btn.removeClass('disabled').find('i').addClass('hide'); })
currentPassword.val(''); .finally(() => {
password.val(''); btn.removeClass('disabled').find('i').addClass('hide');
password_confirm.val(''); currentPassword.val('');
password_notify.parent().removeClass('show-success show-danger'); password.val('');
password_confirm_notify.parent().removeClass('show-success show-danger'); password_confirm.val('');
passwordsmatch = false; password_notify.parent().removeClass('show-success show-danger');
passwordvalid = false; password_confirm_notify.parent().removeClass('show-success show-danger');
}); passwordsmatch = false;
passwordvalid = false;
});
} else { } else {
if (!passwordsmatch) { if (!passwordsmatch) {
app.alertError('[[user:change_password_error_match]]'); app.alertError('[[user:change_password_error_match]]');

@ -26,7 +26,7 @@ define('forum/account/edit/username', [
var btn = $(this); var btn = $(this);
btn.addClass('disabled').find('i').removeClass('hide'); btn.addClass('disabled').find('i').removeClass('hide');
api.put('/users/' + userData.uid, userData, (res) => { api.put('/users/' + userData.uid, userData).then((res) => {
btn.removeClass('disabled').find('i').addClass('hide'); btn.removeClass('disabled').find('i').addClass('hide');
var userslug = slugify(userData.username); var userslug = slugify(userData.username);
if (userData.username && userslug && parseInt(userData.uid, 10) === parseInt(app.user.uid, 10)) { if (userData.username && userslug && parseInt(userData.uid, 10) === parseInt(app.user.uid, 10)) {
@ -38,7 +38,7 @@ define('forum/account/edit/username', [
} }
ajaxify.go('user/' + userslug + '/edit'); ajaxify.go('user/' + userslug + '/edit');
}, 'default'); });
return false; return false;
}); });

@ -152,13 +152,13 @@ define('forum/account/header', [
api.put('/users/' + theirid + '/ban', { api.put('/users/' + theirid + '/ban', {
until: until, until: until,
reason: formData.reason || '', reason: formData.reason || '',
}, () => { }).then(() => {
if (typeof onSuccess === 'function') { if (typeof onSuccess === 'function') {
return onSuccess(); return onSuccess();
} }
ajaxify.refresh(); ajaxify.refresh();
}, 'default'); });
}, },
}, },
}, },
@ -167,9 +167,9 @@ define('forum/account/header', [
} }
function unbanAccount() { function unbanAccount() {
api.del('/users/' + ajaxify.data.theirid + '/ban', undefined, () => { api.del('/users/' + ajaxify.data.theirid + '/ban').then(() => {
ajaxify.refresh(); ajaxify.refresh();
}, 'default'); });
} }
function flagAccount() { function flagAccount() {

@ -106,13 +106,14 @@ define('forum/groups/details', [
break; break;
case 'join': // intentional fall-throughs! case 'join': // intentional fall-throughs!
api.put('/groups/' + ajaxify.data.group.slug + '/membership/' + (uid || app.user.uid), undefined, () => ajaxify.refresh(), 'default'); api.put('/groups/' + ajaxify.data.group.slug + '/membership/' + (uid || app.user.uid), undefined).then(() => ajaxify.refresh());
break; break;
case 'leave': case 'leave':
api.del('/groups/' + ajaxify.data.group.slug + '/membership/' + (uid || app.user.uid), undefined, () => ajaxify.refresh(), 'default'); api.del('/groups/' + ajaxify.data.group.slug + '/membership/' + (uid || app.user.uid), undefined).then(() => ajaxify.refresh());
break; break;
// TODO (14/10/2020): rewrite these to use api module and merge with above 2 case blocks
case 'accept': // intentional fall-throughs! case 'accept': // intentional fall-throughs!
case 'reject': case 'reject':
case 'issueInvite': case 'issueInvite':

@ -14,9 +14,9 @@ define('forum/groups/list', [
if (name && name.length) { if (name && name.length) {
api.post('/groups', { api.post('/groups', {
name: name, name: name,
}, (res) => { }).then((res) => {
ajaxify.go('groups/' + res.slug); ajaxify.go('groups/' + res.slug);
}, 'default'); });
} }
}); });
}); });

@ -82,13 +82,7 @@ define('forum/groups/memberlist', ['api'], function (api) {
if (groupName === 'administrators') { if (groupName === 'administrators') {
socket.emit('admin.user.makeAdmins', uids, done); socket.emit('admin.user.makeAdmins', uids, done);
} else { } else {
var requests = uids.map(function (uid) { Promise.all(uids.map(uid => api.put('/groups/' + ajaxify.data.group.slug + '/membership/' + uid))).then(done);
return api.put('/groups/' + ajaxify.data.group.slug + '/membership/' + uid);
});
$.when(requests)
.done(done)
.fail('default');
} }
} }

@ -4,24 +4,33 @@ define('api', () => {
const api = {}; const api = {};
const baseUrl = config.relative_path + '/api/v3'; const baseUrl = config.relative_path + '/api/v3';
function call(options, onSuccess, onError) { function call(options, callback) {
$.ajax(Object.assign({ return new Promise((resolve, reject) => {
headers: { $.ajax(Object.assign({
'x-csrf-token': config.csrf_token, headers: {
}, 'x-csrf-token': config.csrf_token,
}, options)) },
.done((res) => { }, options))
if (onSuccess) { .done((res) => {
onSuccess(res.response); resolve(res.response);
}
}) if (callback) {
.fail((ev) => { callback(undefined, res.response);
if (onError === 'default') { }
app.alertError(ev.responseJSON.status.message); })
} else if (onError) { .fail((ev) => {
onError(ev.responseJSON); const error = new Error(ev.responseJSON.status.message);
} reject(error);
});
if (!utils.hasLanguageKey(ev.responseJSON.status.message)) {
app.alertError(ev.responseJSON.status.message);
}
if (callback) {
callback(error);
}
});
});
} }
api.get = (route, payload, onSuccess, onError) => call({ api.get = (route, payload, onSuccess, onError) => call({

Loading…
Cancel
Save