János
János

Reputation: 35114

Execute code before codable decode type check is executed?

Is it possible to execute code after decode is called but before type check is carry out?

let o7 = try decoder.decode(Organization.self, from: o6)
o7.configure()
return o7.save(on: request.db).flatMap { page in
    return request.eventLoop.future("done")
}

It raise an error:

caught: typeMismatch(Swift.Dictionary<Swift.String, App.Event>, Swift.DecodingError.Context(codingPath: [ModelCodingKey(stringValue: "events", intValue: nil)], debugDescription: "Could not decode property", underlyingError: Optional(Swift.DecodingError.keyNotFound(ModelCodingKey(stringValue: "events", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key ModelCodingKey(stringValue: "events", intValue: nil) ("events").", underlyingError: nil)))))

o7 is not yet matching the type requirements, but o7.configure() does the needed steps, is it possible to "ask" check type after configure was called?


This is the JSON: {"name": "xxx"} And here is the type:

final class Organization:  Content {
    var name: String?
    var events: [String: Event]
}

as you see I need to initialize events to avoid typeMismatch error. I do it in configure method.

Upvotes: 1

Views: 229

Answers (1)

try adding CodingKeys, this will exclude "var events" from the json decodable.

final class Organization: Codable {
    var name: String?
    var events: [String: Event] = [:]
    
    private enum CodingKeys: String, CodingKey {
        case name
    }
}

Upvotes: 0

Related Questions