diff --git a/Sources/AutomergeRepo/Errors.swift b/Sources/AutomergeRepo/Errors.swift index e1e2afc..3faefe3 100644 --- a/Sources/AutomergeRepo/Errors.swift +++ b/Sources/AutomergeRepo/Errors.swift @@ -93,4 +93,16 @@ public enum Errors: Sendable { self.msg = msg } } + + /// The ID of the document already exists within the repository + public struct DuplicateID: Sendable, LocalizedError { + public var id: DocumentId + public var errorDescription: String? { + "The ID of the document \(id) already exists within the repository." + } + + public init(id: DocumentId) { + self.id = id + } + } } diff --git a/Sources/AutomergeRepo/Repo.swift b/Sources/AutomergeRepo/Repo.swift index b57db52..bf554c8 100644 --- a/Sources/AutomergeRepo/Repo.swift +++ b/Sources/AutomergeRepo/Repo.swift @@ -469,6 +469,9 @@ public final class Repo { /// - Returns: The Automerge document. /// - Parameter id: The Id of the Automerge document. public func create(id: DocumentId) async throws -> DocHandle { + if let existing = handles[id] { + throw Errors.DuplicateID(id: id) + } let handle = InternalDocHandle(id: id, isNew: true, initialValue: Document()) handles[handle.id] = handle docHandlePublisher.send(handle.snapshot()) @@ -480,6 +483,9 @@ public final class Repo { /// - Parameter doc: The Automerge document to use for the new, shared document /// - Returns: The Automerge document. public func create(doc: Document, id: DocumentId? = nil) async throws -> DocHandle { + if let providedId = id, let existing = handles[providedId] { + throw Errors.DuplicateID(id: providedId) + } let creationId = id ?? DocumentId() let handle = InternalDocHandle(id: creationId, isNew: true, initialValue: doc) handles[handle.id] = handle @@ -492,6 +498,9 @@ public final class Repo { /// - Parameter data: The data to load as an Automerge document for the new, shared document. /// - Returns: The Automerge document. public func create(data: Data, id: DocumentId? = nil) async throws -> DocHandle { + if let providedId = id, let existing = handles[providedId] { + throw Errors.DuplicateID(id: providedId) + } let creationId = id ?? DocumentId() let handle = try InternalDocHandle(id: creationId, isNew: true, initialValue: Document(data)) handles[handle.id] = handle