|
| 1 | +const { MongoClient } = require('mongodb'); |
| 2 | + |
| 3 | +async function cleanUp(client) { |
| 4 | + try { |
| 5 | + const customersColl = client.db('testdb').collection('customers'); |
| 6 | + await customersColl.drop(); |
| 7 | + } catch(e) {} |
| 8 | + try { |
| 9 | + const inventoryColl = client.db('testdb').collection('inventory'); |
| 10 | + await inventoryColl.drop(); |
| 11 | + } catch(e) {} |
| 12 | + try { |
| 13 | + const ordersCollection = client.db('testdb').collection('orders') |
| 14 | + await ordersCollection.drop(); |
| 15 | + } catch(e) {} |
| 16 | +} |
| 17 | + |
| 18 | +async function setup(client) { |
| 19 | + try { |
| 20 | + const customerColl = client.db('testdb').collection('customers'); |
| 21 | + const inventoryColl = client.db('testdb').collection('inventory'); |
| 22 | + |
| 23 | + await customerColl.insertOne({ _id: 98765, orders: [] }); |
| 24 | + |
| 25 | + await inventoryColl.insertMany([ |
| 26 | + { name: 'sunblock', sku: 5432, qty: 85 }, |
| 27 | + { name: 'beach towel', sku: 7865, qty: 41 }, |
| 28 | + ]); |
| 29 | + } catch (e) { |
| 30 | + console.log('Unable to insert test data: ' + e); |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +async function queryData() { |
| 35 | + const uri = process.env.MONGODB_URI; |
| 36 | + const client = new MongoClient(uri, { useUnifiedTopology: true }); |
| 37 | + try { |
| 38 | + await client.connect(); |
| 39 | + await Promise.all(['customers', 'inventory', 'orders'].map(async c => { |
| 40 | + const coll = client.db('testdb').collection(c); |
| 41 | + console.log(JSON.stringify(await coll.find().toArray())); |
| 42 | + }, client)); |
| 43 | + } finally { |
| 44 | + client.close(); |
| 45 | + } |
| 46 | +} |
| 47 | + |
| 48 | +// start callback |
| 49 | +async function placeOrder(client, session, cart, payment) { |
| 50 | + const ordersCollection = client.db('testdb').collection('orders'); |
| 51 | + const orderResult = await ordersCollection.insertOne( |
| 52 | + { |
| 53 | + customer: payment.customer, |
| 54 | + items: cart, |
| 55 | + total: payment.total, |
| 56 | + }, |
| 57 | + { session } |
| 58 | + ); |
| 59 | + |
| 60 | + const inventoryCollection = client.db('testdb').collection('inventory'); |
| 61 | + for (let i=0; i<cart.length; i++) { |
| 62 | + const item = cart[i]; |
| 63 | + |
| 64 | + // Cancel the transaction when you have insufficient inventory |
| 65 | + const checkInventory = await inventoryCollection.findOne( |
| 66 | + { |
| 67 | + sku: item.sku, |
| 68 | + qty: { $gte: item.qty } |
| 69 | + }, |
| 70 | + { session } |
| 71 | + ); |
| 72 | + |
| 73 | + if (checkInventory === null) { |
| 74 | + await session.abortTransaction(); |
| 75 | + console.error('Insufficient quantity or SKU not found.'); |
| 76 | + } |
| 77 | + |
| 78 | + await inventoryCollection.updateOne( |
| 79 | + { sku: item.sku }, |
| 80 | + { $inc: { 'qty': -item.qty }}, |
| 81 | + { session } |
| 82 | + ); |
| 83 | + } |
| 84 | + |
| 85 | + const customerCollection = client.db('testdb').collection('customers'); |
| 86 | + await customerCollection.updateOne( |
| 87 | + { _id: payment.customer }, |
| 88 | + { $push: { orders: orderResult.insertedId }}, |
| 89 | + { session } |
| 90 | + ); |
| 91 | +} |
| 92 | +// end callback |
| 93 | + |
| 94 | +const uri = process.env.MONGODB_URI; |
| 95 | +const client = new MongoClient(uri, { useUnifiedTopology: true }); |
| 96 | + |
| 97 | +async function run() { |
| 98 | + /* Test code: uncomment block to run |
| 99 | + await client.connect(); |
| 100 | + await cleanUp(client); |
| 101 | + await setup(client); |
| 102 | +
|
| 103 | + const cart = [ |
| 104 | + { name: 'sunblock', sku: 5432, qty: 1, price: 5.19 }, |
| 105 | + { name: 'beach towel', sku: 7865, qty: 2, price: 15.99 } |
| 106 | + ]; |
| 107 | + const payment = { customer: 98765, total: 37.17 }; |
| 108 | +
|
| 109 | + const transactionOptions = { |
| 110 | + readPreference: 'primary', |
| 111 | + readConcern: { level: 'local' }, |
| 112 | + writeConcern: { w: 'majority' }, |
| 113 | + maxCommitTimeMS: 1000 |
| 114 | + }; |
| 115 | +
|
| 116 | + const session = client.startSession(); |
| 117 | + try { |
| 118 | + await session.withTransaction(async () => { |
| 119 | + await placeOrder(client, session, cart, payment) |
| 120 | + }, transactionOptions); |
| 121 | + } catch(error) { |
| 122 | + console.log('Encountered an error during the transaction: ' + error); |
| 123 | + } finally { |
| 124 | + await session.endSession(); |
| 125 | + } |
| 126 | + await client.close(); |
| 127 | + */ |
| 128 | + |
| 129 | + // start session |
| 130 | + const transactionOptions = { |
| 131 | + readPreference: 'primary', |
| 132 | + readConcern: { level: 'local' }, |
| 133 | + writeConcern: { w: 'majority' }, |
| 134 | + maxCommitTimeMS: 1000 |
| 135 | + }; |
| 136 | + |
| 137 | + const session = client.startSession(); |
| 138 | + try { |
| 139 | + await session.withTransaction( |
| 140 | + async (session) => { /* your transaction here */ }, |
| 141 | + transactionOptions); |
| 142 | + } catch(error) { |
| 143 | + console.log('Encountered an error during the transaction: ' + error); |
| 144 | + } finally { |
| 145 | + await session.endSession(); |
| 146 | + } |
| 147 | + // end session |
| 148 | +} |
| 149 | +run().then(() => queryData()); |
0 commit comments