Skip to content

Add custom JSON encoder / decoder support #285

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 27, 2020
Merged

Conversation

tanner0101
Copy link
Member

@tanner0101 tanner0101 commented Jul 27, 2020

Adds support for configuring which JSON coders MySQL uses when conforming to SQLKit's APIs (#285, fixes #252).

// Some existing conformer to `MySQLDatabase`
let mysql: MySQLDatabase = ...

// Setup custom JSON coders that use unix timestamps
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .secondsSince1970
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970

// Use `sql()` method to create a `SQLDatabase` passing in
// MySQL coders that use the custom JSON coders.
let sql = mysql.sql(
    encoder: MySQLDataEncoder(json: encoder), 
    decoder: MySQLDataDecoder(json: decoder)
)

// Sample model with nested JSON field.
struct Foo: Codable, Equatable {
    struct Bar: Codable, Equatable {
        var baz: Date
    }
    var bar: Bar
}

// New instance to create.
let foo = Foo(
    bar: Bar(
        baz: Date(timeIntervalSince1970: 1337)
    )
)
// INSERT INTO `foo` (`bar`) VALUES (?) ["{\"baz\":1337}"]
try db.insert(into: "foo").model(foo).run().wait()

@tanner0101 tanner0101 added the enhancement New feature or request label Jul 27, 2020
@tanner0101 tanner0101 mentioned this pull request Jul 27, 2020
@tanner0101 tanner0101 added the semver-minor Contains new APIs label Jul 27, 2020
@tanner0101 tanner0101 merged commit a154cf3 into master Jul 27, 2020
@tanner0101 tanner0101 deleted the tn-custom-json branch July 27, 2020 21:40
@tanner0101
Copy link
Member Author

These changes are now available in 4.0.0-rc.1.8

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request semver-minor Contains new APIs
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Custom JSONDecoder
1 participant