Skip to content

Instantly share code, notes, and snippets.

@kirilltitov
Created January 20, 2021 11:46
Show Gist options
  • Save kirilltitov/a25924931289381852757ae72d4486cd to your computer and use it in GitHub Desktop.
Save kirilltitov/a25924931289381852757ae72d4486cd to your computer and use it in GitHub Desktop.
import FDB
import NIO
enum E: Error {
case recordExists
}
let fdb = FDB()
let key = "somekey".bytes
// using blocking API
try fdb.withTransaction { tr in
guard try tr.get(key: key, snapshot: false, commit: false) == nil else {
throw E.recordExists
}
try tr.set(key: key, value: "somevalue".bytes, commit: true) as Void
}
// or if you're using NIO (which is, again, recommended)
let eventLoopGroup: EventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: System.coreCount)
let resultFuture: EventLoopFuture<Void> = fdb.withTransaction(on: eventLoopGroup.next()) { tr in
tr
.get(key: key, snapshot: false, commit: false)
.flatMapThrowing { (maybeValue: Bytes?) in
guard maybeValue == nil else {
throw E.recordExists
}
}
.flatMap {
tr.set(key: key, value: "somevalue".bytes, commit: true)
}
.map { _ in Void() }
}
public extension String {
var bytes: Bytes {
Bytes(self.utf8)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment