.transaction()
Fetch a preconfigured, deferred object hooked up to the sails-mysql or sails-postgresql adapter (and consequently the appropriate driver). (擷取一個預先配置、延遲的物件,該物件已連結至 sails-mysql 或 sails-postgresql 适配器(以及相應的驅動程式)。)
await datastore.transaction(during);
或
var result = await datastore.transaction(during);
參數 | 類型 | 詳細資訊 | |
---|---|---|---|
1 | during | 請參閱下方「during 用法」表格中的參數。 |
參數 | 類型 | 詳細資訊 | |
---|---|---|---|
1 | db | 租用的(事務性)資料庫連線。(有關如何使用此連線的更多資訊,請參閱.usingConnection() 。) |
請注意,在 Sails 1.1.0 之前的版本,
.transaction()
的建議用法是預期您的 "during" 程式碼在完成時呼叫一個回呼函式 (proceed
)。只要您實際上不在 "during" 程式碼的函數簽名中包含第二個參數,現在就沒有必要這樣做了。
類型 | 詳細資訊 |
---|---|
從 during 傳回的可選結果資料。換句話說,如果在您的 during 函數中您執行了 return 'foo'; ,那麼這將會是 'foo' 。 |
名稱 | 類型 | 何時? |
---|---|---|
UsageError | 如果傳入無效的內容,則拋出此錯誤。 | |
AdapterError | 如果資料庫适配器中發生錯誤,則拋出此錯誤。 | |
Error | 如果發生任何其他意外情況,則拋出此錯誤。 |
請參閱概念 > 模型與 ORM > 錯誤,以取得在 Sails 和 Waterline 中處理錯誤的範例。
從一個使用者的餘額中減去指定的金額,並將其加到另一個使用者的餘額中。
// e.g. in an action:
var flaverr = require('flaverr');
await sails.getDatastore()
.transaction(async (db)=> {
var myAccount = await BankAccount.findOne({ owner: this.req.session.userId })
.usingConnection(db);
if (!myAccount) {
throw new Error('Consistency violation: Database is corrupted-- logged in user record has gone missing');
}
var recipientAccount = await BankAccount.findOne({ owner: inputs.recipientId }).usingConnection(db)
if (!recipientAccount) {
throw flaverr('E_NO_SUCH_RECIPIENT', new Error('There is no recipient with that id'));
}
// Do the math to subtract from the logged-in user's account balance,
// and add to the recipient's bank account balance.
var myNewBalance = myAccount.balance - inputs.amount;
// If this would put the logged-in user's account balance below zero,
// then abort. (The transaction will be rolled back automatically.)
if (myNewBalance < 0) {
throw flaverr('E_INSUFFICIENT_FUNDS', new Error('Insufficient funds'));
}
// Update the current user's bank account
await BankAccount.update({ owner: this.req.session.userId })
.set({
balance: myNewBalance
})
.usingConnection(db);
// Update the recipient's bank account
await BankAccount.update({ owner: inputs.recipientId })
.set({
balance: recipientAccount.balance + inputs.amount
})
.usingConnection(db);
})
.intercept('E_INSUFFICIENT_FUNDS', ()=>'badRequest')
.intercept('E_NO_SUCH_RECIPIENT', ()=>'notFound');
請注意,上面的範例僅為示範;實際上,這種增量/減量邏輯也應包含資料列層級鎖定。不確定嗎?。