Notes/src/routes/api/autocomplete.ts

81 lines
2.2 KiB
TypeScript
Raw Normal View History

2018-04-18 00:26:42 -04:00
"use strict";
import beccaService = require('../../becca/becca_service');
import searchService = require('../../services/search/services/search');
import log = require('../../services/log');
import utils = require('../../services/utils');
import cls = require('../../services/cls');
import becca = require('../../becca/becca');
import { Request } from 'express';
import ValidationError = require('../../errors/validation_error');
2018-04-18 00:26:42 -04:00
function getAutocomplete(req: Request) {
if (typeof req.query.query !== "string") {
throw new ValidationError("Invalid query data type.");
}
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();
if (query.length === 0 && typeof activeNoteId === "string") {
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
}
function getRecentNotes(activeNoteId: string) {
let extraCondition = '';
const params = [activeNoteId];
2020-11-23 23:11:21 +01:00
const hoistedNoteId = cls.getHoistedNoteId();
if (hoistedNoteId !== 'root') {
extraCondition = `AND recent_notes.notePath LIKE ?`;
params.push(`%${hoistedNoteId}%`);
}
2021-05-02 19:59:16 +02:00
const recentNotes = becca.getRecentNotesFromQuery(`
SELECT
recent_notes.*
FROM
recent_notes
JOIN notes USING(noteId)
WHERE
2021-02-13 21:52:31 +01:00
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('/');
2021-04-16 23:00:08 +02:00
const noteTitle = beccaService.getNoteTitle(notePathArray[notePathArray.length - 1]);
const notePathTitle = beccaService.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)
};
});
}
export = {
2018-04-18 00:26:42 -04:00
getAutocomplete
};