Repository navigation
Expand file tree
/
Copy pathFunctionBody.swift
More file actions
75 lines (68 loc) · 2.54 KB
/
Copy pathFunctionBody.swift
File metadata and controls
75 lines (68 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//
// FunctionBody.swift
// Functions
//
// Created by Guilherme Souza on 05/10/26.
//
public import Foundation
public import Helpers
/// What an invocation sends.
///
/// Each factory fixes the `Content-Type`; a per-call
/// ``FunctionInvokeOptions/headers`` entry for `Content-Type` overrides it.
///
/// ```swift
/// try await functions.invoke("order", body: .json(order))
/// try await functions.invoke("echo", body: .text("hello"))
/// try await functions.invoke("thumbnail", body: .data(jpeg, contentType: "image/jpeg"))
/// try await functions.invoke("transcribe", body: .stream(try HTTPBody(fileURL: url), contentType: "audio/m4a"))
/// ```
public struct FunctionBody: Sendable {
/// The `Content-Type` sent with the body.
public let contentType: String
/// The bytes sent.
public let httpBody: HTTPBody
/// JSON-encodes `value` now, in the caller's isolation.
///
/// - Parameters:
/// - value: The value to encode.
/// - encoder: The encoder to use. `nil` uses `JSONEncoder.supabase()`, which writes `Date` as
/// ISO 8601.
/// - Returns: A body with the `application/json` content type.
/// - Throws: ``FunctionsError`` with kind ``FunctionsError/Kind-swift.struct/invalidRequest``
/// wrapping the `EncodingError`. Nothing is sent.
public static func json(
_ value: some Encodable,
encoder: JSONEncoder? = nil
) throws -> FunctionBody {
do {
return FunctionBody(
contentType: "application/json",
httpBody: HTTPBody(try (encoder ?? JSONValue.encoder).encode(value)))
} catch {
throw FunctionsError(
kind: .invalidRequest,
message: "Failed to encode the Edge Function request body as JSON.",
underlyingError: error
)
}
}
/// Sends `string` as `text/plain; charset=utf-8`.
public static func text(_ string: String) -> FunctionBody {
FunctionBody(contentType: "text/plain; charset=utf-8", httpBody: HTTPBody(Data(string.utf8)))
}
/// Sends raw bytes. Defaults to `application/octet-stream`.
public static func data(
_ data: Data,
contentType: String = "application/octet-stream"
) -> FunctionBody {
FunctionBody(contentType: contentType, httpBody: HTTPBody(data))
}
/// Sends a streamed body, such as `HTTPBody(fileURL:)` for a large upload.
///
/// A body whose `iterationBehavior` is `.single` can be read once, so it cannot be retried
/// or replayed after a redirect.
public static func stream(_ body: HTTPBody, contentType: String) -> FunctionBody {
FunctionBody(contentType: contentType, httpBody: body)
}
}