refactor: async/await flags

v1.18.x
Barış Soner Uşaklı 5 years ago
parent 625b0815bb
commit 9ee1a882ec

@ -1,37 +1,35 @@
'use strict'; 'use strict';
var async = require('async'); const async = require('async');
var _ = require('lodash'); const _ = require('lodash');
var winston = require('winston'); const winston = require('winston');
var validator = require('validator'); const validator = require('validator');
var db = require('./database'); const db = require('./database');
var user = require('./user'); const user = require('./user');
var groups = require('./groups'); const groups = require('./groups');
var meta = require('./meta'); const meta = require('./meta');
var notifications = require('./notifications'); const notifications = require('./notifications');
var analytics = require('./analytics'); const analytics = require('./analytics');
var topics = require('./topics'); const topics = require('./topics');
var posts = require('./posts'); const posts = require('./posts');
var privileges = require('./privileges'); const privileges = require('./privileges');
var plugins = require('./plugins'); const plugins = require('./plugins');
var utils = require('../public/src/utils'); const utils = require('../public/src/utils');
var Flags = module.exports; const Flags = module.exports;
Flags.init = function (callback) { Flags.init = async function () {
// Query plugins for custom filter strategies and merge into core filter strategies // Query plugins for custom filter strategies and merge into core filter strategies
var prepareSets = function (sets, orSets, prefix, value) { function prepareSets(sets, orSets, prefix, value) {
if (!Array.isArray(value)) { if (!Array.isArray(value)) {
sets.push(prefix + value); sets.push(prefix + value);
} else if (value.length) { } else if (value.length) {
value.forEach(function (x) { value.forEach(x => orSets.push(prefix + x));
orSets.push(prefix + x); }
});
} }
};
plugins.fireHook('filter:flags.getFilters', { const hookData = {
filters: { filters: {
type: function (sets, orSets, key) { type: function (sets, orSets, key) {
prepareSets(sets, orSets, 'flags:byType:', key); prepareSets(sets, orSets, 'flags:byType:', key);
@ -64,54 +62,47 @@ Flags.init = function (callback) {
helpers: { helpers: {
prepareSets: prepareSets, prepareSets: prepareSets,
}, },
}, function (err, data) { };
if (err) {
winston.error('[flags/init] Could not retrieve filters', err);
data.filters = {};
}
try {
const data = await plugins.fireHook('filter:flags.getFilters', hookData);
Flags._filters = data.filters; Flags._filters = data.filters;
callback(); } catch (err) {
}); winston.error('[flags/init] Could not retrieve filters', err);
Flags._filters = {};
}
}; };
Flags.get = function (flagId, callback) { Flags.get = async function (flagId) {
async.waterfall([ const [base, history, notes] = await Promise.all([
// First stage db.getObject('flag:' + flagId),
async.apply(async.parallel, { Flags.getHistory(flagId),
base: async.apply(db.getObject.bind(db), 'flag:' + flagId), Flags.getNotes(flagId),
history: async.apply(Flags.getHistory, flagId), ]);
notes: async.apply(Flags.getNotes, flagId), if (!base) {
}), return;
function (data, next) { }
if (!data.base) {
return callback(); const [userObj, targetObj] = await Promise.all([
} user.getUserFields(base.uid, ['username', 'userslug', 'picture', 'reputation']),
// Second stage Flags.getTarget(base.type, base.targetId, 0),
async.parallel({ ]);
userObj: async.apply(user.getUserFields, data.base.uid, ['username', 'userslug', 'picture', 'reputation']),
targetObj: async.apply(Flags.getTarget, data.base.type, data.base.targetId, 0), const flagObj = {
}, function (err, payload) { state: 'open',
// Final object return construction ...base,
next(err, { state: 'open', description: validator.escape(base.description),
...data.base, datetimeISO: utils.toISOString(base.datetime),
description: validator.escape(data.base.description), target_readable: base.type.charAt(0).toUpperCase() + base.type.slice(1) + ' ' + base.targetId,
datetimeISO: utils.toISOString(data.base.datetime), target: targetObj,
target_readable: data.base.type.charAt(0).toUpperCase() + data.base.type.slice(1) + ' ' + data.base.targetId, history: history,
target: payload.targetObj, notes: notes,
history: data.history, reporter: userObj,
notes: data.notes, };
reporter: payload.userObj }); const data = await plugins.fireHook('filter:flags.get', {
});
},
function (flagObj, next) {
plugins.fireHook('filter:flags.get', {
flag: flagObj, flag: flagObj,
}, function (err, data) {
next(err, data.flag);
}); });
}, return data.flag;
], callback);
}; };
Flags.list = function (filters, uid, callback) { Flags.list = function (filters, uid, callback) {
@ -388,7 +379,8 @@ Flags.create = function (type, id, uid, reason, timestamp, callback) {
if (targetUid) { if (targetUid) {
tasks.push(async.apply(db.sortedSetAdd.bind(db), 'flags:byTargetUid:' + targetUid, timestamp, flagId)); // by target uid tasks.push(async.apply(db.sortedSetAdd.bind(db), 'flags:byTargetUid:' + targetUid, timestamp, flagId)); // by target uid
} }
console.log('type/id', type, id);
console.log('targetUid/cid', targetUid, targetCid);
if (targetCid) { if (targetCid) {
tasks.push(async.apply(db.sortedSetAdd.bind(db), 'flags:byCid:' + targetCid, timestamp, flagId)); // by target cid tasks.push(async.apply(db.sortedSetAdd.bind(db), 'flags:byCid:' + targetCid, timestamp, flagId)); // by target cid
} }
@ -413,88 +405,48 @@ Flags.create = function (type, id, uid, reason, timestamp, callback) {
], callback); ], callback);
}; };
Flags.exists = function (type, id, uid, callback) { Flags.exists = async function (type, id, uid) {
db.isSortedSetMember('flags:hash', [type, id, uid].join(':'), callback); return await db.isSortedSetMember('flags:hash', [type, id, uid].join(':'));
}; };
Flags.getTarget = function (type, id, uid, callback) { Flags.getTarget = async function (type, id, uid) {
async.waterfall([ if (type === 'user') {
async.apply(Flags.targetExists, type, id), const userData = await user.getUserData(id);
function (exists, next) { return userData && userData.uid ? userData : {};
if (exists) {
switch (type) {
case 'post':
async.waterfall([
async.apply(posts.getPostsData, [id]),
function (postData, next) {
async.map(postData, posts.parsePost, next);
},
function (postData, next) {
postData = postData.filter(Boolean);
topics.addPostData(postData, uid, next);
},
function (postData, next) {
next(null, postData[0]);
},
], callback);
break;
case 'user':
user.getUsersData([id], function (err, users) {
next(err, users ? users[0] : undefined);
});
break;
default:
next(new Error('[[error:invalid-data]]'));
break;
} }
} else { if (type === 'post') {
// Target used to exist (otherwise flag creation'd fail), but no longer let postData = await posts.getPostData(id);
next(null, {}); if (!postData) {
return {};
} }
}, postData = await posts.parsePost(postData);
], callback); postData = await topics.addPostData([postData], uid);
return postData[0];
}
throw new Error('[[error:invalid-data]]');
}; };
Flags.targetExists = function (type, id, callback) { Flags.targetExists = async function (type, id) {
switch (type) { if (type === 'post') {
case 'post': return await posts.exists(id);
posts.exists(id, callback); } else if (type === 'user') {
break; return await user.exists(id);
case 'user':
user.exists(id, callback);
break;
default:
callback(new Error('[[error:invalid-data]]'));
break;
} }
throw new Error('[[error:invalid-data]]');
}; };
Flags.getTargetUid = function (type, id, callback) { Flags.getTargetUid = async function (type, id) {
switch (type) { if (type === 'post') {
case 'post': return await posts.getPostField(id, 'uid');
posts.getPostField(id, 'uid', callback);
break;
default:
setImmediate(callback, null, id);
break;
} }
return id;
}; };
Flags.getTargetCid = function (type, id, callback) { Flags.getTargetCid = async function (type, id) {
switch (type) { if (type === 'post') {
case 'post': return await posts.getCidByPid(id);
posts.getCidByPid(id, callback);
break;
default:
setImmediate(callback, null, id);
break;
} }
return id;
}; };
Flags.update = function (flagId, uid, changeset, callback) { Flags.update = function (flagId, uid, changeset, callback) {

Loading…
Cancel
Save