DEV Community

Cover image for MongoDB and Swift Vapor Integration
rachelle palmer
rachelle palmer

Posted on

MongoDB and Swift Vapor Integration

Over the last few years, Vapor has emerged as the leading framework for developing web applications with Swift, and MongoDB has a number of users who are committed to this framework. However, integrating the use of MongoDB, Swift driver, and Vapor requires a fair amount of boilerplate and additional steps. This is irritating.

To combat this, we recently created a small library gluing together the Swift driver and Vapor framework, as well as working with Vapor to add support to Vapor command line tooling for easily generating new projects for MongoDB.

With the new MongoDBVapor library, there are a number of benefits.

  • Users only need to call a single method to initialize a MongoDB client and persist it via app.mongoDB.configure()
  • Simplified app shutdown cleanup for users via a new method app.mongoDB.cleanup()
  • Extensions to Vapor's Request type to provide easy access to MongoDB clients/databases/collections that will return EventLoopFutures on the same EventLoop the Request is on, simplifying thread safety concerns and improving performance
  • Support for using ExtendedJSONEncoder/ExtendedJSONDecoder for encoding/decoding JSON requests

To use the new library requires:
Swift 5.2+
macOS 10.15+, or Linux
Vapor 4.x

Check it out on github.
Documentation for the Swift Driver here.

Top comments (0)