Home

Awesome

Swift Version Vapor Version Build Status codebeat badge codecov GitHub license

Sanitize

Powerful model extraction from JSON requests.

Installation

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")

Usage

Model

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

Request Body

{
  "id": 1,
  "name": "John Appleseed",
  "email": "example@domain.com"
}

Routes

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
}

Pre and Post validations

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."
            )
        }
    }
}

Credits

This package is developed and maintained by Gustavo Perdomo.

This package is heavily inspired by Sanitized

License

Sanitize is released under the MIT License.