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
8.6 KBRaw ↗
jinja
import Foundation
#if canImport(FoundationNetworking)
import FoundationNetworking
#endif

{%- 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 -%}

{%- macro symbol_for(link) -%}
{%- for dependency in file.dependencies -%}
{%- if dependency.target.id == link.id and dependency.symbol -%}{{ dependency.symbol }}{%- endif -%}
{%- endfor -%}
{%- endmacro -%}

{%- macro base_type(value) -%}
{%- if value is none or value.is.unknown or value.is.dynamic or value.is.generic or value.is.composite or value.is.union or value.is.tuple or value.is.literal -%}DryvJSONValue
{%- elif value.is.schema -%}{{ symbol_for(value.schema) or 'DryvJSONValue' }}
{%- elif value.is.enum -%}{{ symbol_for(value.property.enum) or 'DryvJSONValue' }}
{%- elif value.is.boolean -%}Bool
{%- elif value.is.integer -%}Int64
{%- elif value.is.decimal or value.is.money -%}Decimal
{%- elif value.is.number -%}Double
{%- elif value.is.uuid -%}UUID
{%- elif value.is.record -%}[String: DryvJSONValue]
{%- elif value.is.string or value.is.temporal -%}String
{%- else -%}DryvJSONValue
{%- endif -%}
{%- endmacro -%}

{%- macro field_type(field) -%}
{{- base_type(field.value) -}}{%- if field.optional -%}?{%- endif -%}
{%- endmacro -%}

{%- macro bound(binding) -%}
{%- if binding.port.field is none -%}input{%- else -%}input.{{ swift_ident(binding.port.field.camel) }}{%- endif -%}
{%- endmacro -%}

{%- macro binding_optional(operation, binding) -%}
{%- if binding.port.field is not none -%}
{%- for field in operation.input.fields -%}
{%- if field.name.raw == binding.port.field.raw and (field.optional) -%}x{%- endif -%}
{%- endfor -%}
{%- endif -%}
{%- endmacro -%}

{%- macro append_item(target, name, expression, optional, array) -%}
{%- if optional %}
    if let value = {{ expression }} {
{%- if array %}
        for item in value {
            {{ target }}.append(DryvClient.queryItem(name: {{ name | tojson }}, value: item))
        }
{%- else %}
        {{ target }}.append(DryvClient.queryItem(name: {{ name | tojson }}, value: value))
{%- endif %}
    }
{%- else %}
{%- if array %}
    for item in {{ expression }} {
        {{ target }}.append(DryvClient.queryItem(name: {{ name | tojson }}, value: item))
    }
{%- else %}
    {{ target }}.append(DryvClient.queryItem(name: {{ name | tojson }}, value: {{ expression }}))
{%- endif %}
{%- endif -%}
{%- endmacro -%}

{%- set http = operation.facets.http -%}
{%- if operation.input and operation.input.kind != 'schema' %}
public struct {{ operation.name.pascal }}Input: Codable, Sendable {
{%- for field in operation.input.fields %}
    public var {{ swift_ident(field.name.camel) }}: {{ field_type(field) }}
{%- endfor %}

    public init(
{%- for field in operation.input.fields %}
        {{ swift_ident(field.name.camel) }}: {{ field_type(field) }}{% if field.optional %} = nil{% endif %}{% if not loop.last %},{% endif %}
{%- endfor %}
    ) {
{%- for field in operation.input.fields %}
        self.{{ swift_ident(field.name.camel) }} = {{ swift_ident(field.name.camel) }}
{%- endfor %}
    }
}

