feat: manage files via manifestattachment with auth and cascade trigger, format API.md method signatures

This commit is contained in:
seb
2026-09-16 16:49:59 +02:00
parent 8b97948a75
commit 8f23dd8c75
14 changed files with 2058 additions and 1362 deletions

View File

@@ -0,0 +1,99 @@
import { CREATE_FILE, CREATE_ATTACHMENT } from '../../sql/manifestattachment.js';
import resolveSelectedCompanyAccess from '../companyuser/resolveSelectedCompanyAccess.js';
import resolveManifestAccess from './resolveManifestAccess.js';
import request from '../request.js';
export default function add(pool) {
const access = resolveSelectedCompanyAccess(pool);
const manifestAccess = resolveManifestAccess(pool);
/**
* Attaches a file to an existing manifest.
*
* @param {number} googleAuthId - The id of the Google auth user.
* @param {number} manifestId - The id of the manifest.
* @param {object} input - The file data.
* @param {string} input.mimetype - The MIME type of the file (e.g. `'application/pdf'`).
* @param {string} input.name - The file name.
* @param {Buffer} input.content - The file content.
* @returns {Promise<object>} The created attachment record.
* @throws {Error} If the manifest is not found or file input is invalid.
*
* @example
* const attachment = await store.manifestattachment.add(42, 1, {
* mimetype: 'application/pdf',
* name: 'invoice.pdf',
* content: fileBuffer,
* });
* // => { id, manifestId, fileId, mimetype, name }
*/
return async (googleAuthId, manifestId, input, ...rest) => {
let rawMimetype, rawName, rawContent;
if (typeof input === 'object' && input !== null && !Buffer.isBuffer(input)) {
rawMimetype = input.mimetype;
rawName = input.name;
rawContent = input.content;
} else {
rawMimetype = input;
rawName = rest[0];
rawContent = rest[1];
}
const mimetype = typeof rawMimetype === 'string' ? rawMimetype.trim() : null;
if (!mimetype) {
throw new Error('Mimetype required');
}
const name = typeof rawName === 'string' ? rawName.trim() : null;
if (!name) {
throw new Error('File name required');
}
if (rawContent == null) {
throw new Error('Content required');
}
const content = Buffer.isBuffer(rawContent)
? rawContent
: Buffer.from(rawContent);
const { companyId } = await access(googleAuthId);
await manifestAccess(companyId, manifestId);
const tx = pool.transaction();
await tx.begin();
try {
const fileRes = await request(pool, tx)
.input('mimetype', mimetype)
.input('name', name)
.input('content', content)
.query(CREATE_FILE);
const fileId = fileRes.recordset[0].id;
const attachmentRes = await request(pool, tx)
.input('manifestId', manifestId)
.input('fileId', fileId)
.query(CREATE_ATTACHMENT);
const attachmentId = attachmentRes.recordset[0].id;
await tx.commit();
return {
id: attachmentId,
manifestId,
fileId,
mimetype,
name,
};
} catch (err) {
try {
await tx.rollback();
} catch {
// ignore
}
throw err;
}
};
}