|
2 | 2 | import Foundation |
3 | 3 | import NIO |
4 | 4 |
|
| 5 | +private let lock = Lock() |
5 | 6 | private var translators: [ConnectionIdentifier : IndexCursorTranslator] = [:] |
6 | 7 |
|
| 8 | +private func withTranslator<T>(for connectionIdentifier: ConnectionIdentifier, |
| 9 | + using type: IndexCursorTranslator.Type, |
| 10 | + perform: (inout IndexCursorTranslator) throws -> T) rethrows -> T { |
| 11 | + |
| 12 | + return try lock.withLock { |
| 13 | + return try perform(&translators[connectionIdentifier, default: type.init()]) |
| 14 | + } |
| 15 | +} |
| 16 | + |
| 17 | +private func withTranslator<T>(for connectionIdentifier: ConnectionIdentifier, |
| 18 | + using type: IndexCursorTranslator.Type, |
| 19 | + perform: (IndexCursorTranslator) throws -> T) rethrows -> T { |
| 20 | + |
| 21 | + let translator = lock.withLock { |
| 22 | + return translators[connectionIdentifier, default: type.init()] |
| 23 | + } |
| 24 | + return try perform(translator) |
| 25 | +} |
| 26 | + |
7 | 27 | private struct ConnectionIdentifier: Hashable { |
8 | 28 | let type: Int |
9 | 29 | let connection: AnyHashable |
@@ -32,11 +52,15 @@ struct IndexedConnectionWrapper<Connection: IndexedConnection>: ContextBasedConn |
32 | 52 | } |
33 | 53 |
|
34 | 54 | private func cursor(for index: Int) throws -> String { |
35 | | - return try translators[identifier, default: Connection.Translator()].cursor(for: index) |
| 55 | + return try withTranslator(for: identifier, using: Connection.Translator.self) { translator in |
| 56 | + return try translator.cursor(for: index) |
| 57 | + } |
36 | 58 | } |
37 | 59 |
|
38 | 60 | private func index(for cursor: String) throws -> Int { |
39 | | - return try translators[identifier, default: Connection.Translator()].index(for: cursor) |
| 61 | + return try withTranslator(for: identifier, using: Connection.Translator.self) { translator in |
| 62 | + return try translator.index(for: cursor) |
| 63 | + } |
40 | 64 | } |
41 | 65 |
|
42 | 66 | func context(first: Int?, after: String?, last: Int?, before: String?, eventLoop: EventLoopGroup) -> EventLoopFuture<Context> { |
|
0 commit comments