37980-vm/backend/src/db/api/wishlists.js
2026-01-30 17:40:21 +00:00

113 lines
3.1 KiB
JavaScript

const db = require('../models');
const Utils = require('../utils');
const Sequelize = db.Sequelize;
const Op = Sequelize.Op;
module.exports = class WishlistsDBApi {
static async create(data, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const wishlists = await db.wishlists.create(
{
id: data.id || undefined,
userId: currentUser.id,
productId: data.product,
createdById: currentUser.id,
updatedById: currentUser.id,
},
{ transaction },
);
return wishlists;
}
static async deleteByIds(ids, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const wishlists = await db.wishlists.findAll({
where: {
id: {
[Op.in]: ids,
},
userId: currentUser.id, // Only allow deleting own wishlist items
},
transaction,
});
for (const record of wishlists) {
await record.destroy({ transaction });
}
return wishlists;
}
static async remove(id, options) {
const currentUser = (options && options.currentUser) || { id: null };
const transaction = (options && options.transaction) || undefined;
const record = await db.wishlists.findOne({
where: {
id,
userId: currentUser.id
},
transaction
});
if (record) {
await record.destroy({ transaction });
}
return record;
}
static async findBy(where, options) {
const transaction = (options && options.transaction) || undefined;
return await db.wishlists.findOne({ where, transaction });
}
static async findAll(filter, options) {
const limit = filter.limit || 0;
let offset = 0;
const currentPage = +filter.page || 0;
offset = currentPage * limit;
const currentUser = (options && options.currentUser) || { id: null };
let where = {
userId: currentUser.id // Always filter by current user
};
if (filter.product) {
where.productId = Utils.uuid(filter.product);
}
const queryOptions = {
where,
include: [
{
model: db.products,
as: 'product',
}
],
distinct: true,
order: [['createdAt', 'desc']],
transaction: options?.transaction,
};
if (!options?.countOnly) {
queryOptions.limit = limit ? Number(limit) : undefined;
queryOptions.offset = offset ? Number(offset) : undefined;
}
const { rows, count } = await db.wishlists.findAndCountAll(queryOptions);
return {
rows: options?.countOnly ? [] : rows,
count: count
};
}
};