Skip to content
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

New content format #122

Closed
wants to merge 24 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 118 additions & 0 deletions Sources/OpenAI/Public/Utilities/CodableUtilities.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
//
// CodableUtilities.swift
//
//
// Created by Federico Vitale on 09/11/23.
//

import Foundation


/// Allows having dynamic keys in codables.
struct DynamicKey: CodingKey {
var stringValue: String
var intValue: Int?

init(stringValue: String) {
self.stringValue = stringValue
}

init?(intValue: Int) {
self.intValue = intValue
self.stringValue = "\(intValue)"
}
}


/// Allows to encode/decode ``Chat`` or ``Codable`` (T)
/// ```swift
/// struct Person: Codable, Equatable {
/// let name: StringOrCodable<FullName>
///
/// struct FullName {
/// firstName: String
/// lastName: String
/// }
/// }
///
/// let person = Person(name: .string("John Doe"))
/// let fullNamePerson = Person(name: .object(.init(firstName: "John", lastName: "Doe")))
/// ```
public enum StringOrCodable<T: Codable>: Equatable, Codable where T: Equatable {
rawnly marked this conversation as resolved.
Show resolved Hide resolved
case string(String)
case object(T)

enum CodingKeys: CodingKey {
case string
case object
}

public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()

switch self {
case .string(let string):
try container.encode(string)
case .object(let object):
try container.encode(object)
}
}


public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()

if let string = try? container.decode(String.self) {
self = .string(string)
} else if let object = try? container.decode(T.self) {
self = .object(object)
} else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Invalid data encountered when decoding StringOrCodable<T>"
)
)
}
}
}

/// Same as ``StringOrCodable`` but accepts 2 codable generics instead of String as first generic argument
public enum AnyOf<T: Codable, U: Codable>: Equatable, Codable where T: Equatable, U: Equatable {
case objectA(T)
case objectB(U)

enum CodingKeys: CodingKey {
case objectA
case objectB
}

public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()

switch self {
case .objectB(let value):
try container.encode(value)
case .objectA(let value):
try container.encode(value)
}
}


public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()

if let valueT = try? container.decode(T.self) {
self = .objectA(valueT)
} else if let valueU = try? container.decode(U.self) {
self = .objectB(valueU)
} else {
throw DecodingError.dataCorrupted(
DecodingError.Context(
codingPath: decoder.codingPath,
debugDescription: "Invalid data encountered when decoding StringOrCodable<T>"
)
)
}
}
}
84 changes: 84 additions & 0 deletions Tests/OpenAITests/CodableUtilsTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
//
// File.swift
//
//
// Created by Federico Vitale on 09/11/23.
//

import XCTest
@testable import OpenAI

fileprivate class TestUtils {
static func decode<T: Decodable & Equatable>(
_ jsonString: String,
_ expectedValue: T
) throws {
let data = jsonString.data(using: .utf8)!
let decoded = try JSONDecoder().decode(T.self, from: data)

XCTAssertEqual(decoded, expectedValue)
}

static func encode<T: Encodable & Equatable>(
_ value: T,
_ expectedJson: String
) throws {
let source = try jsonDataAsNSDictionary(JSONEncoder().encode(value))
let expected = try jsonDataAsNSDictionary(expectedJson.data(using: .utf8)!)

XCTAssertEqual(source, expected)
}

static func jsonDataAsNSDictionary(_ data: Data) throws -> NSDictionary {
return NSDictionary(dictionary: try JSONSerialization.jsonObject(with: data, options: []) as! [String: Any])
}
}


class CodableUtilsTests: XCTestCase {
func testStringOrCodable_String() throws {
struct Person: Codable, Equatable {
let name: StringOrCodable<FullName>

struct FullName: Codable, Equatable {
let firstName: String
let lastName: String
}
}

let jsonString = """
{
"name": "test"
}
"""

let value = Person(name: .string("test"))

try TestUtils.encode(value, jsonString)
try TestUtils.decode(jsonString, value)
}

func testStringOrCodable_Object() throws {
struct Person: Codable, Equatable {
let name: StringOrCodable<FullName>

struct FullName: Codable, Equatable {
let firstName: String
let lastName: String
}
}

let jsonString = """
{
"name": { "firstName": "first", "lastName": "last" }
}
"""

let value = Person(name: .object(.init(firstName: "first", lastName: "last")))

try TestUtils.encode(value, jsonString)
try TestUtils.decode(jsonString, value)
}
}