traxxx/src/users.js

57 lines
1.3 KiB
JavaScript
Raw Normal View History

2021-03-13 03:26:24 +00:00
'use strict';
const knex = require('./knex');
2021-03-15 02:30:47 +00:00
const { curateStash } = require('./stashes');
2021-03-13 03:26:24 +00:00
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,
2021-11-20 22:59:15 +00:00
stashes: user.stashes?.filter(Boolean).map((stash) => curateStash(stash)) || [],
2021-03-13 03:26:24 +00:00
};
return curatedUser;
}
2021-03-15 02:30:47 +00:00
async function fetchUser(userId, raw) {
2021-03-13 03:26:24 +00:00
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'))
2021-03-15 02:30:47 +00:00
.modify((builder) => {
if (typeof userId === 'number') {
builder.where('users.id', userId);
}
if (typeof userId === 'string') {
builder
.where('users.username', userId)
.orWhere('users.email', userId);
}
})
2021-03-13 03:26:24 +00:00
.leftJoin('users_roles', 'users_roles.role', 'users.role')
2021-03-15 02:30:47 +00:00
.leftJoin('stashes', 'stashes.user_id', 'users.id')
.groupBy('users.id', 'users_roles.role')
2021-03-13 03:26:24 +00:00
.first();
2021-03-15 02:30:47 +00:00
if (raw) {
return user;
}
2021-03-13 03:26:24 +00:00
return curateUser(user);
}
module.exports = {
curateUser,
fetchUser,
};