trilium/src/routes/api/autocomplete.js

71 lines
1.8 KiB
JavaScript
Raw Normal View History

2018-04-18 12:26:42 +08:00
"use strict";
2020-05-17 16:11:19 +08:00
const noteCacheService = require('../../services/note_cache/note_cache_service');
const searchService = require('../../services/search/search');
const repository = require('../../services/repository');
2018-11-05 05:10:52 +08:00
const log = require('../../services/log');
const utils = require('../../services/utils');
const optionService = require('../../services/options');
2018-04-18 12:26:42 +08:00
2020-06-20 18:31:38 +08:00
function getAutocomplete(req) {
2019-09-10 02:29:07 +08:00
const query = req.query.query.trim();
const activeNoteId = req.query.activeNoteId || 'none';
2018-04-18 12:26:42 +08:00
let results;
2018-11-05 05:10:52 +08:00
const timestampStarted = Date.now();
2019-09-10 02:29:07 +08:00
if (query.length === 0) {
2020-06-20 18:31:38 +08:00
results = getRecentNotes(activeNoteId);
}
else {
2020-06-20 18:31:38 +08:00
results = searchService.searchNotesForAutocomplete(query);
}
2018-04-18 12:26:42 +08:00
2018-11-05 05:10:52 +08:00
const msTaken = Date.now() - timestampStarted;
if (msTaken >= 100) {
log.info(`Slow autocomplete took ${msTaken}ms`);
}
return results;
2018-04-18 12:26:42 +08:00
}
2020-06-20 18:31:38 +08:00
function getRecentNotes(activeNoteId) {
let extraCondition = '';
2020-06-20 18:31:38 +08:00
const hoistedNoteId = optionService.getOption('hoistedNoteId');
if (hoistedNoteId !== 'root') {
extraCondition = `AND recent_notes.notePath LIKE '%${utils.sanitizeSql(hoistedNoteId)}%'`;
}
2020-06-20 18:31:38 +08: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-13 03:58:31 +08:00
utcDateCreated DESC
LIMIT 200`, [activeNoteId]);
return recentNotes.map(rn => {
2018-11-08 00:16:33 +08:00
const title = noteCacheService.getNoteTitleForPath(rn.notePath.split('/'));
return {
2020-05-17 04:11:09 +08:00
notePath: rn.notePath,
notePathTitle: title,
highlightedNotePathTitle: utils.escapeHtml(title)
};
});
}
2018-04-18 12:26:42 +08:00
module.exports = {
getAutocomplete
};