Instance Method
update(dbName:doc:dateEncodingStrategy:eventLoopGroup:)
Updates a document conforming to CouchDBRepresentable in a specified database on the CouchDB server.
func update<T>(dbName: String, doc: T, dateEncodingStrategy: JSONEncoder.DateEncodingStrategy = .secondsSince1970, eventLoopGroup: (any EventLoopGroup)? = nil) async throws -> T where T : CouchDBRepresentable
Parameters
- dbName
The name of the database containing the document to be updated.
- doc
A reference to the document of type T that will be updated. The document must have valid _id and _rev properties.
- dateEncodingStrategy
The date encoding strategy to use when encoding dates in the document. Defaults to .secondsSince1970.
- eventLoopGroup
An optional EventLoopGroup for executing network operations. If not provided, the function uses a shared instance of HTTPClient.
Return Value
The updated document of type T, with its _rev property reflecting the new revision token.
Discussion
This asynchronous generic function updates a document in the specified database. The document must conform to the CouchDBRepresentable protocol, which requires _id and _rev properties. The function supports using a custom EventLoopGroup for network operations and allows a configurable date encoding strategy.
Throws
A CouchDBClientError if the operation fails, including: .revMissing if the document’s _rev is missing or empty, .unknownResponse if the server’s response is not successful or unexpected.
Function Workflow:
Verifies that the document has a valid _rev property.
Encodes the document using a JSONEncoder configured with the specified date encoding strategy.
Constructs the request body using the encoded document data.
Sends a PUT request to update the document in the specified database.
Processes the server’s response and throws an error if the operation fails.
Returns the document updated with the new _rev value from CouchDB.
Example Usage:
Define Your Document Model:
struct ExpectedDoc: CouchDBRepresentable {
var name: String
var _id: String = UUID().uuidString
var _rev: String?
func updateRevision(_ newRevision: String) -> Self {
return ExpectedDoc(name: name, _id: _id, _rev: newRevision)
}
}
Retrieve and Update a Document:
var doc: ExpectedDoc = try await couchDBClient.get(
fromDB: "myDatabase",
uri: "documentID"
)
// Modify the document
doc.name = "Updated name"
// Update the document in the database
doc = try await couchDBClient.update(
dbName: "myDatabase",
doc: doc
)
print(doc) // Document now includes the updated name and a new `_rev` value
Note
Ensure that the CouchDB server is running and accessible before calling this function. Handle thrown errors appropriately, especially for document updates and server responses.