mirror of
https://iceshrimp.dev/limepotato/jormungandr-bite.git
synced 2024-11-19 00:17:35 -07:00
64 lines
1.2 KiB
JavaScript
64 lines
1.2 KiB
JavaScript
'use strict';
|
|
|
|
/**
|
|
* Module dependencies
|
|
*/
|
|
import * as mongo from 'mongodb';
|
|
import User from '../../models/user';
|
|
import serialize from '../../serializers/user';
|
|
|
|
/**
|
|
* Search a user by username
|
|
*
|
|
* @param {any} params
|
|
* @param {any} me
|
|
* @return {Promise<any>}
|
|
*/
|
|
module.exports = (params, me) =>
|
|
new Promise(async (res, rej) =>
|
|
{
|
|
// Get 'query' parameter
|
|
let query = params.query;
|
|
if (query === undefined || query === null || query.trim() === '') {
|
|
return rej('query is required');
|
|
}
|
|
|
|
query = query.trim();
|
|
|
|
if (!/^[a-zA-Z0-9-]+$/.test(query)) {
|
|
return rej('invalid query');
|
|
}
|
|
|
|
// Get 'limit' parameter
|
|
let limit = params.limit;
|
|
if (limit !== undefined && limit !== null) {
|
|
limit = parseInt(limit, 10);
|
|
|
|
// From 1 to 100
|
|
if (!(1 <= limit && limit <= 100)) {
|
|
return rej('invalid limit range');
|
|
}
|
|
} else {
|
|
limit = 10;
|
|
}
|
|
|
|
// Get 'offset' parameter
|
|
let offset = params.offset;
|
|
if (offset !== undefined && offset !== null) {
|
|
offset = parseInt(offset, 10);
|
|
} else {
|
|
offset = 0;
|
|
}
|
|
|
|
const users = await User
|
|
.find({
|
|
username_lower: new RegExp(query.toLowerCase())
|
|
}, {
|
|
limit: limit,
|
|
skip: offset
|
|
});
|
|
|
|
// Serialize
|
|
res(await Promise.all(users.map(async user =>
|
|
await serialize(user, me, { detail: true }))));
|
|
});
|