Powerful model extraction from JSON requests.
Add this project to the Package.swift
dependencies of your Vapor project:
.Package(url: "https://github.com/gperdomor/sanitize.git", majorVersion: 1)
or for Swift 4:
.package(url: "https://github.com/gperdomor/sanitize.git", from: "1.0.0")
Before you're able to extract your model from a request it needs to conform to
the protocol Sanitizable
adding a [String]
named allowedKeys
with a list
of keys you wish to allow:
import Sanitize
class User: Sanitizable { // or struct
var id: Node?
var name: String
var email: String
// Valid properties taken from the request json
static var allowedKeys: [String] = ["name", "email"]
//...
}
Now that you have a conforming model, you can safely extract it from a Request
{
"id": 1,
"name": "John Appleseed",
"email": "[email protected]"
}
drop.post("model") { req in
var user: User = try req.extractModel()
print(user.id == nil) // prints `true` because was removed (`id` is not a allowed key)
try user.save()
return user
}
You can also configure some preSanitize
and postSanitize
validations,
this validations will be executed before and after model initialization.
extension User {
static func preSanitize(data: JSON) throws {
guard data["name"]?.string != nil else {
throw Abort(
.badRequest,
metadata: nil,
reason: "No name provided."
)
}
guard data["email"]?.string != nil else {
throw Abort(
.badRequest,
metadata: nil,
reason: "No email provided."
)
}
}
func postSanitize() throws {
guard email.characters.count > 8 else {
throw Abort(
.badRequest,
metadata: nil,
reason: "Email must be longer than 8 characters."
)
}
}
}
This package is developed and maintained by Gustavo Perdomo.
This package is heavily inspired by Sanitized
Sanitize is released under the MIT License.