traxxx/src/users.js

57 lines
1.3 KiB
JavaScript
Executable File

'use strict';
const knex = require('./knex');
const { curateStash } = require('./stashes');
function curateUser(user) {
if (!user) {
return null;
}
const ability = [...(user.role_abilities || []), ...(user.abilities || [])];
const curatedUser = {
id: user.id,
username: user.username,
email: user.email,
emailVerified: user.email_verified,
identityVerified: user.identity_verified,
ability,
createdAt: user.created_at,
stashes: user.stashes?.filter(Boolean).map((stash) => curateStash(stash)) || [],
};
return curatedUser;
}
async function fetchUser(userId, raw) {
const user = await knex('users')
.select(knex.raw('users.*, users_roles.abilities as role_abilities, COALESCE(json_agg(stashes ORDER BY stashes.created_at) FILTER (WHERE stashes.id IS NOT NULL), \'[]\') as stashes'))
.modify((builder) => {
if (typeof userId === 'number') {
builder.where('users.id', userId);
}
if (typeof userId === 'string') {
builder
.where('users.username', userId)
.orWhere('users.email', userId);
}
})
.leftJoin('users_roles', 'users_roles.role', 'users.role')
.leftJoin('stashes', 'stashes.user_id', 'users.id')
.groupBy('users.id', 'users_roles.role')
.first();
if (raw) {
return user;
}
return curateUser(user);
}
module.exports = {
curateUser,
fetchUser,
};