Created
May 4, 2018 19:51
-
-
Save theseanything/92bd2275f596d37d5bb4d91dac2d7ae2 to your computer and use it in GitHub Desktop.
Custom decoder for Vapor Model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import FluentSQLite | |
import Vapor | |
/// A single entry of a Issue list. | |
final class Issue: SQLiteModel { | |
/// The unique identifier for this `Issue`. | |
var id: Int? | |
var title: String | |
var description: String | |
var upVotes: Int = 0 | |
var downVotes: Int = 0 | |
var propertyId: Property.ID | |
/// Creates a new `Issue`. | |
init(id: Int? = nil, title: String, description: String, propertyId: Property.ID) { | |
self.id = id | |
self.title = title | |
self.description = description | |
self.propertyId = propertyId | |
} | |
// Custom decoding so upVotes and downVotes properties are not required. | |
// Now json request throw "Value required for key 'id'." | |
init(from decoder: Decoder) throws { | |
let values = try decoder.container(keyedBy: CodingKeys.self) | |
// Removing line below causes `FluentError.idProperty: Unable to reflect ID property for Issue.` | |
self.id = try values.decode(Int.self, forKey: .id) | |
self.title = try values.decode(String.self, forKey: .title) | |
self.description = try values.decode(String.self, forKey: .description) | |
self.propertyId = try values.decode(Int.self, forKey: .propertyId) | |
} | |
} | |
/// Allows `Issue` to be used as a dynamic migration. | |
extension Issue: Migration { } | |
/// Allows `Issue` to be encoded to and decoded from HTTP messages. | |
extension Issue: Content { } | |
/// Allows `Issue` to be used as a dynamic parameter in route definitions. | |
extension Issue: Parameter { } | |
extension Issue { | |
var property: Parent<Issue, Property> { | |
return parent(\.propertyId) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment