This commit is contained in:
seb
2026-08-02 19:01:00 +02:00
parent 787e411547
commit b890843445
10 changed files with 480 additions and 0 deletions

View File

@@ -0,0 +1,74 @@
import {
ADD_CATEGORY,
DELETE_CATEGORIES_BY_ARTICLE,
} from '../../sql/article.js';
import request from '../request.js';
import resolveCategoryAccess from '../category/resolveCategoryAccess.js';
import queryBySku from './queryBySku.js';
import resolveArticleBySku from './resolveArticleBySku.js';
export default function setCategoryIdsBySku(pool) {
const resolve = resolveArticleBySku(pool);
const categoryAccess = resolveCategoryAccess(pool);
const load = queryBySku(pool);
return async (googleAuthId, sku, categoryIds) => {
if (!Array.isArray(categoryIds)) {
throw new Error('Invalid categoryIds');
}
const seen = new Set();
const normalized = [];
for (const categoryId of categoryIds) {
if (!Number.isFinite(categoryId) || seen.has(categoryId)) {
throw new Error('Invalid categoryIds');
}
seen.add(categoryId);
normalized.push(categoryId);
}
const { articleId, languageId, companyId } = await resolve(
googleAuthId,
sku,
);
const tx = pool.transaction();
await tx.begin();
try {
for (const categoryId of normalized) {
// Ensures the category belongs to the same company as the article.
const access = await categoryAccess(googleAuthId, categoryId);
if (access.companyId !== companyId) {
throw new Error('Invalid categoryIds');
}
}
await request(pool, tx)
.input('articleId', articleId)
.query(DELETE_CATEGORIES_BY_ARTICLE);
for (const categoryId of normalized) {
await request(pool, tx)
.input('categoryId', categoryId)
.input('articleId', articleId)
.query(ADD_CATEGORY);
}
await tx.commit();
} catch (err) {
try {
await tx.rollback();
} catch {
// ignore
}
throw err;
}
const article = await load(articleId, languageId);
if (!article) {
throw new Error('Article not found');
}
return article;
};
}