Instance Method
insert(dbName:doc:dateEncodingStrategy:eventLoopGroup:)
Inserts a new document conforming to CouchDBRepresentable into a specified database on the CouchDB server.
func insert<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 where the new document will be inserted.
- doc
The document of type T to be inserted. The type T must conform to CouchDBRepresentable.
- dateEncodingStrategy
The strategy used for encoding dates within the document. Defaults to .secondsSince1970.
- eventLoopGroup
An optional EventLoopGroup for managing network operations. If not provided, a shared instance of HTTPClient is used.
Return Value
The newly inserted document of type T, updated with its new _rev property.
Discussion
This asynchronous generic function inserts a new document into the specified database. The document must conform to the CouchDBRepresentable protocol, which requires _id and _rev properties. It supports using a custom EventLoopGroup for network operations and allows a configurable date encoding strategy.
Throws
A CouchDBClientError if the operation fails, including: .unknownResponse if the server’s response is unexpected or unsuccessful.
Function Workflow:
Encodes the document using a JSONEncoder configured with the specified date encoding strategy.
Prepares a POST request with the encoded document as the request body.
Sends the request to the CouchDB server and processes the response.
Returns the document updated with the new _rev from CouchDB.
Throws an error if the server’s response is unexpected or unsuccessful.
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)
}
}
Insert a New Document:
var testDoc = ExpectedDoc(name: "My name")
testDoc = try await couchDBClient.insert(
dbName: "myDatabase",
doc: testDoc
)
print(testDoc) // Document now contains its assigned `_id` and `_rev`.
Note
Ensure that the CouchDB server is operational and accessible before using this function. Handle thrown errors appropriately, especially for unexpected server responses.