Skip to content

Commit 69040b3

Browse files
author
Chris Cho
committed
DOCSP-32718: add CodeWhisperer comments to transactions code snippets (#769)
* DOCSP-32718: add CodeWhisperer comments to transactions code snippets (cherry picked from commit 4db5c08)
1 parent 65c529f commit 69040b3

File tree

2 files changed

+46
-8
lines changed

2 files changed

+46
-8
lines changed

source/code-snippets/transactions/txn-core.js

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
1+
/* Performs multiple write operations in a transaction */
2+
13
const { MongoError, MongoClient } = require('mongodb');
24

3-
// drop collections
5+
// Drop the "customers", "inventory", and "orders" collections from the "testdb" database
46
async function cleanUp(client) {
57
await Promise.all( ['customers', 'inventory', 'orders'].map(async c => {
68
try {
79
const coll = client.db('testdb').collection(c);
810
await coll.drop();
9-
} catch(e) {}
11+
} catch(e) {} // Ignore any exceptions
1012
}));
1113
}
1214

@@ -15,17 +17,21 @@ async function setup(client) {
1517
const customerColl = client.db('testdb').collection('customers');
1618
const inventoryColl = client.db('testdb').collection('inventory');
1719

20+
// Insert order data for customer "98765" in the customers collection
1821
await customerColl.insertOne({ _id: 98765, orders: [] });
1922

23+
// Insert inventory data for "sunblock" and "beach towel"
2024
await inventoryColl.insertMany([
2125
{ name: 'sunblock', sku: 5432, qty: 85 },
2226
{ name: 'beach towel', sku: 7865, qty: 41 },
2327
]);
2428
} catch (e) {
29+
// Print the exception if one was thrown
2530
console.log('Unable to insert test data: ' + e);
2631
}
2732
}
2833

34+
// Print all documents in the "customers", "inventory", and "orders" collections
2935
async function queryData() {
3036
const uri = process.env.MONGODB_URI;
3137
const client = new MongoClient(uri);
@@ -36,23 +42,29 @@ async function queryData() {
3642
}, client));
3743

3844
} finally {
45+
// Close the database connection
3946
client.close();
4047
}
4148
}
4249

