Home > OS >  Postgres jsonb data in Swift/Vapor
Postgres jsonb data in Swift/Vapor

Time:10-30

I have the following Vapor Fluent migration that creates a jsonb column

public func prepare(on database: Database) -> EventLoopFuture<Void> {
        return database.schema(MyModel.schema)
            .id()
            .field(.name, .custom("VARCHAR(255)"), .required)
            .field(.metadata, .custom("JSONB"), .required)
            .create()
    }

The model looks like this:

public final class MyModel: Model, Content {
    public static let schema = "blah"
    
    @ID(key: .id)
    public var id: UUID?
    
    @Field(key: .metadata)
    public var metadata: Data // This is obviously wrong.
}

Any idea how to make Vapor retrieve and set data from to Postgres jsonb columns ?

CodePudding user response:

I think what you're looking for is to use the .json type when declaring your field in your migration.

Here's an example I put together using the starter template code for reference:

struct Person: Codable {
    let name: String
}

final class Todo: Model, Content {
    static let schema = "todos"
    
    @ID(key: .id)
    var id: UUID?
    
    @Field(key: "metadata")
    var metadata: [String: String]
    
    @Field(key: "person")
    var person: Person

    init() { }

    init(id: UUID? = nil, metadata: [String: String], person: Person) {
        self.id = id
        self.metadata = metadata
        self.person = person
    }
}

I declared two Fields, metadata and person.

struct CreateTodo: Migration {
    func prepare(on database: Database) -> EventLoopFuture<Void> {
        return database.schema("todos")
            .id()
            .field("metadata", .json, .required)
            .field("person", .json, .required)
            .create()
    }


    func revert(on database: Database) -> EventLoopFuture<Void> {
        return database.schema("todos").delete()
    }
}
  • Related