Home > OS >  Vapor-Swift DecodingError: Could not convert MySQL data to Date
Vapor-Swift DecodingError: Could not convert MySQL data to Date

Time:08-05

I'm trying to obtain some articles from my MySQL database using Vapor-Fluent but there is something wrong with my Date type (I have read a little bit of Date type in Vapor but I'm not sure about how to solve this issue).

This is my Vapor-Fluent model:

final class ArticleModel: Model, Content {
    
    static let schema = "tbl_article"
    
    @ID(custom: .id)
    var id: Int?
    
    @Field(key: "title")
    var title: String
    
    @Field(key: "description")
    var description: String
    
    @Field(key: "checked_out_time")
    var checkedOutTime: Date
    
    init() { }
    
    init(id: Int,
         title: String,
         description: String,
         checkedOutTime: Date) {
        self.id = id
        self.title = title
        self.description = description
        self.checkedOutTime = checkedOutTime
    }
}

This is my Controller:

func getContent(req: Request) async throws -> [ArticleModel] {
    try await ArticleModel(on: req.db)
        .sort(\.$checkedOutTime)
        .all()
}

This is the format of my Date type in my tbl_article table (it's DATETIME type in my database):

2022-08-02 21:51:29

When I try to obtain the articles by visiting my URL, it returns the following error:

{"error":true,"reason":"invalid field: checked_out_time type: Date error: typeMismatch(Foundation.Date, Swift.DecodingError.Context(codingPath: [], debugDescription: "Could not convert MySQL data to Date: 1970-01-01 00:00:00 0000", underlyingError: nil))"}

My question is:

What I have to change in order to make this work? I tried changing my model type to String but it didn't work, so maybe I have to change something related to the decoding process?

I'm new to Vapor (I'm creating my first real MySQL connection and I don't know how to solve this issue regarding the Date type).

Thanks!

CodePudding user response:

I am fairly sure the problem is caused by a NULL value in your checked_out_time data column.

The error definitely suggests there is a nil value being fetched from the database and because the data type is non-optional, it is erroring.

It should be simple to fix by defining your field as optional with Date?.

  • Related