Powerful model extraction from Vapor JSON requests
Switch branches/tags
Clone or download
Latest commit e0b9722 Nov 15, 2017
Permalink
Failed to load latest commit information.
.circleci removed travis badge Nov 15, 2017
Sources/Sanitize fixes Sep 28, 2017
Tests pre and post sanitize functions Sep 28, 2017
.gitignore fixes Sep 28, 2017
.jazzy.yaml fixes Sep 28, 2017
.swiftlint.yml initial code Sep 28, 2017
LICENSE Initial commit Sep 28, 2017
Package.swift initial code Sep 28, 2017
Package@swift-4.swift initial code Sep 28, 2017
README.md removed travis badge Nov 15, 2017
codecov.yml Initial commit Sep 28, 2017

README.md

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.