mizzkey/src/api/endpoints/users/search_by_username.js

65 lines
1.2 KiB
JavaScript
Raw Normal View History

2016-12-28 23:49:51 +01:00
'use strict';
/**
* Module dependencies
*/
import * as mongo from 'mongodb';
import User from '../../models/user';
import serialize from '../../serializers/user';
/**
* Search a user by username
*
2017-03-01 09:37:01 +01:00
* @param {any} params
* @param {any} me
* @return {Promise<any>}
2016-12-28 23:49:51 +01:00
*/
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
2017-01-17 03:11:22 +01:00
});
2016-12-28 23:49:51 +01:00
// Serialize
res(await Promise.all(users.map(async user =>
await serialize(user, me, { detail: true }))));
});