Meow plugin for API generation
MeowVapor bridges Meow to Vapor and provides awesome helpers for creating a Meow based Vapor app/API.
.package(url: "https://github.com/OpenKitten/MeowVapor.git", from: "2.0.0")
Add MeowVapor as a dependency via SPM and run swift package update
.
Add Meow to your Vapor services. Be sure to change the MongoDB URI to point to your server.
let meow = try MeowProvider(uri: "mongodb://localhost/MyDatabase")
try services.register(meow)
router.get { request -> Future<[User]> in
let context = try request.make(Meow.Context.self)
return context.find(User.self).getAllResults()
}
When creating a Model you need to conform your class
to Model
.
The only requirement is that you add a property to your model with a key of _id
and is not a computed property.
final class User: Model {
var _id = ObjectId()
...
}
You can use any type for the _id
key as long as it’s a standard BSON Primitive
type including:
Binary
/ Data
The following is completely legitimate:
// Stores the username in _id
final class User: Model {
var _id: String
var username: String {
return _id
}
...
By default the model name will be used for the collection name. You can customize this with a static let collectionName: String
final class User: Model {
// Changes the collection name from `User` to `users`
static let collectionName = "users"
var _id = ObjectId()
...
Queries reside within the Context
.
final class Article: Model {
var _id = ObjectId()
let creator: Reference<User>
var title: String
var text: String
...
The above demonstrates how a simple reference can be created to another model. In this case a User model. And below demonstrates resolving the reference.
let resolvedUser = article.creator.resolve(in: context)
The result in this case is an EventLoopFuture<User>
, but if you wish to resolve the reference’s target to nil
if it doesn’t exist you can simply do article.creator.resolveIfPresent(in: context)
.
You’re also able to delete the target of the reference using reference.deleteTarget(in: context)
. This implies that resolving the normal way (not with ifPresent
) will result in a failure.
If a feature is unsupported by Meow, for example when it can’t be type-safe, you can always fall back to MongoKitten.
let database: MongoKitten.Database = context.manager.database
Join our slack here and become a part of the welcoming community.