From 4b48a4e03fc8d7e011dffb4e0adbc8d4cf2f9c8f Mon Sep 17 00:00:00 2001 From: Valerio Mazzeo Date: Wed, 30 Jan 2019 15:42:46 +0000 Subject: [PATCH] mapIfDuplicatedKeyError --- Sources/FluentMongo/Model+Index.swift | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/Sources/FluentMongo/Model+Index.swift b/Sources/FluentMongo/Model+Index.swift index 6726fd1..3c270d9 100644 --- a/Sources/FluentMongo/Model+Index.swift +++ b/Sources/FluentMongo/Model+Index.swift @@ -18,3 +18,20 @@ extension Model where Database == MongoDatabase { return IndexBuilder(on: conn.databaseConnection(to: Self.defaultDatabase)) } } + +extension Future where T: Model, T.Database == MongoDatabase { + + @discardableResult + public func mapIfDuplicatedKeyError(_ callback: @escaping (MongoConnection.Error) throws -> T) -> Future { + return self.catchMap { error in + guard + let mongoConnectionError = error as? MongoConnection.Error, + case .duplicatedKey = mongoConnectionError + else { + throw error + } + + return try callback(mongoConnectionError) + } + } +}