u
This commit is contained in:
70
src/store/article/orderImages.js
Normal file
70
src/store/article/orderImages.js
Normal file
@@ -0,0 +1,70 @@
|
||||
import {
|
||||
LIST_HASHES_BY_ARTICLE,
|
||||
SET_TEMP_SORTS,
|
||||
UPDATE_SORT_BY_HASH,
|
||||
} from '../../sql/articlepic.js';
|
||||
import resolveArticleBySku from './resolveArticleBySku.js';
|
||||
import request from '../request.js';
|
||||
|
||||
export default function orderImages(pool) {
|
||||
const resolve = resolveArticleBySku(pool);
|
||||
|
||||
return async (googleAuthId, sku, { fullHashes }) => {
|
||||
if (!Array.isArray(fullHashes)) {
|
||||
throw new Error('Invalid image order');
|
||||
}
|
||||
|
||||
const { articleId } = await resolve(googleAuthId, sku);
|
||||
|
||||
const current = await pool
|
||||
.request()
|
||||
.input('articleId', articleId)
|
||||
.query(LIST_HASHES_BY_ARTICLE);
|
||||
|
||||
const existing = new Set(current.recordset.map((r) => r.fullHash));
|
||||
|
||||
if (fullHashes.length !== existing.size) {
|
||||
throw new Error('Invalid image order');
|
||||
}
|
||||
|
||||
const seen = new Set();
|
||||
for (const fullHash of fullHashes) {
|
||||
if (!existing.has(fullHash) || seen.has(fullHash)) {
|
||||
throw new Error('Invalid image order');
|
||||
}
|
||||
seen.add(fullHash);
|
||||
}
|
||||
|
||||
const tx = pool.transaction();
|
||||
await tx.begin();
|
||||
|
||||
try {
|
||||
await request(pool, tx)
|
||||
.input('articleId', articleId)
|
||||
.query(SET_TEMP_SORTS);
|
||||
|
||||
for (let sort = 0; sort < fullHashes.length; sort++) {
|
||||
const update = await request(pool, tx)
|
||||
.input('articleId', articleId)
|
||||
.input('fullHash', fullHashes[sort])
|
||||
.input('sort', sort)
|
||||
.query(UPDATE_SORT_BY_HASH);
|
||||
|
||||
if (!update.rowsAffected[0]) {
|
||||
throw new Error('Invalid image order');
|
||||
}
|
||||
}
|
||||
|
||||
await tx.commit();
|
||||
|
||||
return { fullHashes };
|
||||
} catch (err) {
|
||||
try {
|
||||
await tx.rollback();
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user