Created
January 20, 2021 11:46
-
-
Save kirilltitov/a25924931289381852757ae72d4486cd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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