2017-03-08 19:50:09 +01:00
|
|
|
import $ from 'cafy';
|
2018-06-18 02:54:53 +02:00
|
|
|
import User, { pack, ILocalUser } from '../../../../models/user';
|
2016-12-28 23:49:51 +01:00
|
|
|
const escapeRegexp = require('escape-regexp');
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Search a user
|
|
|
|
*/
|
2018-06-18 02:54:53 +02:00
|
|
|
module.exports = (params: any, me: ILocalUser) => new Promise(async (res, rej) => {
|
2016-12-28 23:49:51 +01:00
|
|
|
// Get 'query' parameter
|
2018-05-02 11:06:16 +02:00
|
|
|
const [query, queryError] = $.str.pipe(x => x != '').get(params.query);
|
2017-03-02 23:47:14 +01:00
|
|
|
if (queryError) return rej('invalid query param');
|
2016-12-28 23:49:51 +01:00
|
|
|
|
|
|
|
// Get 'max' parameter
|
2018-07-05 16:36:07 +02:00
|
|
|
const [max = 10, maxErr] = $.num.optional.range(1, 30).get(params.max);
|
2017-03-02 23:47:14 +01:00
|
|
|
if (maxErr) return rej('invalid max param');
|
2016-12-28 23:49:51 +01:00
|
|
|
|
|
|
|
const escapedQuery = escapeRegexp(query);
|
|
|
|
|
|
|
|
// Search users
|
|
|
|
const users = await User
|
|
|
|
.find({
|
2018-06-17 09:40:18 +02:00
|
|
|
host: null,
|
2016-12-28 23:49:51 +01:00
|
|
|
$or: [{
|
2018-03-29 07:48:47 +02:00
|
|
|
usernameLower: new RegExp(escapedQuery.replace('@', '').toLowerCase())
|
2016-12-28 23:49:51 +01:00
|
|
|
}, {
|
|
|
|
name: new RegExp(escapedQuery)
|
|
|
|
}]
|
2017-02-16 03:20:41 +01:00
|
|
|
}, {
|
|
|
|
limit: max
|
2017-01-17 03:11:22 +01:00
|
|
|
});
|
2016-12-28 23:49:51 +01:00
|
|
|
|
|
|
|
// Serialize
|
2018-06-18 02:54:53 +02:00
|
|
|
res(await Promise.all(users.map(user => pack(user, me, { detail: true }))));
|
|
|
|
});
|