Skip to content
This repository has been archived by the owner on Aug 13, 2024. It is now read-only.
/ MongoManager Public archive

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

License

Notifications You must be signed in to change notification settings

SparrowTek/MongoManager

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

21 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

This repo is deprecated. It still works but is not maintained. You are better off using MongoDB from the Swift Cloud team.

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.

About

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

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages