Swiftpack.co - SparrowTek/MongoManager as Swift Package

Swiftpack.co is a collection of thousands of indexed Swift packages. Search packages.
See all packages published by SparrowTek.
SparrowTek/MongoManager 1.0.6
A simple Swift library to interact with MongDB Atlas via their Data API for Compute
⭐️ 1
🕓 1 year ago
macOS
.package(url: "https://github.com/SparrowTek/MongoManager.git", from: "1.0.6")

MongoManager

A simple Swift library to interact with MongDB Atlas via their Data API for Compute

This can all be easily hosted on Swift Cloud

Getting Started

Install MongoManager

.package(url: "https://github.com/SparrowTek/MongoManager", from: "1.0.6")

Add it as a target dependency

.executableTarget(
    name: "MyApp",
    dependencies: ["MongoManager"]
)

Sample implementation

Create a global let property

let mongoData = MongoData(baseURL: "https://data.mongodb-api.com/app/data-abcde/endpoint/data/v1",
                          database: "database",
                          dataSource: "dataSource",
                          apiKey: try? Dictionary(name: "mongoDB").get("dataAPI"))

Your baseURL will be provided to you by MongoDB Atlas. You will configure database and dataSource in Atlas. You will create an apiKey when you setup the MongoDB Atlas Data API. This sample code is extracting that key from a Dictionary hosted on Swift Cloud.

Now in your route,

struct MongoDBAtlasRoutes {
    static func regiser(_ router: Router) {
        router.post("/mongo/user", createUser)
    }
    
    static func createUser(req: IncomingRequest, res: OutgoingResponse) async throws {
        // create the Codable user object from the req body
        let user = try await req.body.decode(User.self)
        
        do {
            // use static insertOne method on MongoManager struct 
            _ = try await MongoManager.insertOne(mongoData: mongoData, collection: mongoCollection, document: user)
            // report back to API
            try await res.status(.created).send(user)
        } catch {
            // handle error
            try await res.status(.internalServerError).send(error.localizedDescription)
        }
    }
}

This POST route will create a User object from the request body and insert it into your MongoDB users collection.

GitHub

link
Stars: 1
Last commit: 1 year ago
Advertisement: IndiePitcher.com - Cold Email Software for Startups

Release Notes

v: 1.0.6
1 year ago

build with Swift 5.7 use new generic syntax

Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics