-
-
Notifications
You must be signed in to change notification settings - Fork 72
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
82c1ffa
commit 5807407
Showing
2 changed files
with
67 additions
and
9 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
import Foundation | ||
|
||
extension PostgresData { | ||
public init(json jsonData: Data) { | ||
let jsonData = [UInt8](jsonData) | ||
|
||
var buffer = ByteBufferAllocator() | ||
.buffer(capacity: jsonData.count) | ||
buffer.writeBytes(jsonData) | ||
self.init(type: .json, formatCode: .binary, value: buffer) | ||
} | ||
|
||
public init<T>(json value: T) throws where T: Encodable { | ||
let jsonData = try JSONEncoder().encode(value) | ||
self.init(json: jsonData) | ||
} | ||
|
||
public var json: Data? { | ||
guard var value = self.value else { | ||
return nil | ||
} | ||
guard case .json = self.type else { | ||
return nil | ||
} | ||
guard let data = value.readBytes(length: value.readableBytes) else { | ||
return nil | ||
} | ||
return Data(data) | ||
} | ||
|
||
public func json<T>(as type: T.Type) throws -> T? where T: Decodable { | ||
guard let data = self.json else { | ||
return nil | ||
} | ||
return try JSONDecoder().decode(T.self, from: data) | ||
} | ||
} | ||
|
||
public protocol PostgresJSONCodable: Codable, PostgresDataConvertible { } | ||
|
||
extension PostgresJSONCodable { | ||
public static var postgresDataType: PostgresDataType { | ||
return .json | ||
} | ||
|
||
public var postgresData: PostgresData? { | ||
return try? .init(json: self) | ||
} | ||
|
||
public init?(postgresData: PostgresData) { | ||
guard let value = try? postgresData.json(as: Self.self) else { | ||
return nil | ||
} | ||
self = value | ||
} | ||
} |
This file contains 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