overleaf/services/spelling/app/js/LearnedWordsManager.js

98 lines
2.3 KiB
JavaScript
Raw Normal View History

2019-07-03 08:41:01 -04:00
const db = require('./DB')
const mongoCache = require('./MongoCache')
const logger = require('logger-sharelatex')
const metrics = require('metrics-sharelatex')
const { promisify } = require('util')
2019-07-03 08:41:01 -04:00
const LearnedWordsManager = {
2019-07-03 08:41:01 -04:00
learnWord(userToken, word, callback) {
if (callback == null) {
callback = () => {}
}
mongoCache.del(userToken)
return db.spellingPreferences.update(
{
token: userToken
},
{
$push: { learnedWords: word }
},
{
upsert: true
},
callback
)
},
2019-07-20 09:04:08 -04:00
unlearnWord(userToken, word, callback) {
if (callback == null) {
callback = () => {}
}
mongoCache.del(userToken)
return db.spellingPreferences.update(
{
token: userToken
},
{
$pull: { learnedWords: word }
},
callback
)
},
2019-07-03 08:41:01 -04:00
getLearnedWords(userToken, callback) {
if (callback == null) {
callback = () => {}
}
const mongoCachedWords = mongoCache.get(userToken)
if (mongoCachedWords != null) {
metrics.inc('mongoCache', 0.1, { status: 'hit' })
return callback(null, mongoCachedWords)
}
metrics.inc('mongoCache', 0.1, { status: 'miss' })
logger.info({ userToken }, 'mongoCache miss')
db.spellingPreferences.findOne({ token: userToken }, function(
2019-07-03 08:41:01 -04:00
error,
preferences
) {
if (error != null) {
return callback(error)
}
const words =
(preferences != null ? preferences.learnedWords : undefined) || []
mongoCache.set(userToken, words)
callback(null, words)
2019-07-03 08:41:01 -04:00
})
},
deleteUsersLearnedWords(userToken, callback) {
if (callback == null) {
callback = () => {}
}
db.spellingPreferences.remove({ token: userToken }, callback)
2019-07-03 08:41:01 -04:00
}
}
const promises = {
learnWord: promisify(LearnedWordsManager.learnWord),
2019-07-20 09:04:08 -04:00
unlearnWord: promisify(LearnedWordsManager.unlearnWord),
getLearnedWords: promisify(LearnedWordsManager.getLearnedWords),
deleteUsersLearnedWords: promisify(
LearnedWordsManager.deleteUsersLearnedWords
)
}
LearnedWordsManager.promises = promises
module.exports = LearnedWordsManager
2019-07-20 09:04:08 -04:00
;['learnWord', 'unlearnWord', 'getLearnedWords'].map(method =>
2019-07-03 08:41:01 -04:00
metrics.timeAsyncMethod(
LearnedWordsManager,
method,
'mongo.LearnedWordsManager',
logger
)
)