import { DefaultAzureCredential } from "@azure/identity"; import { BlobServiceClient } from "@azure/storage-blob"; export default async function handler(req, res) { if (req.method !== "POST") { res.status(405).json({ error: "Method not allowed" }); return; } const { container, blobName } = req.body; if (!container || !blobName) { res.status(400).json({ error: "Missing container or blobName" }); return; } try { const accountName = process.env.AZURE_STORAGE_ACCOUNT_NAME; const creds = new DefaultAzureCredential(); const blobServiceClient = new BlobServiceClient( `https://${accountName}.blob.core.windows.net`, creds ); const containerClient = blobServiceClient.getContainerClient(container); const blockBlobClient = containerClient.getBlockBlobClient(blobName); // Download blob content const downloadResponse = await blockBlobClient.download(0); const downloaded = await streamToString( downloadResponse.readableStreamBody ); // Parse JSON const json = JSON.parse(downloaded); // Remove repComplete element if it exists if ("repComplete" in json) { delete json.repComplete; } const tags = { containerid: json.containerID, caseID: json.ticketnumber, blobType: "Representation", }; // Convert back to string const updatedContent = JSON.stringify(json, null, 2); // Upload updated content (overwrite) await blockBlobClient.upload( updatedContent, Buffer.byteLength(updatedContent), { blobHTTPHeaders: { blobContentType: "application/json" }, } ); console.log("the tags:", tags); const withTags = await blockBlobClient.setTags(tags); const withMeta = await blockBlobClient.setMetadata(tags); res.status(200).json({ message: "repComplete removed successfully" }); } catch (error) { console.error("Error editing rep.json:", error); res.status(500).json({ error: "Failed to edit rep.json" }); } } // Helper function to read stream to string async function streamToString(readableStream) { return new Promise((resolve, reject) => { const chunks = []; readableStream.on("data", (data) => { chunks.push(data.toString()); }); readableStream.on("end", () => { resolve(chunks.join("")); }); readableStream.on("error", reject); }); }