endpoint for fetching all users

This commit is contained in:
Erik 2022-11-21 12:49:46 +02:00
parent f0320d1350
commit e2aa998723
Signed by: Navy.gif
GPG Key ID: 811EC0CD80E7E5FB
2 changed files with 40 additions and 0 deletions

View File

@ -31,6 +31,21 @@ class UserDatabase extends AbstractUserDatabase {
// this.userCollection = this.db.collection(this._userColllection); // this.userCollection = this.db.collection(this._userColllection);
} }
async fetchUsers (page, amount = 10, query = {}) {
if (!page) throw new Error('Missing page number');
const data = await this.db.find('users', query, { limit: amount, skip: (page - 1) * amount });
const users = [];
for (const user of data) {
let u = this.cache.get(user._id);
if (!u) {
u = this._createUser(user);
this.cache.set(u.id, u);
}
users.push(u);
}
return users;
}
async fetchUser (id, force = false) { async fetchUser (id, force = false) {
if (!id) throw new Error('Missing token'); if (!id) throw new Error('Missing token');

View File

@ -0,0 +1,25 @@
const { ApiEndpoint } = require("../../interfaces");
class UsersEndpoint extends ApiEndpoint {
constructor (server) {
super(server, {
name: 'users',
path: '/users'
});
this.methods.push([ 'get', this.getUsers.bind(this), [ server.auth.createAuthoriser('administrator', 10) ]]);
}
async getUsers (req, res) {
const { query } = req;
const { amount, page } = query;
if (!page) return res.status(400).send('Missing page number');
const users = await this.server.users.fetchUsers(page, amount);
res.json(users.map(user => user.json));
}
}
module.exports = UsersEndpoint;