2020-11-05 18:58:23 +02:00
|
|
|
import BaseModel, { ModelType } from '../../../BaseModel';
|
|
|
|
import { Request } from '../Api';
|
|
|
|
import defaultLoadOptions from '../utils/defaultLoadOptions';
|
|
|
|
import { ErrorBadRequest, ErrorMethodNotAllowed } from '../utils/errors';
|
|
|
|
import requestFields from '../utils/requestFields';
|
2020-11-11 13:52:47 +02:00
|
|
|
import collectionToPaginatedResults from '../utils/collectionToPaginatedResults';
|
2020-11-05 18:58:23 +02:00
|
|
|
const BaseItem = require('../../../models/BaseItem');
|
|
|
|
const SearchEngineUtils = require('../../searchengine/SearchEngineUtils');
|
|
|
|
|
|
|
|
export default async function(request:Request) {
|
|
|
|
if (request.method !== 'GET') throw new ErrorMethodNotAllowed();
|
|
|
|
|
|
|
|
const query = request.query.query;
|
|
|
|
if (!query) throw new ErrorBadRequest('Missing "query" parameter');
|
|
|
|
|
|
|
|
const modelType = request.query.type ? BaseModel.modelNameToType(request.query.type) : BaseModel.TYPE_NOTE;
|
|
|
|
|
|
|
|
let results = [];
|
|
|
|
|
|
|
|
if (modelType !== BaseItem.TYPE_NOTE) {
|
|
|
|
const ModelClass = BaseItem.getClassByItemType(modelType);
|
|
|
|
const options:any = {};
|
|
|
|
const fields = requestFields(request, modelType);
|
|
|
|
if (fields.length) options.fields = fields;
|
|
|
|
const sqlQueryPart = query.replace(/\*/g, '%');
|
|
|
|
options.where = 'title LIKE ?';
|
|
|
|
options.whereParams = [sqlQueryPart];
|
|
|
|
options.caseInsensitive = true;
|
|
|
|
results = await ModelClass.all(options);
|
|
|
|
} else {
|
|
|
|
results = await SearchEngineUtils.notesForQuery(query, defaultLoadOptions(request, ModelType.Note));
|
|
|
|
}
|
|
|
|
|
2020-11-11 13:52:47 +02:00
|
|
|
return collectionToPaginatedResults(results, request);
|
2020-11-05 18:58:23 +02:00
|
|
|
}
|