2019-03-17 05:19:01 +08:00
|
|
|
const repository = require('./repository');
|
|
|
|
const sql = require('./sql');
|
2019-03-17 18:38:27 +08:00
|
|
|
const log = require('./log');
|
2019-03-17 05:19:01 +08:00
|
|
|
const parseFilters = require('./parse_filters');
|
|
|
|
const buildSearchQuery = require('./build_search_query');
|
2019-04-23 00:08:33 +08:00
|
|
|
const noteCacheService = require('./note_cache');
|
2019-03-17 05:19:01 +08:00
|
|
|
|
|
|
|
async function searchForNotes(searchString) {
|
2019-04-23 00:08:33 +08:00
|
|
|
const noteIds = await searchForNoteIds(searchString);
|
2019-03-17 18:38:27 +08:00
|
|
|
|
2019-04-23 00:08:33 +08:00
|
|
|
return await repository.getNotes(noteIds);
|
2019-03-17 05:19:01 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
async function searchForNoteIds(searchString) {
|
|
|
|
const filters = parseFilters(searchString);
|
|
|
|
|
|
|
|
const {query, params} = buildSearchQuery(filters, 'notes.noteId');
|
|
|
|
|
2019-03-17 18:38:27 +08:00
|
|
|
try {
|
2019-09-04 02:16:38 +08:00
|
|
|
let noteIds = await sql.getColumn(query, params);
|
|
|
|
|
|
|
|
noteIds = noteIds.filter(noteCacheService.isAvailable);
|
|
|
|
|
|
|
|
const isArchivedFilter = filters.find(filter => filter.name.toLowerCase() === 'isarchived');
|
|
|
|
|
2019-09-10 02:29:07 +08:00
|
|
|
if (isArchivedFilter) {
|
2019-09-04 02:16:38 +08:00
|
|
|
if (isArchivedFilter.operator === 'exists') {
|
|
|
|
noteIds = noteIds.filter(noteCacheService.isArchived);
|
|
|
|
}
|
|
|
|
else if (isArchivedFilter.operator === 'not-exists') {
|
|
|
|
noteIds = noteIds.filter(noteId => !noteCacheService.isArchived(noteId));
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
throw new Error(`Unrecognized isArchived operator ${isArchivedFilter.operator}`);
|
|
|
|
}
|
|
|
|
}
|
2019-04-23 00:08:33 +08:00
|
|
|
|
|
|
|
const limitFilter = filters.find(filter => filter.name.toLowerCase() === 'limit');
|
|
|
|
|
|
|
|
if (limitFilter) {
|
|
|
|
const limit = parseInt(limitFilter.value);
|
|
|
|
|
2019-09-04 02:16:38 +08:00
|
|
|
return noteIds.splice(0, limit);
|
2019-04-23 00:08:33 +08:00
|
|
|
}
|
|
|
|
else {
|
2019-09-04 02:16:38 +08:00
|
|
|
return noteIds;
|
2019-04-23 00:08:33 +08:00
|
|
|
}
|
|
|
|
|
2019-03-17 18:38:27 +08:00
|
|
|
}
|
|
|
|
catch (e) {
|
|
|
|
log.error("Search failed for " + query);
|
|
|
|
|
|
|
|
throw e;
|
|
|
|
}
|
2019-03-17 05:19:01 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
searchForNotes,
|
|
|
|
searchForNoteIds
|
|
|
|
};
|