4350
// start placeOrder
4451
async function placeOrder(client, cart, payment) {
52+
// Specify readConcern, writeConcern, and readPreference transaction options
4553
const transactionOptions = {
4654
readConcern: { level: 'snapshot' },
4755
writeConcern: { w: 'majority' },
4856
readPreference: 'primary'
4957
};
5058

59+
// Start the session
5160
const session = client.startSession();
5261
try {
62+
// Start the transaction in the session, specifying the transaction options
5363
session.startTransaction(transactionOptions);
5464

5565
const ordersCollection = client.db('testdb').collection('orders');
66+
// Within the session, insert an order that contains information about the
67+
// customer, items purchased, and the total payment.
5668
const orderResult = await ordersCollection.insertOne(
5769
{
5870
customer: payment.customer,
@@ -63,21 +75,26 @@ async function placeOrder(client, cart, payment) {
6375
);
6476

6577
const inventoryCollection = client.db('testdb').collection('inventory');
78+
79+
// Within the session, for each item purchased, decrement the purchased quantity in the "inventory" collection.
80+
// Cancel the transaction when you have insufficient inventory or if the item SKU does not exist.
6681
for (let i=0; i<cart.length; i++) {
6782
const item = cart[i];
6883

69-
// Cancel the transaction when you have insufficient inventory
84+
// Retrieve the inventory information for the item
7085
const checkInventory = await inventoryCollection.findOne(
7186
{
7287
sku: item.sku,
7388
qty: { $gte: item.qty }
7489
},
7590
{ session }
7691
)
92+
// Throw an exception if the item lacks sufficient quantity or SKU does not exist.
7793
if (checkInventory === null) {
7894
throw new Error('Insufficient quantity or SKU not found.');
7995
}
8096

97+
// Decrement the inventory of the item by the amount specified in the order.
8198
await inventoryCollection.updateOne(
8299
{ sku: item.sku },
83100
{ $inc: { 'qty': -item.qty }},
@@ -86,15 +103,23 @@ async function placeOrder(client, cart, payment) {
86103
}
87104

88105
const customerCollection = client.db('testdb').collection('customers');
106+
107+
// Within the session, add the order details to the "orders" array of the customer document.
89108
await customerCollection.updateOne(
90109
{ _id: payment.customer },
91110
{ $push: { orders: orderResult.insertedId }},
92111
{ session }
93112
);
113+
114+
// Commit the transaction to apply all updates performed within it
94115
await session.commitTransaction();
95116
console.log('Transaction successfully committed.');
96117

97118
} catch (error) {
119+
/*
120+
Handle any exceptions thrown during the transaction and end the
121+
transaction. Roll back all the updates performed in the transaction.
122+
*/
98123
if (error instanceof MongoError && error.hasErrorLabel('UnknownTransactionCommitResult')) {
99124
// add your logic to retry or handle the error
100125
}
@@ -105,28 +130,41 @@ async function placeOrder(client, cart, payment) {
105130
}
106131
await session.abortTransaction();
107132
} finally {
133+
// End the session so that no further calls can be made on it
108134
await session.endSession();
109135
}
110136
}
111137
// end placeOrder
112138

139+
140+
// Run the full transaction example
113141
async function run() {
114142
const uri = process.env.MONGODB_URI;
115143
const client = new MongoClient(uri);
116144

145+
// Call a method that removes data from prior runs of this example
117146
await cleanUp(client);
147+
148+
// Call a method that creates sample inventory data for this example
118149
await setup(client);
119150

151+
// Create sample data for a customer's shopping cart that includes "sunblock" and "beach towel" items
120152
const cart = [
121153
{ name: 'sunblock', sku: 5432, qty: 1, price: 5.19 },
122154
{ name: 'beach towel', sku: 7865, qty: 2, price: 15.99 }
123155
];
156+
157+
// Create sample data for a customer's payment, calculated from the contents of their cart
124158
const payment = { customer: 98765, total: 37.17 };
125159

126160
try {
161+
// Call the method that updates the customer and inventory in a transaction
127162
await placeOrder(client, cart, payment);
128163
} finally {
164+
// Call a method that removes data from prior runs of this example
129165
await cleanUp(client);
166+
167+
// Close the database connection
130168
await client.close();
131169
}
132170
}

source/fundamentals/transactions.txt

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ Overview
1616
In this guide, you can learn how to use the
1717
{+driver-short+} to perform **transactions**. Transactions allow you
1818
to run a series of operations that do not change any data until the
19-
entire transaction is committed. If any operation in the transaction fails, the
19+
entire transaction is committed. If any operation in the transaction fails, the
2020
driver aborts the transaction and discards all data changes before they
2121
ever become visible. This feature is called **atomicity**.
2222

@@ -247,16 +247,16 @@ shows how you can perform the following:
247247
.. literalinclude:: /code-snippets/transactions/txn-core.js
248248
:language: javascript
249249
:linenos:
250-
:emphasize-lines: 2-6,8,10,19,32,41,49,51,55-59,63,65
250+
:emphasize-lines: 3-7,13,24,40,51,61,65,73-74,76-77,81,84
251251
:start-after: start placeOrder
252252
:end-before: end placeOrder
253253

254254
You must pass the session object to each CRUD operation that
255255
you want to run on that session.
256256

257257
.. important:: Use a Session with the Client That Started It
258-
259-
Starting in version 6.0 of the {+driver-short+}, the driver
258+
259+
Starting in version 6.0 of the {+driver-short+}, the driver
260260
throws an error if you provide a session from one ``MongoClient``
261261
instance to a different client instance.
262262

@@ -267,7 +267,7 @@ you want to run on that session.
267267

268268
.. code-block:: js
269269
:emphasize-lines: 2
270-
270+
271271
const session = client1.startSession();
272272
client2.db('myDB').collection('myColl').insertOne({ name: 'Jane Eyre' }, { session });
273273

0 commit comments

Comments
 (0)