簡體   English   中英

在 Node.js 中同時生成的發票具有相同的編號。 如何實現唯一性?

[英]Invoices have the same number when generated at the same time in Node.js. How to achieve uniqueness?

在我的 Node.js 應用程序中,我想啟用一個功能來生成帶有發票的 PDF。 一切正常,直到兩個或更多人同時(在不同的機器上)生成發票。 然后他們會收到具有相同編號的不同發票,例如發票編號。 355.這是將發票保存到MySQL的方法(使用Sequelize):

CCInvoice.max("invoiceNumber")
    .then(invoiceMaxNum => {
        if(isNaN(invoiceMaxNum)){
            invoiceMaxNum = 1;
        } else {
            invoiceMaxNum++;
        }

        CCInvoice.create({
            invoiceNumber: invoiceMaxNum,
            invoiceNetPrice: parseFloat(report.finalNetPrice),
            invoiceVAT: parseFloat(report.finalVAT),
            invoiceGrossPrice: parseFloat(report.finalGrossPrice),
            invoiceDate: new Date(Date.now())
        })
            .then(...)
            .catch(...)

主鍵是 id,它是 auto_increment,該值每 10 個數字(因為我在 Heroku 上使用 ClearDB)。 因為我必須從 350 左右的數字開始開具發票(以前的發票是手動開具的)並且因為 id 增加了 10,所以 id 和發票編號之間沒有簡單的關聯。

不幸的是,在 MySQL 中只有一列可以是 auto_increment。 我不確定如何確保所有請求的唯一性,無論有多少。 如果您有一些想法,請告訴我。

如果您想要一個唯一的數字,為什么不使用當前時間戳或簡單地使用 UUID?

這些數字只需要是唯一的,還是它們也需要是連續的? 或者人們也能記住的數字?

如果只是保證它是唯一的,那么使用 uuid 會讓你的生活簡單得多。 兩行代碼,你就完成了。

作為參考,我在 Sequelize 中使用了事務,並且代碼似乎可以正常工作。 我嘗試同時從兩台不同的機器生成發票,實際上它們有兩個不同的數字(400 和 401)。 對我有用的代碼:

let transaction = await sequelize.transaction({ autocommit: false });

try {

    let { count, rows } = await CCInvoice.findAndCountAll({
        attributes: ["invoiceNumber"],
        transaction: transaction
    })

    // Since the numeration in the system does not begin from 0 but from 329
    let invoiceMaxNum = count + 328 + 1;

    let invoice = await CCInvoice.create({
        invoiceNumber: invoiceMaxNum,
        invoiceNetPrice: parseFloat(report.finalNetPrice),
        invoiceVAT: parseFloat(report.finalVAT),
        invoiceGrossPrice: parseFloat(report.finalGrossPrice),
        invoiceDate: new Date(Date.now())
    })

    (...)

    await transaction.commit();

} 
catch(error) {
    console.log(error);
    await transaction.rollback();
}

我不確定這是否是最有效的解決方案,但現在它似乎有效。 如果您有任何建議或改進,請告訴我。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM