Instance Method
update(dbName:uri:body:eventLoopGroup:)
Updates a document in a specified database on the CouchDB server.
func update(dbName: String, uri: String, body: HTTPClientRequest.Body, eventLoopGroup: (any EventLoopGroup)? = nil) async throws -> CouchUpdateResponse
Parameters
- dbName
The name of the database containing the document to be updated.
- uri
The URI path of the specific document within the database.
- body
The HTTPClientRequest.Body containing the updated content of the document.
- eventLoopGroup
An optional EventLoopGroup for executing network operations. If not provided, the function uses a shared instance of HTTPClient.
Return Value
A CouchUpdateResponse object containing the result of the update operation.
Discussion
This asynchronous function sends a PUT request to the CouchDB server to update a document at a given URI within a specified database. It allows the use of a custom EventLoopGroup for network operations.
Throws
A CouchDBClientError if the operation fails, including: .unauthorized if authentication fails, .noData if the response body cannot be read, .conflictError(error:) when CouchDB returns a conflict, .updateError(error:) when CouchDB reports a not-found or update error, and .unknownResponse if CouchDB returns an unexpected error payload.
Function Workflow:
Constructs a PUT request for the target document and attaches the provided body.
Executes the request using an authenticated client and buffers the response body.
Throws .conflictError(error:) when CouchDB responds with 409 Conflict.
Throws .updateError(error:) when CouchDB responds with 404 Not Found.
Decodes and returns CouchUpdateResponse for successful responses.
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)
}
}
Update a Document:
// Fetch the document by ID
var response = try await couchDBClient.get(
fromDB: "myDatabase",
uri: "documentID"
)
// Parse the document
let bytes = response.body!.readBytes(length: response.body!.readableBytes)!
var doc = try JSONDecoder().decode(
ExpectedDoc.self,
from: Data(bytes)
)
// Modify the document
doc.name = "Updated name"
// Encode the updated document into JSON
let data = try JSONEncoder().encode(doc)
let body: HTTPClientRequest.Body = .bytes(ByteBuffer(data: data))
// Send the update request
let updateResponse = try await couchDBClient.update(
dbName: "myDatabase",
uri: doc._id,
body: body
)
print(updateResponse)
Note
Ensure that the CouchDB server is running and accessible before calling this function. Handle thrown errors appropriately, especially for authentication or data-related issues.