Add Create validation

This commit is contained in:
Simon Edelmann 2020-02-28 16:49:04 +01:00
parent ee3b857cca
commit 8df9124d7c
3 changed files with 29 additions and 2 deletions

View File

@ -16,7 +16,9 @@ struct CrudController<T: Model & Content & Publicable>: CrudControllerProtocol w
extension CrudController where T: Createable {
func create(req: Request) throws -> EventLoopFuture<T.Public> {
// Validation
if let validatable = T.Create.self as? Validatable.Type {
try validatable.validate(req)
}
let data = try req.content.decode(T.Create.self)
return create(from: data, on: req.db).public()
}

View File

@ -31,7 +31,7 @@ final class CreateTests: ApplicationXCTestCase {
}
}
func testCreateWithInvalidData() throws {
func testCreateWithoutData() throws {
struct Empty: Content {}
try routes()
@ -47,9 +47,28 @@ final class CreateTests: ApplicationXCTestCase {
XCTAssertNotEqual(res.status, .ok)
}
}
func testCreateWithInvalidData() throws {
struct Empty: Content {}
try routes()
try app.test(.GET, "/todos/1") { res in
XCTAssertEqual(res.status, .notFound)
XCTAssertNotEqual(res.status, .ok)
}.test(.POST, "/todos", json: Todo(title: "Sh")) { res in
XCTAssertEqual(res.status, .badRequest)
XCTAssertContains(res.body.string, "title is less than minimum of 3 character(s)")
XCTAssertNotEqual(res.status, .ok)
}.test(.GET, "/todos/1") { res in
XCTAssertEqual(res.status, .notFound)
XCTAssertNotEqual(res.status, .ok)
}
}
static var allTests = [
("testCreateWithValidData", testCreateWithValidData),
("testCreateWithoutData", testCreateWithoutData),
("testCreateWithInvalidData", testCreateWithInvalidData),
]
}

View File

@ -43,6 +43,12 @@ extension Todo: Createable {
}
}
extension Todo.Create: Validatable {
static func validations(_ validations: inout Validations) {
validations.add("title", as: String.self, is: .count(3...))
}
}
extension Todo {
struct migration: Migration {
var name = "TodoMigration"