30560/backend/src/db/api/profiles.js
2025-04-08 12:00:52 +00:00

425 lines
10 KiB
JavaScript

const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class ProfilesDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const profiles = await db.profiles.create(
{
id: data.id || undefined,
username: data.username || null,
display_name: data.display_name || null,
bio: data.bio || null,
theme_mode: data.theme_mode || null,
importHash: data.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
await profiles.setUser(data.user || null, {
transaction,
});
await profiles.setLinks(data.links || [], {
transaction,
});
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.profiles.getTableName(),
belongsToColumn: 'avatar',
belongsToId: profiles.id,
},
data.avatar,
options,
);
return profiles;
}
static async bulkImport(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
// Prepare data - wrapping individual data transformations in a map() method
const profilesData = data.map((item, index) => ({
id: item.id || undefined,
username: item.username || null,
display_name: item.display_name || null,
bio: item.bio || null,
theme_mode: item.theme_mode || null,
importHash: item.importHash || null,
createdById: currentUser.id,
updatedById: currentUser.id,
createdAt: new Date(Date.now() + index * 1000),
}));
// Bulk create items
const profiles = await db.profiles.bulkCreate(profilesData, {
transaction,
});
// For each item created, replace relation files
for (let i = 0; i < profiles.length; i++) {
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.profiles.getTableName(),
belongsToColumn: 'avatar',
belongsToId: profiles[i].id,
},
data[i].avatar,
options,
);
}
return profiles;
}
static async update(id, data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const profiles = await db.profiles.findByPk(id, {}, { transaction });
const updatePayload = {};
if (data.username !== undefined) updatePayload.username = data.username;
if (data.display_name !== undefined)
updatePayload.display_name = data.display_name;
if (data.bio !== undefined) updatePayload.bio = data.bio;
if (data.theme_mode !== undefined)
updatePayload.theme_mode = data.theme_mode;
updatePayload.updatedById = currentUser.id;
await profiles.update(updatePayload, { transaction });
if (data.user !== undefined) {
await profiles.setUser(
data.user,
{ transaction },
);
}
if (data.links !== undefined) {
await profiles.setLinks(data.links, { transaction });
}
await FileDBApi.replaceRelationFiles(
{
belongsTo: db.profiles.getTableName(),
belongsToColumn: 'avatar',
belongsToId: profiles.id,
},
data.avatar,
options,
);
return profiles;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const profiles = await db.profiles.findAll({
where: {
id: {
[Op.in]: ids,
},
},
transaction,
});
await db.sequelize.transaction(async (transaction) => {
for (const record of profiles) {
await record.update({ deletedBy: currentUser.id }, { transaction });
}
for (const record of profiles) {
await record.destroy({ transaction });
}
});
return profiles;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const profiles = await db.profiles.findByPk(id, options);
await profiles.update(
{
deletedBy: currentUser.id,
},
{
transaction,
},
);
await profiles.destroy({
transaction,
});
return profiles;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
const profiles = await db.profiles.findOne({ where }, { transaction });
if (!profiles) {
return profiles;
}
const output = profiles.get({ plain: true });
output.links_profile = await profiles.getLinks_profile({
transaction,
});
output.avatar = await profiles.getAvatar({
transaction,
});
output.links = await profiles.getLinks({
transaction,
});
output.user = await profiles.getUser({
transaction,
});
return output;
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
let where = {};
const currentPage = +filter.page;
offset = currentPage * limit;
const orderBy = null;
const transaction = (options && options.transaction) || undefined;
let include = [
{
model: db.users,
as: 'user',
where: filter.user
? {
[Op.or]: [
{
id: {
[Op.in]: filter.user
.split('|')
.map((term) => Utils.uuid(term)),
},
},
{
firstName: {
[Op.or]: filter.user
.split('|')
.map((term) => ({ [Op.iLike]: `%${term}%` })),
},
},
],
}
: {},
},
{
model: db.links,
as: 'links',
required: false,
},
{
model: db.file,
as: 'avatar',
},
];
if (filter) {
if (filter.id) {
where = {
...where,
['id']: Utils.uuid(filter.id),
};
}
if (filter.username) {
where = {
...where,
[Op.and]: Utils.ilike('profiles', 'username', filter.username),
};
}
if (filter.display_name) {
where = {
...where,
[Op.and]: Utils.ilike(
'profiles',
'display_name',
filter.display_name,
),
};
}
if (filter.bio) {
where = {
...where,
[Op.and]: Utils.ilike('profiles', 'bio', filter.bio),
};
}
if (filter.active !== undefined) {
where = {
...where,
active: filter.active === true || filter.active === 'true',
};
}
if (filter.theme_mode) {
where = {
...where,
theme_mode: filter.theme_mode,
};
}
if (filter.links) {
const searchTerms = filter.links.split('|');
include = [
{
model: db.links,
as: 'links_filter',
required: searchTerms.length > 0,
where:
searchTerms.length > 0
? {
[Op.or]: [
{
id: {
[Op.in]: searchTerms.map((term) => Utils.uuid(term)),
},
},
{
title: {
[Op.or]: searchTerms.map((term) => ({
[Op.iLike]: `%${term}%`,
})),
},
},
],
}
: undefined,
},
...include,
];
}
if (filter.createdAtRange) {
const [start, end] = filter.createdAtRange;
if (start !== undefined && start !== null && start !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.gte]: start,
},
};
}
if (end !== undefined && end !== null && end !== '') {
where = {
...where,
['createdAt']: {
...where.createdAt,
[Op.lte]: end,
},
};
}
}
}
const queryOptions = {
where,
include,
distinct: true,
order:
filter.field && filter.sort
? [[filter.field, filter.sort]]
: [['createdAt', 'desc']],
transaction: options?.transaction,
logging: console.log,
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
try {
const { rows, count } = await db.profiles.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count,
};
} catch (error) {
console.error('Error executing query:', error);
throw error;
}
}
static async findAllAutocomplete(query, limit, offset) {
let where = {};
if (query) {
where = {
[Op.or]: [
{ ['id']: Utils.uuid(query) },
Utils.ilike('profiles', 'username', query),
],
};
}
const records = await db.profiles.findAll({
attributes: ['id', 'username'],
where,
limit: limit ? Number(limit) : undefined,
offset: offset ? Number(offset) : undefined,
orderBy: [['username', 'ASC']],
});
return records.map((record) => ({
id: record.id,
label: record.username,
}));
}
};