dryvPacks

@dryv/swift-client-sdkv0.1.0

Dependency-free Swift URLSession SDK with Codable wire types.

Swift Client SDKClientsUnitPublished 7 days ago2 downloads

dryv pack add @dryv/swift-client-sdk
2.1 KBRaw ↗
jinja
import Foundation

{%- macro swift_ident(name) -%}
{%- if name in ['associatedtype','class','deinit','enum','extension','fileprivate','func','import','init','inout','internal','let','open','operator','private','protocol','public','rethrows','static','struct','subscript','typealias','var','break','case','continue','default','defer','do','else','fallthrough','for','guard','if','in','repeat','return','throw','switch','where','while','as','Any','catch','false','is','nil','super','self','Self','throws','true','try','_'] -%}\`{{ name }}\`{%- else -%}{{ name }}{%- endif -%}
{%- endmacro -%}

public struct {{ file.symbol }}: Codable, Equatable, Sendable, CustomStringConvertible {
    public let value: DryvJSONValue

    private init(value: DryvJSONValue) {
        self.value = value
    }

{%- for item in property.enum.values %}
    public static let {{ swift_ident(item.name.camel) }} = Self(
        value: {% if item.value is boolean %}.bool({% if item.value %}true{% else %}false{% endif %}){% elif item.value is integer %}.int({{ item.value }}){% elif item.value is float %}.double({{ item.value }}){% elif item.value is string %}.string(String(decoding: [{{ item.value.encode('utf-8') | join(', ') }}], as: UTF8.self)){% endif %}
    )
{%- endfor %}

    public static let allValues: [Self] = [
{%- for item in property.enum.values %}
        .{{ swift_ident(item.name.camel) }}{% if not loop.last %},{% endif %}
{%- endfor %}
    ]

    public init(from decoder: Decoder) throws {
        let decoded = try DryvJSONValue(from: decoder)
        guard Self.allValues.contains(where: { $0.value == decoded }) else {
            throw DecodingError.dataCorrupted(
                .init(codingPath: decoder.codingPath, debugDescription: "Invalid {{ property.enum.name.local }} value")
            )
        }
        self.value = decoded
    }

    public func encode(to encoder: Encoder) throws {
        try value.encode(to: encoder)
    }

    public static func parseWire(_ raw: String) -> Self? {
        allValues.first(where: { $0.description == raw })
    }

    public var description: String {
        value.description
    }
}