Skip to content

Instantly share code, notes, and snippets.

@winniecluk
Created November 20, 2018 20:02
Show Gist options
  • Save winniecluk/0e52d253a1d3c245ccff10314c265dd1 to your computer and use it in GitHub Desktop.
Save winniecluk/0e52d253a1d3c245ccff10314c265dd1 to your computer and use it in GitHub Desktop.
bbb
fetchNotifications(userId, options, time = +new Date(), pageSize, startKey) {
return new Promise((resolve, reject) => {
let query = this.model
.query('assignee_id')
.eq(userId)
.where('create_time')
.lt(new Date(time).getTime());
if (startKey && typeof startKey !== 'boolean') {
query.startAt(startKey);
}
query = Object.keys(options).reduce((q, field) => {
if (options[field] || options[field] === false) {
q
.and()
.filter(field)
.eq(options[field]);
}
return q;
}, query);
query
.descending()
.limit(pageSize)
.exec()
.then(notifications => resolve(notifications))
.catch(reject);
});
}
index(req, res) {
let { pageSize, time, transaction_id } = req.query;
if (!pageSize) {
pageSize = 10;
}
return new Promise(async (resolve, reject) => {
try {
if (req.user.admin) {
this.model.scan().exec((err, notifications) => {
if (err) {
reject(err);
} else {
resolve(notifications);
}
});
} else {
let results = [];
let lastTime = time;
let lastKey = true;
while (results.length < pageSize && lastKey) {
let notifications = await this.fetchNotifications(
req.user.id,
{
transaction_id,
recent_activity: helpers.convertStringToBoolean(req.query.recent_activity),
global_notification: helpers.convertStringToBoolean(req.query.global_notification)
},
lastTime,
pageSize,
lastKey
);
if (notifications.length > 0) {
lastTime = notifications[notifications.length - 1].create_time;
results = [...results, ...notifications];
}
lastKey = notifications.lastKey;
}
resolve(results.slice(0, pageSize));
}
} catch (err) {
reject(err);
}
});
}
notifications.get(helpers.api.auth, helpers.api.user, async (req, res) => {
try {
const method = req.params.id ? 'show' : 'index';
const notifications = await Controller[method](req, res);
res.json(notifications);
} catch (err) {
throw new Error(err);
}
});
@germ13
Copy link

germ13 commented Nov 20, 2018

is lastKey always a bool?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment