refactor: async/await

This commit is contained in:
Barış Soner Uşaklı
2019-09-13 23:34:52 -04:00
parent f05c1dae69
commit 52b2d670e5
2 changed files with 164 additions and 266 deletions

View File

@@ -1,223 +1,153 @@
'use strict'; 'use strict';
var async = require('async'); const categories = require('../categories');
const privileges = require('../privileges');
const user = require('../user');
const topics = require('../topics');
const apiController = require('../controllers/api');
var categories = require('../categories'); const SocketCategories = module.exports;
var privileges = require('../privileges');
var user = require('../user');
var topics = require('../topics');
var apiController = require('../controllers/api');
var SocketCategories = module.exports; SocketCategories.getRecentReplies = async function (socket, cid) {
return await categories.getRecentReplies(cid, socket.uid, 4);
SocketCategories.getRecentReplies = function (socket, cid, callback) {
categories.getRecentReplies(cid, socket.uid, 4, callback);
}; };
SocketCategories.get = function (socket, data, callback) { SocketCategories.get = async function (socket) {
async.waterfall([ async function getCategories() {
function (next) { const cids = await categories.getCidsByPrivilege('categories:cid', socket.uid, 'find');
async.parallel({ return await categories.getCategoriesData(cids);
isAdmin: async.apply(user.isAdministrator, socket.uid), }
categories: function (next) { const [isAdmin, categoriesData] = await Promise.all([
async.waterfall([ user.isAdministrator(socket.uid),
async.apply(categories.getCidsByPrivilege, 'categories:cid', socket.uid, 'find'), getCategories(),
async.apply(categories.getCategoriesData), ]);
], next); return categoriesData.filter(category => category && (!category.disabled || isAdmin));
},
}, next);
},
function (results, next) {
results.categories = results.categories.filter(function (category) {
return category && (!category.disabled || results.isAdmin);
});
next(null, results.categories);
},
], callback);
}; };
SocketCategories.getWatchedCategories = function (socket, data, callback) { SocketCategories.getWatchedCategories = async function (socket) {
async.waterfall([ const [categoriesData, ignoredCids] = await Promise.all([
function (next) { categories.getCategoriesByPrivilege('cid:0:children', socket.uid, 'find'),
async.parallel({ user.getIgnoredCategories(socket.uid),
categories: async.apply(categories.getCategoriesByPrivilege, 'cid:0:children', socket.uid, 'find'), ]);
ignoredCids: async.apply(user.getIgnoredCategories, socket.uid), return categoriesData.filter(category => category && !ignoredCids.includes(String(category.cid)));
}, next);
},
function (results, next) {
var watchedCategories = results.categories.filter(function (category) {
return category && !results.ignoredCids.includes(String(category.cid));
});
next(null, watchedCategories);
},
], callback);
}; };
SocketCategories.loadMore = function (socket, data, callback) { SocketCategories.loadMore = async function (socket, data) {
if (!data) { if (!data) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
data.query = data.query || {}; data.query = data.query || {};
var userPrivileges; const [userPrivileges, settings, targetUid] = await Promise.all([
async.waterfall([ privileges.categories.get(data.cid, socket.uid),
function (next) { user.getSettings(socket.uid),
async.parallel({ user.getUidByUserslug(data.query.author),
privileges: function (next) { ]);
privileges.categories.get(data.cid, socket.uid, next);
},
settings: function (next) {
user.getSettings(socket.uid, next);
},
targetUid: function (next) {
if (data.query.author) {
user.getUidByUserslug(data.query.author, next);
} else {
next();
}
},
}, next);
},
function (results, next) {
userPrivileges = results.privileges;
if (!userPrivileges.read) {
return callback(new Error('[[error:no-privileges]]'));
}
var infScrollTopicsPerPage = 20;
var sort = data.sort || data.categoryTopicSort;
var start = Math.max(0, parseInt(data.after, 10)); if (!userPrivileges.read) {
throw new Error('[[error:no-privileges]]');
if (data.direction === -1) {
start -= infScrollTopicsPerPage;
}
var stop = start + infScrollTopicsPerPage - 1;
start = Math.max(0, start);
stop = Math.max(0, stop);
categories.getCategoryTopics({
uid: socket.uid,
cid: data.cid,
start: start,
stop: stop,
sort: sort,
settings: results.settings,
query: data.query,
tag: data.query.tag,
targetUid: results.targetUid,
}, next);
},
function (data, next) {
categories.modifyTopicsByPrivilege(data.topics, userPrivileges);
data.privileges = userPrivileges;
data.template = {
category: true,
name: 'category',
};
next(null, data);
},
], callback);
};
SocketCategories.getTopicCount = function (socket, cid, callback) {
categories.getCategoryField(cid, 'topic_count', callback);
};
SocketCategories.getCategoriesByPrivilege = function (socket, privilege, callback) {
categories.getCategoriesByPrivilege('categories:cid', socket.uid, privilege, callback);
};
SocketCategories.getMoveCategories = function (socket, data, callback) {
SocketCategories.getSelectCategories(socket, data, callback);
};
SocketCategories.getSelectCategories = function (socket, data, callback) {
async.waterfall([
function (next) {
async.parallel({
isAdmin: async.apply(user.isAdministrator, socket.uid),
categories: function (next) {
categories.buildForSelect(socket.uid, 'find', next);
},
}, next);
},
function (results, next) {
results.categories = results.categories.filter(function (category) {
return category && (!category.disabled || results.isAdmin) && !category.link;
});
next(null, results.categories);
},
], callback);
};
SocketCategories.setWatchState = function (socket, data, callback) {
if (!data || !data.cid || !data.state) {
return callback(new Error('[[error:invalid-data]]'));
} }
ignoreOrWatch(function (uid, cid, next) {
user.setCategoryWatchState(uid, cid, categories.watchStates[data.state], next); const infScrollTopicsPerPage = 20;
}, socket, data, callback); const sort = data.sort || data.categoryTopicSort;
let start = Math.max(0, parseInt(data.after, 10));
if (data.direction === -1) {
start -= infScrollTopicsPerPage;
}
let stop = start + infScrollTopicsPerPage - 1;
start = Math.max(0, start);
stop = Math.max(0, stop);
const result = await categories.getCategoryTopics({
uid: socket.uid,
cid: data.cid,
start: start,
stop: stop,
sort: sort,
settings: settings,
query: data.query,
tag: data.query.tag,
targetUid: targetUid,
});
categories.modifyTopicsByPrivilege(data.topics, userPrivileges);
result.privileges = userPrivileges;
result.template = {
category: true,
name: 'category',
};
return result;
}; };
SocketCategories.watch = function (socket, data, callback) { SocketCategories.getTopicCount = async function (socket, cid) {
ignoreOrWatch(user.watchCategory, socket, data, callback); return await categories.getCategoryField(cid, 'topic_count');
}; };
SocketCategories.ignore = function (socket, data, callback) { SocketCategories.getCategoriesByPrivilege = async function (socket, privilege) {
ignoreOrWatch(user.ignoreCategory, socket, data, callback); return await categories.getCategoriesByPrivilege('categories:cid', socket.uid, privilege);
}; };
function ignoreOrWatch(fn, socket, data, callback) { SocketCategories.getMoveCategories = async function (socket, data) {
var targetUid = socket.uid; return await SocketCategories.getSelectCategories(socket, data);
var cids = [parseInt(data.cid, 10)]; };
SocketCategories.getSelectCategories = async function (socket) {
const [isAdmin, categoriesData] = await Promise.all([
user.isAdministrator(socket.uid),
categories.buildForSelect(socket.uid, 'find'),
]);
return categoriesData.filter(category => category && (!category.disabled || isAdmin) && !category.link);
};
SocketCategories.setWatchState = async function (socket, data) {
if (!data || !data.cid || !data.state) {
throw new Error('[[error:invalid-data]]');
}
await ignoreOrWatch(async function (uid, cid) {
await user.setCategoryWatchState(uid, cid, categories.watchStates[data.state]);
}, socket, data);
};
SocketCategories.watch = async function (socket, data) {
await ignoreOrWatch(user.watchCategory, socket, data);
};
SocketCategories.ignore = async function (socket, data) {
await ignoreOrWatch(user.ignoreCategory, socket, data);
};
async function ignoreOrWatch(fn, socket, data) {
let targetUid = socket.uid;
const cids = [parseInt(data.cid, 10)];
if (data.hasOwnProperty('uid')) { if (data.hasOwnProperty('uid')) {
targetUid = data.uid; targetUid = data.uid;
} }
await user.isAdminOrGlobalModOrSelf(socket.uid, targetUid);
const allCids = await categories.getAllCidsFromSet('categories:cid');
const categoryData = await categories.getCategoriesFields(allCids, ['cid', 'parentCid']);
async.waterfall([ // filter to subcategories of cid
function (next) { let cat;
user.isAdminOrGlobalModOrSelf(socket.uid, targetUid, next); do {
}, cat = categoryData.find(c => !cids.includes(c.cid) && cids.includes(c.parentCid));
function (next) { if (cat) {
categories.getAllCidsFromSet('categories:cid', next); cids.push(cat.cid);
}, }
function (cids, next) { } while (cat);
categories.getCategoriesFields(cids, ['cid', 'parentCid'], next);
},
function (categoryData, next) {
// filter to subcategories of cid
var cat;
do {
cat = categoryData.find(function (c) {
return !cids.includes(c.cid) && cids.includes(c.parentCid);
});
if (cat) {
cids.push(cat.cid);
}
} while (cat);
async.each(cids, function (cid, next) { await Promise.all(cids.map(cid => fn(targetUid, cid)));
fn(targetUid, cid, next); await topics.pushUnreadCount(targetUid);
}, next); return cids;
},
function (next) {
topics.pushUnreadCount(targetUid, next);
},
function (next) {
next(null, cids);
},
], callback);
} }
SocketCategories.isModerator = function (socket, cid, callback) { SocketCategories.isModerator = async function (socket, cid) {
user.isModerator(socket.uid, cid, callback); return await user.isModerator(socket.uid, cid);
}; };
SocketCategories.getCategory = function (socket, cid, callback) { SocketCategories.getCategory = async function (socket, cid) {
apiController.getCategoryData(cid, socket.uid, callback); return await apiController.getCategoryData(cid, socket.uid);
}; };
require('../promisify')(SocketCategories);

View File

@@ -1,97 +1,65 @@
'use strict'; 'use strict';
var async = require('async'); const user = require('../user');
const flags = require('../flags');
var user = require('../user'); const SocketFlags = module.exports;
var flags = require('../flags');
var SocketFlags = module.exports; SocketFlags.create = async function (socket, data) {
SocketFlags.create = function (socket, data, callback) {
if (!socket.uid) { if (!socket.uid) {
return callback(new Error('[[error:not-logged-in]]')); throw new Error('[[error:not-logged-in]]');
} }
if (!data || !data.type || !data.id || !data.reason) { if (!data || !data.type || !data.id || !data.reason) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
await flags.validate({
uid: socket.uid,
type: data.type,
id: data.id,
});
async.waterfall([ const flagObj = await flags.create(data.type, data.id, socket.uid, data.reason);
async.apply(flags.validate, { await flags.notify(flagObj, socket.uid);
uid: socket.uid, return flagObj;
type: data.type,
id: data.id,
}),
function (next) {
// If we got here, then no errors occurred
flags.create(data.type, data.id, socket.uid, data.reason, next);
},
function (flagObj, next) {
flags.notify(flagObj, socket.uid);
next(null, flagObj);
},
], callback);
}; };
SocketFlags.update = function (socket, data, callback) { SocketFlags.update = async function (socket, data) {
if (!data || !(data.flagId && data.data)) { if (!data || !(data.flagId && data.data)) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
var payload = {}; const allowed = await user.isPrivileged(socket.uid);
if (!allowed) {
throw new Error('[[no-privileges]]');
}
let payload = {};
// Translate form data into object
payload = data.data.reduce(function (memo, cur) {
memo[cur.name] = cur.value;
return memo;
}, payload);
async.waterfall([ await flags.update(data.flagId, socket.uid, payload);
function (next) { return await flags.getHistory(data.flagId);
async.parallel([
async.apply(user.isAdminOrGlobalMod, socket.uid),
async.apply(user.isModeratorOfAnyCategory, socket.uid),
], function (err, results) {
next(err, results[0] || results[1]);
});
},
function (allowed, next) {
if (!allowed) {
return next(new Error('[[no-privileges]]'));
}
// Translate form data into object
payload = data.data.reduce(function (memo, cur) {
memo[cur.name] = cur.value;
return memo;
}, payload);
flags.update(data.flagId, socket.uid, payload, next);
},
async.apply(flags.getHistory, data.flagId),
], callback);
}; };
SocketFlags.appendNote = function (socket, data, callback) { SocketFlags.appendNote = async function (socket, data) {
if (!data || !(data.flagId && data.note)) { if (!data || !(data.flagId && data.note)) {
return callback(new Error('[[error:invalid-data]]')); throw new Error('[[error:invalid-data]]');
} }
async.waterfall([ const allowed = await user.isPrivileged(socket.uid);
function (next) { if (!allowed) {
async.parallel([ throw new Error('[[no-privileges]]');
async.apply(user.isAdminOrGlobalMod, socket.uid), }
async.apply(user.isModeratorOfAnyCategory, socket.uid), await flags.appendNote(data.flagId, socket.uid, data.note);
], function (err, results) {
next(err, results[0] || results[1]);
});
},
function (allowed, next) {
if (!allowed) {
return next(new Error('[[no-privileges]]'));
}
flags.appendNote(data.flagId, socket.uid, data.note, next); const [notes, history] = await Promise.all([
}, flags.getNotes(data.flagId),
function (next) { flags.getHistory(data.flagId),
async.parallel({ ]);
notes: async.apply(flags.getNotes, data.flagId), return { notes: notes, history: history };
history: async.apply(flags.getHistory, data.flagId),
}, next);
},
], callback);
}; };
require('../promisify')(SocketFlags);