forked from apple/swift-http-api-proposal
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExampleMiddlewareClient.swift
More file actions
70 lines (62 loc) · 2.27 KB
/
Copy pathExampleMiddlewareClient.swift
File metadata and controls
70 lines (62 loc) · 2.27 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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift HTTP API Proposal open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift HTTP API Proposal project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import HTTPAPIs
import Middleware
@available(anyAppleOS 26.0, *)
struct ExampleMiddlewareClient<Client: HTTPClient & ~Copyable, ClientMiddleware: Middleware<HTTPRequest, HTTPRequest>>: HTTPClient, ~Copyable {
typealias RequestOptions = Client.RequestOptions
typealias RequestWriter = Client.RequestWriter
typealias ResponseConcludingReader = Client.ResponseConcludingReader
var defaultRequestOptions: Client.RequestOptions {
self.client.defaultRequestOptions
}
private var client: Client
private let middleware: ClientMiddleware
init(
client: consuming Client,
@MiddlewareBuilder
middlewareBuilder: (RequestMiddleware<Client>) -> ClientMiddleware
) {
self.client = client
self.middleware = middlewareBuilder(RequestMiddleware<Client>())
}
mutating func perform<Return: ~Copyable>(
request: HTTPRequest,
body: consuming HTTPClientRequestBody<RequestWriter>?,
options: RequestOptions,
responseHandler: (HTTPResponse, consuming ResponseConcludingReader) async throws -> Return
) async throws -> Return {
var body = Optional(body)
return try await self.middleware.intercept(
input: request
) { request in
try await self.client.perform(
request: request,
body: body.take()!,
options: options,
responseHandler: responseHandler
)
}
}
}
@available(anyAppleOS 26.0, *)
struct RequestMiddleware<Client: HTTPClient & ~Copyable>: Middleware {
typealias Input = HTTPRequest
typealias NextInput = Input
func intercept<Return: ~Copyable>(
input: consuming Input,
next: (consuming NextInput) async throws -> Return
) async throws -> Return {
try await next(input)
}
}