Sharkey/src/server/api/endpoints/notes/search.ts

80 lines
1.4 KiB
TypeScript
Raw Normal View History

2018-07-04 07:21:30 +03:00
import $ from 'cafy';
import * as mongo from 'mongodb';
import Note from '../../../../models/note';
import { packMany } from '../../../../models/note';
2018-07-04 07:21:30 +03:00
import es from '../../../../db/elasticsearch';
2018-11-02 06:47:44 +02:00
import define from '../../define';
import { apiLogger } from '../../logger';
2018-07-04 07:21:30 +03:00
2018-11-02 05:49:08 +02:00
export const meta = {
desc: {
'ja-JP': '投稿を検索します。',
'en-US': 'Search notes.'
},
requireCredential: false,
params: {
query: {
validator: $.str
},
2018-07-04 07:21:30 +03:00
2018-11-02 05:49:08 +02:00
limit: {
2019-02-13 09:33:07 +02:00
validator: $.optional.num.range(1, 100),
2018-11-02 05:49:08 +02:00
default: 10
},
2018-07-04 07:21:30 +03:00
2018-11-02 05:49:08 +02:00
offset: {
2019-02-13 09:33:07 +02:00
validator: $.optional.num.min(0),
2018-11-02 05:49:08 +02:00
default: 0
}
}
};
2018-11-02 06:47:44 +02:00
export default define(meta, (ps, me) => new Promise(async (res, rej) => {
if (es == null) return rej('searching not available');
2018-07-04 07:21:30 +03:00
es.search({
index: 'misskey',
type: 'note',
body: {
2018-11-02 05:49:08 +02:00
size: ps.limit,
from: ps.offset,
2018-07-04 07:21:30 +03:00
query: {
simple_query_string: {
fields: ['text'],
2018-11-02 05:49:08 +02:00
query: ps.query,
2018-07-04 07:21:30 +03:00
default_operator: 'and'
}
},
sort: [
{ _doc: 'desc' }
]
}
}, async (error, response) => {
if (error) {
apiLogger.error(error);
2018-07-04 07:21:30 +03:00
return res(500);
}
if (response.hits.total === 0) {
return res([]);
}
const hits = response.hits.hits.map(hit => new mongo.ObjectID(hit._id));
// Fetch found notes
const notes = await Note.find({
_id: {
$in: hits
}
}, {
sort: {
_id: -1
}
});
2018-07-04 07:21:30 +03:00
res(await packMany(notes, me));
2018-07-04 07:21:30 +03:00
});
2018-11-02 06:47:44 +02:00
}));