{%- endif %}
public func {{ swift_ident(file.symbol) }}(
    client: DryvClient{% if operation.input %},
    input: {% if operation.input.kind == 'schema' %}{{ base_type(operation.input.value) }}{% else %}{{ operation.name.pascal }}Input{% endif %}{% endif %}
) async throws{% if operation.output %} -> {{ base_type(operation.output.value) }}{% endif %} {
{%- if http.input_groups.multipart %}
    throw DryvAPIError(status: 501, message: "Multipart bindings require an explicit Swift semantic mapping.")
{%- else %}
    var path = {{ http.path.local | tojson }}
{%- for binding in http.input_groups.path %}
{%- if binding_optional(operation, binding) %}
    guard let pathValue{{ loop.index }} = {{ bound(binding) }} else {
        throw DryvAPIError(status: 400, message: "Missing path value {{ binding.name or binding.port.name.raw }}")
    }
    path = path.replacingOccurrences(
        of: {{ ('{' ~ (binding.name or binding.port.name.raw) ~ '}') | tojson }},
        with: DryvClient.pathSegment(pathValue{{ loop.index }})
    )
{%- else %}
    path = path.replacingOccurrences(
        of: {{ ('{' ~ (binding.name or binding.port.name.raw) ~ '}') | tojson }},
        with: DryvClient.pathSegment({{ bound(binding) }})
    )
{%- endif %}
{%- endfor %}

    var queryItems: [URLQueryItem] = []
{%- for binding in http.input_groups.query %}
{{ append_item('queryItems', binding.name or binding.port.name.raw, bound(binding), binding_optional(operation, binding), false) }}
{%- endfor %}
{%- for binding in http.input_groups.query_object %}
{%- if binding.port.value.is.schema %}
{%- if binding_optional(operation, binding) %}
    if let queryObject = {{ bound(binding) }} {
{%- for field in binding.port.value.schema.fields %}
{{ append_item('queryItems', field.name.raw, 'queryObject.' ~ swift_ident(field.name.camel), field.optional or field.nullable, field.array is not none) | indent(4, true) }}
{%- endfor %}
    }
{%- else %}
    let queryObject = {{ bound(binding) }}
{%- for field in binding.port.value.schema.fields %}
{{ append_item('queryItems', field.name.raw, 'queryObject.' ~ swift_ident(field.name.camel), field.optional or field.nullable, field.array is not none) }}
{%- endfor %}
{%- endif %}
{%- endif %}
{%- endfor %}

    var request = try client.request(
        method: {{ http.method | tojson }},
        path: path,
        queryItems: queryItems
    )
{%- for binding in http.input_groups.header %}
{%- if binding_optional(operation, binding) %}
    if let value = {{ bound(binding) }} {
        request.setValue(DryvClient.wireString(value), forHTTPHeaderField: {{ (binding.name or binding.port.name.raw) | tojson }})
    }
{%- else %}
    request.setValue(DryvClient.wireString({{ bound(binding) }}), forHTTPHeaderField: {{ (binding.name or binding.port.name.raw) | tojson }})
{%- endif %}
{%- endfor %}
{%- if http.input_groups.cookie %}
    var cookieParts: [String] = []
{%- for binding in http.input_groups.cookie %}
{%- if binding_optional(operation, binding) %}
    if let value = {{ bound(binding) }} {
        cookieParts.append({{ (binding.name or binding.port.name.raw) | tojson }} + "=" + DryvClient.pathSegment(value))
    }
{%- else %}
    cookieParts.append({{ (binding.name or binding.port.name.raw) | tojson }} + "=" + DryvClient.pathSegment({{ bound(binding) }}))
{%- endif %}
{%- endfor %}
    if !cookieParts.isEmpty {
        request.setValue(cookieParts.joined(separator: "; "), forHTTPHeaderField: "Cookie")
    }
{%- endif %}
{%- for binding in http.input_groups.body %}
{%- if binding_optional(operation, binding) %}
    if let bodyValue = {{ bound(binding) }} {
        request.httpBody = try client.encode(bodyValue)
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    }
{%- else %}
    request.httpBody = try client.encode({{ bound(binding) }})
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
{%- endif %}
{%- endfor %}
{%- if http.input_groups.form %}
    var formItems: [URLQueryItem] = []
{%- for binding in http.input_groups.form %}
{%- if binding.port.field is none and binding.port.value.is.schema %}
{%- if binding_optional(operation, binding) %}
    if let formObject = {{ bound(binding) }} {
{%- for field in binding.port.value.schema.fields %}
{{ append_item('formItems', field.name.raw, 'formObject.' ~ swift_ident(field.name.camel), field.optional or field.nullable, field.array is not none) | indent(4, true) }}
{%- endfor %}
    }
{%- else %}
    let formObject = {{ bound(binding) }}
{%- for field in binding.port.value.schema.fields %}
{{ append_item('formItems', field.name.raw, 'formObject.' ~ swift_ident(field.name.camel), field.optional or field.nullable, field.array is not none) }}
{%- endfor %}
{%- endif %}
{%- else %}
{{ append_item('formItems', binding.name or binding.port.name.raw, bound(binding), binding_optional(operation, binding), false) }}
{%- endif %}
{%- endfor %}
    request.httpBody = DryvClient.formData(formItems)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
{%- endif %}

{%- if operation.output %}
    return try await client.send(request, as: {{ base_type(operation.output.value) }}.self)
{%- else %}
    try await client.sendVoid(request)
{%- endif %}
{%- endif %}
}