69 lines
1.8 KiB
JavaScript
Executable File
69 lines
1.8 KiB
JavaScript
Executable File
import { knexOwner as knex } from './knex.js';
|
|
import { curateStash } from './stashes.js';
|
|
import { HttpError } from './errors.js';
|
|
|
|
export function curateUser(user, assets = {}) {
|
|
if (!user) {
|
|
return null;
|
|
}
|
|
|
|
const curatedStashes = assets.stashes?.filter(Boolean).map((stash) => curateStash(stash)) || [];
|
|
|
|
const curatedUser = {
|
|
id: user.id,
|
|
username: user.username,
|
|
email: user.email,
|
|
emailVerified: user.email_verified,
|
|
identityVerified: user.identity_verified,
|
|
avatar: `/media/avatars/${user.id}_${user.username}.png`,
|
|
createdAt: user.created_at,
|
|
stashes: curatedStashes,
|
|
primaryStash: curatedStashes.find((stash) => stash.isPrimary),
|
|
};
|
|
|
|
return curatedUser;
|
|
}
|
|
|
|
function whereUser(builder, userId, options = {}) {
|
|
if (Number.isNaN(Number(userId))) {
|
|
builder.where(knex.raw('lower(users.username)'), userId.toLowerCase());
|
|
|
|
if (options.email) {
|
|
builder.orWhere(knex.raw('lower(users.email)'), userId.toLowerCase());
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
builder.where('users.id', Number(userId));
|
|
}
|
|
|
|
export async function fetchUser(userId, options = {}, reqUser) {
|
|
const user = await knex('users')
|
|
.select(knex.raw('users.*, users_roles.abilities as role_abilities'))
|
|
.modify((builder) => whereUser(builder, userId, options))
|
|
.leftJoin('users_roles', 'users_roles.role', 'users.role')
|
|
.groupBy('users.id', 'users_roles.role')
|
|
.first();
|
|
|
|
if (!user) {
|
|
throw new HttpError(`User '${userId}' not found`, 404);
|
|
}
|
|
|
|
const stashes = await knex('stashes')
|
|
.select('stashes.*', 'stashes_meta.*')
|
|
.leftJoin('stashes_meta', 'stashes_meta.stash_id', 'stashes.id')
|
|
.where('user_id', user.id)
|
|
.modify((builder) => {
|
|
if (reqUser?.id !== user.id && !options.includeStashes) {
|
|
builder.where('public', true);
|
|
}
|
|
});
|
|
|
|
if (options.raw) {
|
|
return { user, stashes };
|
|
}
|
|
|
|
return curateUser(user, { stashes });
|
|
}
|