Created
November 20, 2018 20:02
-
-
Save winniecluk/0e52d253a1d3c245ccff10314c265dd1 to your computer and use it in GitHub Desktop.
bbb
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
}); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
is
lastKey
always a bool?