albatross 3.4.2 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/index.d.ts CHANGED
@@ -82,6 +82,7 @@ declare namespace albatross {
82
82
  collection<TSchema extends { _id: any }> (name: string): Collection<TSchema>
83
83
  grid (name?: string): Grid
84
84
  ping (timeout?: number): Promise<void>
85
+ transaction<T> (fn: (session: mongodb.ClientSession) => PromiseLike<T>): Promise<T>
85
86
  close (force?: boolean): Promise<void>
86
87
  }
87
88
 
package/lib/albatross.js CHANGED
@@ -99,6 +99,23 @@ class Albatross {
99
99
  }
100
100
  }
101
101
 
102
+ async transaction (fn) {
103
+ const client = await this[kConnect]()
104
+ const session = client.startSession()
105
+
106
+ let result
107
+
108
+ try {
109
+ await session.withTransaction(async (...args) => {
110
+ result = await fn(...args)
111
+ })
112
+ } finally {
113
+ session.endSession()
114
+ }
115
+
116
+ return result
117
+ }
118
+
102
119
  async close (force) {
103
120
  if (this[kClient] == null) return
104
121
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "albatross",
3
- "version": "3.4.2",
3
+ "version": "3.5.0",
4
4
  "license": "MIT",
5
5
  "author": "Linus Unnebäck <linus@folkdatorn.se>",
6
6
  "repository": "LinusU/node-albatross",
package/readme.md CHANGED
@@ -95,6 +95,26 @@ Send the `ping` command to the server, to check that the connection is still int
95
95
 
96
96
  Optionally accepts a timeout in milliseconds.
97
97
 
98
+ #### `.transaction(fn): Promise`
99
+
100
+ Runs a provided function within a transaction, retrying either the commit operation or entire transaction as needed (and when the error permits) to better ensure that the transaction can complete successfully.
101
+
102
+ Example:
103
+
104
+ ```js
105
+ const user = db.collection('user')
106
+
107
+ const result = await db.transaction(async (session) => {
108
+ await user.insert({ name: 'Linus', born: 1992 }, { session })
109
+ await user.insert({ name: 'Steve', born: 1955 }, { session })
110
+
111
+ return await user.findOne({ born: 1992 }, { session })
112
+ })
113
+
114
+ console.log('Hello ' + result.name)
115
+ //=> Hello Linus
116
+ ```
117
+
98
118
  #### `.close(): Promise<void>`
99
119
 
100
120
  Closes the connection to the server.