Instance Method
insert(dbName:body:eventLoopGroup:)
Inserts a raw document body into a specified database on the CouchDB server.
func insert(dbName: String, body: HTTPClientRequest.Body, eventLoopGroup: (any EventLoopGroup)? = nil) async throws -> CouchUpdateResponse
Parameters
- dbName
The name of the database into which the new document will be inserted.
- body
The HTTPClientRequest.Body containing the JSON-encoded content of the new document.
- eventLoopGroup
An optional EventLoopGroup for executing network requests. If not provided, the function uses a shared instance of HTTPClient.
Return Value
A CouchUpdateResponse object containing the result of the insertion operation.
Discussion
This method sends a POST request with a caller-provided request body and decodes CouchDB’s update response. It allows the use of a custom EventLoopGroup for managing network operations.
Throws
A CouchDBClientError if authentication fails, the response body is missing, or CouchDB returns an error payload that maps to .insertError(error:). Non-CouchDB decoding failures are propagated as the underlying decoding error.
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)
}
}
Create and Insert a Document:
let testDoc = ExpectedDoc(name: "My name")
let encodedData = try JSONEncoder().encode(testDoc)
let body: HTTPClientRequest.Body = .bytes(ByteBuffer(data: encodedData))
let response = try await couchDBClient.insert(
dbName: "myDatabase",
body: body
)
print(response) // Response includes operation status and revision token
Note
Ensure that the CouchDB server is running and accessible before calling this function. Handle thrown errors appropriately, especially for authentication issues or unexpected server responses.