Notes/src/routes/api/autocomplete.js

77 lines
2.0 KiB
JavaScript
Raw Normal View History

2018-04-18 00:26:42 -04:00
"use strict";
2020-05-17 10:11:19 +02:00
const noteCacheService = require('../../services/note_cache/note_cache_service');
2020-07-21 00:01:07 +02:00
const searchService = require('../../services/search/services/search.js');
const repository = require('../../services/repository');
2018-11-04 22:10:52 +01:00
const log = require('../../services/log');
const utils = require('../../services/utils');
const optionService = require('../../services/options');
2018-04-18 00:26:42 -04:00
2020-06-20 12:31:38 +02:00
function getAutocomplete(req) {
2019-09-09 20:29:07 +02:00
const query = req.query.query.trim();
const activeNoteId = req.query.activeNoteId || 'none';
2018-04-18 00:26:42 -04:00
let results;
2018-11-04 22:10:52 +01:00
const timestampStarted = Date.now();
2019-09-09 20:29:07 +02:00
if (query.length === 0) {
2020-06-20 12:31:38 +02:00
results = getRecentNotes(activeNoteId);
}
else {
2020-06-20 12:31:38 +02:00
results = searchService.searchNotesForAutocomplete(query);
}
2018-04-18 00:26:42 -04:00
2018-11-04 22:10:52 +01:00
const msTaken = Date.now() - timestampStarted;
if (msTaken >= 100) {
log.info(`Slow autocomplete took ${msTaken}ms`);
}
return results;
2018-04-18 00:26:42 -04:00
}
2020-06-20 12:31:38 +02:00
function getRecentNotes(activeNoteId) {
let extraCondition = '';
const params = [activeNoteId];
2020-06-20 12:31:38 +02:00
const hoistedNoteId = optionService.getOption('hoistedNoteId');
if (hoistedNoteId !== 'root') {
extraCondition = `AND recent_notes.notePath LIKE ?`;
params.push(hoistedNoteId + '%');
}
2020-06-20 12:31:38 +02:00
const recentNotes = repository.getEntities(`
SELECT
recent_notes.*
FROM
recent_notes
JOIN notes USING(noteId)
WHERE
recent_notes.isDeleted = 0
AND notes.isDeleted = 0
AND notes.noteId != ?
${extraCondition}
ORDER BY
2019-03-12 20:58:31 +01:00
utcDateCreated DESC
LIMIT 200`, params);
return recentNotes.map(rn => {
const notePathArray = rn.notePath.split('/');
const noteTitle = noteCacheService.getNoteTitle(notePathArray[notePathArray.length - 1]);
const notePathTitle = noteCacheService.getNoteTitleForPath(notePathArray);
2018-11-07 17:16:33 +01:00
return {
2020-05-16 22:11:09 +02:00
notePath: rn.notePath,
noteTitle,
notePathTitle,
highlightedNotePathTitle: utils.escapeHtml(notePathTitle)
};
});
}
2018-04-18 00:26:42 -04:00
module.exports = {
getAutocomplete
};