async function appendToJson()

in wiki-interface/lib/gcs/gcs.js [150:203]


async function appendToJson(transId, userMessage, aiMessage) {
    // Set filename
    let fileName = "history_" + transId + ".txt";

    // Create a new Storage client
    const storage = new Storage();

    let bucketName = configFile.getBucket();

    // Create a reference to the file in the bucket
    const file = storage.bucket(bucketName).file(fileName);

    // Get the existing JSON data from the file
    let [contents] = await file.download();

    let existingData = contents.toString();

    let existingJSON = {};
    try {
        existingJSON = JSON.parse(existingData);
    } catch (err) {
        // File is empty, so initialize with an empty array
        existingJSON = [];
    }

    let thisEntry = {
        role: "user",
        message: userMessage
    }
    // Append the new object to the existing data
    existingJSON.push(thisEntry);

    thisEntry = {
        role: "model",
        message: fileUtils.cleanFile(aiMessage)
    }
    // Append the new object to the existing data
    existingJSON.push(thisEntry);

    // Convert the updated JSON data to a string
    const updatedJSON = JSON.stringify(existingJSON);

    try {
        // Upload the updated JSON string to the file
        await file.save(updatedJSON, {
            metadata: {
                contentType: 'application/json',
            },
        });
    } catch (err) {
        console.error(`Erro ao ler o conteúdo do arquivo ${fileName}:`, err);
    }

}