mirror of
https://github.com/samsonjs/Osiris.git
synced 2026-03-26 09:05:48 +00:00
Compare commits
No commits in common. "main" and "2.0.1" have entirely different histories.
20 changed files with 349 additions and 1918 deletions
33
CHANGELOG.md
Normal file
33
CHANGELOG.md
Normal file
|
|
@ -0,0 +1,33 @@
|
||||||
|
# Changelog
|
||||||
|
|
||||||
|
## [2.0.1] - 2025-06-15
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- GET and DELETE requests with empty parameters no longer include unnecessary question mark in URL
|
||||||
|
|
||||||
|
[2.0.1]: https://github.com/samsonjs/Osiris/compare/2.0.0...main
|
||||||
|
|
||||||
|
## [2.0.0] - 2025-06-15
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **GET/DELETE query parameter support** - Parameters are now automatically encoded as query strings for GET and DELETE requests
|
||||||
|
- **Enhanced error types** with localized descriptions and failure reasons
|
||||||
|
- **Header convenience method** `addHeader(name:value:)` on `HTTPRequest`
|
||||||
|
- **Comprehensive test coverage**
|
||||||
|
|
||||||
|
### Enhanced
|
||||||
|
- **Public API** - All types and methods now have proper public access modifiers
|
||||||
|
- **Error handling** - More specific error cases with `LocalizedError` conformance
|
||||||
|
- **Debugging support** - All types now conform to `CustomStringConvertible` with idiomatic descriptions for better OSLog output
|
||||||
|
|
||||||
|
[2.0.0]: https://github.com/samsonjs/Osiris/compare/1.0.0...2.0.0
|
||||||
|
|
||||||
|
## [1.0.0] - 2017-07-28
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- Initial release with multipart form encoding
|
||||||
|
- HTTPRequest and HTTPResponse abstractions
|
||||||
|
- RequestBuilder for URLRequest conversion
|
||||||
|
- FormEncoder for URL-encoded forms
|
||||||
|
|
||||||
|
[1.0.0]: https://github.com/samsonjs/Osiris/releases/tag/1.0.0
|
||||||
67
Changelog.md
67
Changelog.md
|
|
@ -1,67 +0,0 @@
|
||||||
# Changelog
|
|
||||||
|
|
||||||
## [2.1.0] - Unreleased
|
|
||||||
|
|
||||||
### Added
|
|
||||||
- Codable body support in HTTPRequest factory methods: `post(body:encoder:)`, `put(body:encoder:)`, `patch(body:encoder:)`
|
|
||||||
- URLSession extensions for automatic JSON decoding with custom decoder support
|
|
||||||
- HTTPError type with status code and response body for better error debugging
|
|
||||||
- Multipart convenience methods: `postMultipart()`, `putMultipart()`, `patchMultipart()`
|
|
||||||
- Explicit body encoding methods with clear naming: `postJSON()`, `postForm()`, etc.
|
|
||||||
- Query parameter support for GET and DELETE requests - parameters are now properly encoded as query strings
|
|
||||||
|
|
||||||
### Removed
|
|
||||||
- `CodableRequest<Response>` - Replaced with direct HTTPRequest Codable support for simplicity
|
|
||||||
|
|
||||||
### Changed
|
|
||||||
- Minimum deployment targets changed to ones that actually build: iOS 16.0 and macOS 13.0
|
|
||||||
- `HTTPRequest` now uses `HTTPRequestBody` enum internally for better type safety
|
|
||||||
- GET and DELETE requests now properly encode parameters as query strings instead of ignoring them
|
|
||||||
- Added validation to prevent GET/DELETE requests from having request bodies
|
|
||||||
|
|
||||||
### Deprecated
|
|
||||||
- `HTTPRequest.post(url:contentType:parameters:)` - Use `postJSON()` or `postForm()` instead
|
|
||||||
- `HTTPRequest.put(url:contentType:parameters:)` - Use `putJSON()` or `putForm()` instead
|
|
||||||
- `HTTPRequest.patch(url:contentType:parameters:)` - Use `patchJSON()` or `patchForm()` instead
|
|
||||||
- Direct access to `HTTPRequest.parameters` property
|
|
||||||
- Direct access to `HTTPRequest.parts` property
|
|
||||||
|
|
||||||
### Migration Guide
|
|
||||||
- Swap `HTTPRequest.post(url, contentType: .json, parameters: params)` for `HTTPRequest.postJSON(url, body: params)`
|
|
||||||
- Swap `HTTPRequest.post(url, contentType: .formEncoded, parameters: params)` for `HTTPRequest.postForm(url, parameters: params)`
|
|
||||||
- Swap `HTTPRequest.put(url, contentType: .json, parameters: params)` for `HTTPRequest.putJSON(url, body: params)`
|
|
||||||
- Swap `HTTPRequest.patch(url, contentType: .json, parameters: params)` for `HTTPRequest.patchJSON(url, body: params)`
|
|
||||||
- For multipart requests, use `HTTPRequest.postMultipart(url, parts: parts)` instead of setting the `parts` property directly
|
|
||||||
|
|
||||||
[2.1.0]: https://github.com/samsonjs/Osiris/compare/2.0.1...main
|
|
||||||
|
|
||||||
## [2.0.1] - 2025-06-15
|
|
||||||
|
|
||||||
### Fixed
|
|
||||||
- GET and DELETE requests with empty parameters no longer include unnecessary question mark in URL
|
|
||||||
|
|
||||||
[2.0.1]: https://github.com/samsonjs/Osiris/compare/2.0.0...2.0.1
|
|
||||||
|
|
||||||
## [2.0.0] - 2025-06-15
|
|
||||||
|
|
||||||
### Added
|
|
||||||
- **GET/DELETE query parameter support** - Parameters are now automatically encoded as query strings for GET and DELETE requests
|
|
||||||
- **Enhanced error types** with localized descriptions and failure reasons
|
|
||||||
- **Comprehensive test coverage**
|
|
||||||
|
|
||||||
### Enhanced
|
|
||||||
- **Public API** - All types and methods now have proper public access modifiers
|
|
||||||
- **Error handling** - More specific error cases with `LocalizedError` conformance
|
|
||||||
- **Debugging support** - All types now conform to `CustomStringConvertible` with idiomatic descriptions for better OSLog output
|
|
||||||
|
|
||||||
[2.0.0]: https://github.com/samsonjs/Osiris/compare/1.0.0...2.0.0
|
|
||||||
|
|
||||||
## [1.0.0] - 2017-07-28
|
|
||||||
|
|
||||||
### Added
|
|
||||||
- Initial release with multipart form encoding
|
|
||||||
- HTTPRequest and HTTPResponse abstractions
|
|
||||||
- RequestBuilder for URLRequest conversion
|
|
||||||
- FormEncoder for URL-encoded forms
|
|
||||||
|
|
||||||
[1.0.0]: https://github.com/samsonjs/Osiris/releases/tag/1.0.0
|
|
||||||
|
|
@ -6,8 +6,8 @@ import PackageDescription
|
||||||
let package = Package(
|
let package = Package(
|
||||||
name: "Osiris",
|
name: "Osiris",
|
||||||
platforms: [
|
platforms: [
|
||||||
.iOS(.v16),
|
.iOS(.v14),
|
||||||
.macOS(.v13),
|
.macOS(.v11),
|
||||||
],
|
],
|
||||||
products: [
|
products: [
|
||||||
.library(
|
.library(
|
||||||
|
|
|
||||||
300
Readme.md
300
Readme.md
|
|
@ -6,11 +6,9 @@
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
Osiris is a Swift library that makes HTTP requests less ambiguous. It gives you multipart form encoding, cleaner abstractions for requests and responses, and stops you from wrangling optionals and errors manually. Instead you get types and an API that feels more Swifty.
|
Osiris is a Swift library that provides a multipart form encoder and HTTP utilities designed to make working with HTTP requests simpler and more flexible. The library focuses on practical utility over complexity, offering tools that handle common HTTP tasks like multipart form encoding, request building, and response handling.
|
||||||
|
|
||||||
The main components are clean abstractions for HTTP requests and responses, and a `MultipartFormEncoder` that can encode forms either to memory or to files. The multipart encoder can stream data to files for large request bodies. Everything conforms to `CustomStringConvertible` with helpful descriptions so debugging with OSLog doesn't involve `String(describing:)` or other annoyances.
|
The main components include a robust `MultipartFormEncoder` that can encode forms either to memory or directly to files for streaming, and clean abstractions for HTTP requests and responses. All types conform to `CustomStringConvertible` with idiomatic descriptions, making debugging with OSLog significantly easier.
|
||||||
|
|
||||||
For the most part Osiris strives you give you tools to make `URLSession` easier to use. However there are convenience methods to directly perform `HTTPRequest`s without building them yourself, and also to decode JSON response bodies. They're optional but you'll probably want to use them.
|
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
|
|
@ -18,7 +16,7 @@ You can install Osiris using Swift Package Manager (SPM) or copy the files direc
|
||||||
|
|
||||||
### Supported Platforms
|
### Supported Platforms
|
||||||
|
|
||||||
This package supports iOS 16.0+ and macOS 13.0+. The package is built with Swift 6.0+ but doesn't require projects importing Osiris to use Swift 6 language mode.
|
This package supports iOS 14.0+ and macOS 11.0+. The package is built with Swift 6.0+ but doesn't require projects importing Osiris to use Swift 6 language mode.
|
||||||
|
|
||||||
### Xcode
|
### Xcode
|
||||||
|
|
||||||
|
|
@ -29,121 +27,84 @@ Add the package to your project's Package Dependencies by entering the URL `http
|
||||||
Add this to your Package.swift dependencies:
|
Add this to your Package.swift dependencies:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
.package(url: "https://github.com/samsonjs/Osiris.git", .upToNextMajor(from: "2.1.0"))
|
.package(url: "https://github.com/samsonjs/Osiris.git", .upToNextMajor(from: "2.0.0"))
|
||||||
```
|
```
|
||||||
|
|
||||||
and add `"Osiris"` to your target dependencies.
|
and add `"Osiris"` to your target dependencies.
|
||||||
|
|
||||||
|
### Direct Integration
|
||||||
|
|
||||||
|
Alternatively, copy the files you want to use into your project and customize them to suit your needs.
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
|
|
||||||
### HTTPRequest with Codable Support
|
### Multipart Form Encoding
|
||||||
|
|
||||||
Automatic JSON encoding/decoding with URLSession extensions:
|
Create an encoder and then add parts to it as needed:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
import Osiris
|
import Osiris
|
||||||
|
|
||||||
let url = URL(string: "https://trails.example.net/riders")!
|
let avatarData = UIImage(systemName: "person.circle")?.jpegData(compressionQuality: 1.0)
|
||||||
|
let encoder = MultipartFormEncoder()
|
||||||
// GET request with automatic JSON decoding
|
let body = try encoder.encodeData(parts: [
|
||||||
let riders: [RiderProfile] = try await URLSession.shared.perform(.get(url))
|
.text("ziggy@example.net", name: "email"),
|
||||||
|
.text("StarmanWaiting", name: "password"),
|
||||||
// POST with Codable body and automatic response decoding
|
.data(avatarData ?? Data(), name: "avatar", type: "image/jpeg", filename: "avatar.jpg"),
|
||||||
struct CreateRiderRequest: Codable {
|
])
|
||||||
let name: String
|
|
||||||
let email: String
|
|
||||||
let bike: String
|
|
||||||
}
|
|
||||||
|
|
||||||
let danny = CreateRiderRequest(name: "Danny MacAskill", email: "danny@trails.example.net", bike: "Santa Cruz 5010")
|
|
||||||
let created: RiderProfile = try await URLSession.shared.perform(.post(url, body: danny))
|
|
||||||
|
|
||||||
// Custom JSON encoding/decoding (e.g., snake_case)
|
|
||||||
let encoder = JSONEncoder()
|
|
||||||
encoder.keyEncodingStrategy = .convertToSnakeCase
|
|
||||||
let decoder = JSONDecoder()
|
|
||||||
decoder.keyDecodingStrategy = .convertFromSnakeCase
|
|
||||||
|
|
||||||
let customRequest = try HTTPRequest.post(url, body: danny, encoder: encoder)
|
|
||||||
let result: RiderProfile = try await URLSession.shared.perform(customRequest, decoder: decoder)
|
|
||||||
|
|
||||||
// For requests expecting no content (204, etc.)
|
|
||||||
try await URLSession.shared.perform(.delete(url.appendingPathComponent("123")))
|
|
||||||
```
|
```
|
||||||
|
|
||||||
### Basic HTTPRequest
|
The form can be encoded as `Data` in memory, or to a file. There's a hard limit of 50 MB on encoding to memory but in practice you probably never want to go that high purely in memory. If you're adding any kind of image or video file then it's probably better to stream to a file.
|
||||||
|
|
||||||
For simple requests:
|
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
import Osiris
|
let body = try encoder.encodeFile(parts: [
|
||||||
|
.text("ziggy@example.net", name: "email"),
|
||||||
|
.text("StarmanWaiting", name: "password"),
|
||||||
|
.data(avatarData ?? Data(), name: "avatar", type: "image/jpeg", filename: "avatar.jpg"),
|
||||||
|
])
|
||||||
|
|
||||||
let url = URL(string: "https://example.net/kittens")!
|
var request = URLRequest(url: URL(string: "https://example.net/accounts")!)
|
||||||
|
request.httpMethod = "POST"
|
||||||
|
request.httpBodyStream = InputStream(url: body.url)
|
||||||
|
request.addValue(body.contentType, forHTTPHeaderField: "Content-Type")
|
||||||
|
request.addValue("\(body.contentLength)", forHTTPHeaderField: "Content-Length")
|
||||||
|
```
|
||||||
|
|
||||||
// Basic GET request
|
### HTTPRequest
|
||||||
let request = HTTPRequest.get(url)
|
|
||||||
|
Basic usage:
|
||||||
|
|
||||||
|
```swift
|
||||||
|
let url = URL(string: "https://example.net")!
|
||||||
|
|
||||||
// GET request with query parameters
|
// GET request with query parameters
|
||||||
let getRequest = HTTPRequest.get(url, parameters: ["page": 1, "limit": 10])
|
let getRequest = HTTPRequest.get(url, parameters: ["page": "1", "limit": "10"])
|
||||||
|
|
||||||
// DELETE request with query parameters
|
// DELETE request with query parameters
|
||||||
let deleteRequest = HTTPRequest.delete(url, parameters: ["confirm": "true"])
|
let deleteRequest = HTTPRequest.delete(url, parameters: ["confirm": "true"])
|
||||||
|
|
||||||
|
// Or use the general initializer
|
||||||
|
let request = HTTPRequest(method: .get, url: url)
|
||||||
```
|
```
|
||||||
|
|
||||||
More complicated POST requests with bodies and headers:
|
More advanced usage with parameters and headers:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
// POST with JSON body and a custom header
|
let url = URL(string: "https://example.net")!
|
||||||
let url = URL(string: "https://example.net/band")!
|
let params = ["email": "freddie@example.net", "password": "BohemianRhapsody"]
|
||||||
let params = ["email": "fatmike@example.net", "password": "LinoleumSupportsMyHead"]
|
|
||||||
var jsonRequest = HTTPRequest.postJSON(url, body: params)
|
|
||||||
jsonRequest.headers["x-the-answer"] = "42"
|
|
||||||
|
|
||||||
// POST with form-encoded body
|
// POST with JSON parameters (goes in request body)
|
||||||
let formRequest = HTTPRequest.postForm(url, parameters: params)
|
let request = HTTPRequest.post(url, contentType: .json, parameters: params)
|
||||||
|
request.addHeader(name: "x-custom", value: "42")
|
||||||
// POST with multipart body
|
request.addMultipartJPEG(name: "avatar", image: UIImage(), quality: 1, filename: "avatar.jpg")
|
||||||
let multipartRequest = HTTPRequest.postMultipart(url, parts: [.text("all day", name: "album")])
|
|
||||||
```
|
```
|
||||||
|
|
||||||
You can build a `URLRequest` from an `HTTPRequest` using `RequestBuilder`:
|
You can build a `URLRequest` from an `HTTPRequest` instance using `RequestBuilder`:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let urlRequest = try RequestBuilder.build(request: request)
|
let urlRequest = try RequestBuilder.build(request: request)
|
||||||
```
|
```
|
||||||
|
|
||||||
### More Codable Examples
|
|
||||||
|
|
||||||
HTTPRequest has built-in support for Codable request bodies:
|
|
||||||
|
|
||||||
```swift
|
|
||||||
struct Artist: Codable {
|
|
||||||
let name: String
|
|
||||||
let email: String
|
|
||||||
let genre: String
|
|
||||||
}
|
|
||||||
|
|
||||||
let url = URL(string: "https://beats.example.net/artists")!
|
|
||||||
let artist = Artist(name: "Trent Reznor", email: "trent@example.net", genre: "Industrial")
|
|
||||||
|
|
||||||
// POST with Codable body
|
|
||||||
let postRequest = try HTTPRequest.post(url, body: artist)
|
|
||||||
let created: Artist = try await URLSession.shared.perform(postRequest)
|
|
||||||
|
|
||||||
// PUT with Codable body
|
|
||||||
let putRequest = try HTTPRequest.put(url, body: artist)
|
|
||||||
let updated: Artist = try await URLSession.shared.perform(putRequest)
|
|
||||||
|
|
||||||
// PATCH with Codable body
|
|
||||||
let patchRequest = try HTTPRequest.patch(url, body: artist)
|
|
||||||
let patched: Artist = try await URLSession.shared.perform(patchRequest)
|
|
||||||
|
|
||||||
// Custom encoder for different JSON formatting
|
|
||||||
let encoder = JSONEncoder()
|
|
||||||
encoder.keyEncodingStrategy = .convertToSnakeCase
|
|
||||||
let customRequest = try HTTPRequest.post(url, body: artist, encoder: encoder)
|
|
||||||
```
|
|
||||||
|
|
||||||
### HTTPResponse
|
### HTTPResponse
|
||||||
|
|
||||||
This enum makes sense of the 3 parameters of `URLSession`'s completion block. Its initializer takes in the optional `URLResponse`, `Data`, and `Error` values and determines if the request succeeded or failed, taking the HTTP status code into account. 200-level statuses are successes and anything else is a failure.
|
This enum makes sense of the 3 parameters of `URLSession`'s completion block. Its initializer takes in the optional `URLResponse`, `Data`, and `Error` values and determines if the request succeeded or failed, taking the HTTP status code into account. 200-level statuses are successes and anything else is a failure.
|
||||||
|
|
@ -151,14 +112,14 @@ This enum makes sense of the 3 parameters of `URLSession`'s completion block. It
|
||||||
```swift
|
```swift
|
||||||
let task = URLSession.shared.dataTask(with: urlRequest) { data, response, error in
|
let task = URLSession.shared.dataTask(with: urlRequest) { data, response, error in
|
||||||
let httpResponse = HTTPResponse(response: response, data: data, error: error)
|
let httpResponse = HTTPResponse(response: response, data: data, error: error)
|
||||||
|
|
||||||
switch httpResponse {
|
switch httpResponse {
|
||||||
case let .success(httpURLResponse, data):
|
case .success(let httpURLResponse, let data):
|
||||||
print("Success: \(httpURLResponse.statusCode)")
|
print("Success: \(httpURLResponse.statusCode)")
|
||||||
if let data = data {
|
if let data = data {
|
||||||
print("Response: \(String(data: data, encoding: .utf8) ?? "")")
|
print("Response: \(String(data: data, encoding: .utf8) ?? "")")
|
||||||
}
|
}
|
||||||
case let .failure(error, httpURLResponse, data):
|
case .failure(let error, let httpURLResponse, let data):
|
||||||
print("Failed: \(error)")
|
print("Failed: \(error)")
|
||||||
if let httpURLResponse = httpURLResponse {
|
if let httpURLResponse = httpURLResponse {
|
||||||
print("Status: \(httpURLResponse.statusCode)")
|
print("Status: \(httpURLResponse.statusCode)")
|
||||||
|
|
@ -181,156 +142,49 @@ The response provides convenient properties:
|
||||||
URL-encoded form data encoder adapted from [Alamofire][]:
|
URL-encoded form data encoder adapted from [Alamofire][]:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
let body = FormEncoder.encode(["email": "trent@example.net", "password": "CloserToGod"])
|
let body = FormEncoder.encode(["email": "bowie@example.net", "password": "MajorTom"])
|
||||||
// => "email=trent%40example.net&password=CloserToGod"
|
// => "email=bowie%40example.net&password=MajorTom"
|
||||||
```
|
```
|
||||||
|
|
||||||
[Alamofire]: https://github.com/Alamofire/Alamofire
|
[Alamofire]: https://github.com/Alamofire/Alamofire
|
||||||
|
|
||||||
### Multipart Form Encoding
|
|
||||||
|
|
||||||
Create an encoder and then add parts to it as needed:
|
|
||||||
|
|
||||||
```swift
|
|
||||||
let avatarData = UIImage(systemName: "person.circle")?.jpegData(compressionQuality: 1.0)
|
|
||||||
let encoder = MultipartFormEncoder()
|
|
||||||
let body = try encoder.encodeData(parts: [
|
|
||||||
.text("chali@example.net", name: "email"),
|
|
||||||
.text("QualityControl", name: "password"),
|
|
||||||
.data(avatarData ?? Data(), name: "avatar", type: "image/jpeg", filename: "avatar.jpg"),
|
|
||||||
])
|
|
||||||
```
|
|
||||||
|
|
||||||
You can encode forms as `Data` in memory, or encode to a file which can then be streamed from disk. There's a 50 MB limit on in-memory encoding, but honestly you probably don't want to go anywhere near that. If you're dealing with images or video files, just encode to a file from the start.
|
|
||||||
|
|
||||||
```swift
|
|
||||||
let body = try encoder.encodeFile(parts: [
|
|
||||||
.text("chali@example.net", name: "email"),
|
|
||||||
.text("QualityControl", name: "password"),
|
|
||||||
.data(avatarData ?? Data(), name: "avatar", type: "image/jpeg", filename: "avatar.jpg"),
|
|
||||||
])
|
|
||||||
|
|
||||||
var request = URLRequest(url: URL(string: "https://example.net/accounts")!)
|
|
||||||
request.httpMethod = "POST"
|
|
||||||
request.httpBodyStream = InputStream(url: body.url)
|
|
||||||
request.addValue(body.contentType, forHTTPHeaderField: "Content-Type")
|
|
||||||
request.addValue("\(body.contentLength)", forHTTPHeaderField: "Content-Length")
|
|
||||||
|
|
||||||
// Clean up the temporary file when done
|
|
||||||
defer { _ = body.cleanup() }
|
|
||||||
```
|
|
||||||
|
|
||||||
### Complete Example
|
### Complete Example
|
||||||
|
|
||||||
Here's a realistic example with error handling:
|
Here's how everything comes together:
|
||||||
|
|
||||||
```swift
|
```swift
|
||||||
import Osiris
|
import Osiris
|
||||||
|
|
||||||
struct ArtistProfile: Codable {
|
// Create an HTTP request
|
||||||
let name: String
|
let url = URL(string: "https://httpbin.org/post")!
|
||||||
let email: String
|
let request = HTTPRequest(method: .post, url: url)
|
||||||
let genre: String
|
|
||||||
}
|
|
||||||
|
|
||||||
struct UpdateProfileRequest: Codable {
|
// Add multipart form data
|
||||||
let name: String
|
let encoder = MultipartFormEncoder()
|
||||||
let email: String
|
let formData = try encoder.encodeData(parts: [
|
||||||
let genre: String
|
.text("John Doe", name: "name"),
|
||||||
}
|
.text("john@example.net", name: "email"),
|
||||||
|
])
|
||||||
|
|
||||||
func updateProfile(name: String, email: String, genre: String) async throws -> ArtistProfile {
|
// Build URLRequest
|
||||||
let url = URL(string: "https://beats.example.net/profile")!
|
var urlRequest = try RequestBuilder.build(request: request)
|
||||||
let updateRequest = UpdateProfileRequest(name: name, email: email, genre: genre)
|
urlRequest.httpBody = formData.data
|
||||||
|
urlRequest.addValue(formData.contentType, forHTTPHeaderField: "Content-Type")
|
||||||
|
|
||||||
|
// Make the request
|
||||||
|
let task = URLSession.shared.dataTask(with: urlRequest) { data, response, error in
|
||||||
|
let httpResponse = HTTPResponse(response: response, data: data, error: error)
|
||||||
|
|
||||||
// Use Codable body instead of dictionary
|
switch httpResponse {
|
||||||
let request = try HTTPRequest.put(url, body: updateRequest)
|
case .success(let httpURLResponse, let data):
|
||||||
|
print("Upload successful: \(httpURLResponse.statusCode)")
|
||||||
// URLSession extension handles status checking and JSON decoding
|
case .failure(let error, _, _):
|
||||||
return try await URLSession.shared.perform(request)
|
print("Upload failed: \(error)")
|
||||||
}
|
|
||||||
|
|
||||||
// For varied data structures, dictionaries are still available as an escape hatch:
|
|
||||||
func updateProfileWithDictionary(fields: [String: String]) async throws -> ArtistProfile {
|
|
||||||
let url = URL(string: "https://beats.example.net/profile")!
|
|
||||||
let request = HTTPRequest.putJSON(url, body: fields)
|
|
||||||
return try await URLSession.shared.perform(request)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Usage with error handling
|
|
||||||
do {
|
|
||||||
let profile = try await updateProfile(name: "Trent Reznor", email: "trent@example.net", genre: "Industrial")
|
|
||||||
print("Profile updated: \(profile)")
|
|
||||||
} catch let httpError as HTTPError {
|
|
||||||
switch httpError {
|
|
||||||
case let .failure(statusCode, data, _):
|
|
||||||
print("HTTP \(statusCode) error: \(String(data: data, encoding: .utf8) ?? "No body")")
|
|
||||||
case .invalidResponse:
|
|
||||||
print("Invalid response from server")
|
|
||||||
}
|
}
|
||||||
} catch is DecodingError {
|
|
||||||
print("Failed to decode response JSON")
|
|
||||||
} catch {
|
|
||||||
print("Network error: \(error)")
|
|
||||||
}
|
}
|
||||||
|
task.resume()
|
||||||
```
|
```
|
||||||
|
|
||||||
## Migration Guide
|
|
||||||
|
|
||||||
### Migrating from 2.0 to 2.1
|
|
||||||
|
|
||||||
Version 2.1.0 cleans up the API while keeping everything backward compatible. The old methods are deprecated and you'll get warnings, but they still work. We'll remove them in 3.0.
|
|
||||||
|
|
||||||
#### HTTPRequest Changes
|
|
||||||
|
|
||||||
**Old API (deprecated):**
|
|
||||||
```swift
|
|
||||||
// Parameters with content type
|
|
||||||
let request = HTTPRequest.post(url, contentType: .json, parameters: ["key": "value"])
|
|
||||||
let request = HTTPRequest.put(url, contentType: .formEncoded, parameters: params)
|
|
||||||
|
|
||||||
// Direct property access
|
|
||||||
var request = HTTPRequest.post(url)
|
|
||||||
request.parameters = ["key": "value"]
|
|
||||||
request.parts = [.text("value", name: "field")]
|
|
||||||
```
|
|
||||||
|
|
||||||
**New API:**
|
|
||||||
```swift
|
|
||||||
// Explicit methods for different encodings
|
|
||||||
let request = HTTPRequest.postJSON(url, body: ["key": "value"])
|
|
||||||
let request = HTTPRequest.putForm(url, parameters: params)
|
|
||||||
|
|
||||||
// Multipart convenience methods
|
|
||||||
let request = HTTPRequest.postMultipart(url, parts: [.text("value", name: "field")])
|
|
||||||
|
|
||||||
// Codable support
|
|
||||||
struct Artist: Codable {
|
|
||||||
let name: String
|
|
||||||
let genre: String
|
|
||||||
}
|
|
||||||
let request = try HTTPRequest.post(url, body: Artist(name: "Trent Reznor", genre: "Industrial"))
|
|
||||||
```
|
|
||||||
|
|
||||||
#### What's Different
|
|
||||||
|
|
||||||
1. **GET/DELETE Query Parameters**: You can now pass parameters to GET and DELETE requests and they'll be automatically encoded as query strings like they should have been all along, instead of having to build the URL yourself.
|
|
||||||
|
|
||||||
2. **Codable Support**: HTTPRequest now has direct Codable support and URLSession extensions for automatic JSON handling:
|
|
||||||
```swift
|
|
||||||
let request = try HTTPRequest.post(url, body: newArtist)
|
|
||||||
let response: ArtistResponse = try await URLSession.shared.perform(request)
|
|
||||||
```
|
|
||||||
|
|
||||||
3. **Clearer Method Names**: Methods like `postJSON()` and `postForm()` tell you exactly what encoding you're getting.
|
|
||||||
|
|
||||||
#### Migration Steps
|
|
||||||
|
|
||||||
1. Update to version 2.1
|
|
||||||
2. Fix the deprecation warnings by swapping old method calls for new ones
|
|
||||||
3. You can now pass query parameters to GET/DELETE requests instead of adding them to the URL yourself
|
|
||||||
4. Take advantage of the built-in Codable support for type-safe request bodies
|
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
|
|
||||||
Originally created by [@samsonjs][] for [1 Second Everyday][1SE]. `FormEncoder.swift` was adapted from [Alamofire][].
|
Originally created by [@samsonjs][] for [1 Second Everyday][1SE]. `FormEncoder.swift` was adapted from [Alamofire][].
|
||||||
|
|
|
||||||
|
|
@ -9,7 +9,7 @@ import Foundation
|
||||||
import OSLog
|
import OSLog
|
||||||
import UIKit
|
import UIKit
|
||||||
|
|
||||||
private let log = Logger(subsystem: "net.samhuri.Osiris", category: "Service")
|
private let log = Logger(subsystem: "co.1se.Osiris", category: "Service")
|
||||||
|
|
||||||
enum ServiceError: Error {
|
enum ServiceError: Error {
|
||||||
case malformedRequest(HTTPRequest)
|
case malformedRequest(HTTPRequest)
|
||||||
|
|
@ -32,6 +32,7 @@ enum ServiceEnvironment: String {
|
||||||
return selected
|
return selected
|
||||||
}
|
}
|
||||||
set {
|
set {
|
||||||
|
assert(Thread.isMainThread)
|
||||||
guard newValue != selected else {
|
guard newValue != selected else {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
@ -86,32 +87,32 @@ final class Service {
|
||||||
|
|
||||||
// MARK: - Requests
|
// MARK: - Requests
|
||||||
|
|
||||||
fileprivate func delete(_ path: String, parameters: [String: any Sendable]? = nil) -> HTTPRequest {
|
fileprivate func deleteRequest(path: String, parameters: [String: any Sendable]? = nil) -> HTTPRequest {
|
||||||
newRequest(method: .delete, path: path, parameters: parameters)
|
return newRequest(method: .delete, path: path, parameters: parameters)
|
||||||
}
|
}
|
||||||
|
|
||||||
fileprivate func get(_ path: String) -> HTTPRequest {
|
fileprivate func getRequest(path: String) -> HTTPRequest {
|
||||||
newRequest(method: .get, path: path)
|
return newRequest(method: .get, path: path)
|
||||||
}
|
}
|
||||||
|
|
||||||
fileprivate func patch(_ path: String, parameters: [String: any Sendable]) -> HTTPRequest {
|
fileprivate func patchRequest(path: String, parameters: [String: any Sendable]) -> HTTPRequest {
|
||||||
newRequest(method: .patch, path: path, contentType: .formEncoded, parameters: parameters)
|
return newRequest(method: .patch, path: path, contentType: .formEncoded, parameters: parameters)
|
||||||
}
|
}
|
||||||
|
|
||||||
fileprivate func postJSON(_ path: String, parameters: [String: any Sendable]) -> HTTPRequest {
|
fileprivate func postJSONRequest(path: String, parameters: [String: any Sendable]) -> HTTPRequest {
|
||||||
newRequest(method: .post, path: path, contentType: .json, parameters: parameters)
|
return newRequest(method: .post, path: path, contentType: .json, parameters: parameters)
|
||||||
}
|
}
|
||||||
|
|
||||||
fileprivate func post(_ path: String, parameters: [String: any Sendable]) -> HTTPRequest {
|
fileprivate func postRequest(path: String, parameters: [String: any Sendable]) -> HTTPRequest {
|
||||||
newRequest(method: .post, path: path, contentType: .formEncoded, parameters: parameters)
|
return newRequest(method: .post, path: path, contentType: .formEncoded, parameters: parameters)
|
||||||
}
|
}
|
||||||
|
|
||||||
fileprivate func putJSON(_ path: String, parameters: [String: any Sendable]) -> HTTPRequest {
|
fileprivate func putJSONRequest(path: String, parameters: [String: any Sendable]) -> HTTPRequest {
|
||||||
newRequest(method: .put, path: path, contentType: .json, parameters: parameters)
|
return newRequest(method: .put, path: path, contentType: .json, parameters: parameters)
|
||||||
}
|
}
|
||||||
|
|
||||||
fileprivate func put(_ path: String, parameters: [String: any Sendable]) -> HTTPRequest {
|
fileprivate func putRequest(path: String, parameters: [String: any Sendable]) -> HTTPRequest {
|
||||||
newRequest(method: .put, path: path, contentType: .formEncoded, parameters: parameters)
|
return newRequest(method: .put, path: path, contentType: .formEncoded, parameters: parameters)
|
||||||
}
|
}
|
||||||
|
|
||||||
fileprivate func newRequest(method: HTTPMethod, path: String, contentType: HTTPContentType = .none, parameters: [String: any Sendable]? = nil) -> HTTPRequest {
|
fileprivate func newRequest(method: HTTPMethod, path: String, contentType: HTTPContentType = .none, parameters: [String: any Sendable]? = nil) -> HTTPRequest {
|
||||||
|
|
@ -122,7 +123,7 @@ final class Service {
|
||||||
fileprivate func newRequest(method: HTTPMethod, url: URL, contentType: HTTPContentType = .none, parameters: [String: any Sendable]? = nil) -> HTTPRequest {
|
fileprivate func newRequest(method: HTTPMethod, url: URL, contentType: HTTPContentType = .none, parameters: [String: any Sendable]? = nil) -> HTTPRequest {
|
||||||
let request = HTTPRequest(method: method, url: url, contentType: contentType, parameters: parameters)
|
let request = HTTPRequest(method: method, url: url, contentType: contentType, parameters: parameters)
|
||||||
|
|
||||||
// Authorize requests to your service automatically.
|
// Authorize requests to our service automatically.
|
||||||
if let token = self.token, url.hasBaseURL(environment.baseURL) {
|
if let token = self.token, url.hasBaseURL(environment.baseURL) {
|
||||||
authorizeRequest(request, token: token)
|
authorizeRequest(request, token: token)
|
||||||
}
|
}
|
||||||
|
|
@ -132,11 +133,28 @@ final class Service {
|
||||||
fileprivate func authorizeRequest(_ request: HTTPRequest, token: String) {
|
fileprivate func authorizeRequest(_ request: HTTPRequest, token: String) {
|
||||||
let encodedCredentials = "api:\(token)".base64
|
let encodedCredentials = "api:\(token)".base64
|
||||||
let basicAuth = "Basic \(encodedCredentials)"
|
let basicAuth = "Basic \(encodedCredentials)"
|
||||||
request.headers["Authorization"] = basicAuth
|
request.addHeader(name: "Authorization", value: basicAuth)
|
||||||
}
|
}
|
||||||
|
|
||||||
func performRequest<Response: Decodable>(_ request: HTTPRequest) async throws -> Response {
|
func performRequest(_ request: HTTPRequest) async throws -> HTTPResponse {
|
||||||
try await urlSession.perform(RequestBuilder.build(request: request))
|
let urlRequest: URLRequest
|
||||||
|
do {
|
||||||
|
urlRequest = try RequestBuilder.build(request: request)
|
||||||
|
}
|
||||||
|
catch {
|
||||||
|
log.error("Invalid request \(request): \(error)")
|
||||||
|
throw ServiceError.malformedRequest(request)
|
||||||
|
}
|
||||||
|
|
||||||
|
let start = Date()
|
||||||
|
let (data, response) = try await urlSession.data(for: urlRequest)
|
||||||
|
let httpResponse = HTTPResponse(response: response, data: data, error: nil)
|
||||||
|
|
||||||
|
let end = Date()
|
||||||
|
let duration = end.timeIntervalSince1970 - start.timeIntervalSince1970
|
||||||
|
logRequest(request, response: httpResponse, duration: duration)
|
||||||
|
|
||||||
|
return httpResponse
|
||||||
}
|
}
|
||||||
|
|
||||||
private func scrubParameters(_ parameters: [String: any Sendable], for url: URL) -> [String: any Sendable] {
|
private func scrubParameters(_ parameters: [String: any Sendable], for url: URL) -> [String: any Sendable] {
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@
|
||||||
import Foundation
|
import Foundation
|
||||||
|
|
||||||
/// Content types that can be automatically handled by HTTPRequest.
|
/// Content types that can be automatically handled by HTTPRequest.
|
||||||
public enum HTTPContentType: Sendable, Equatable, CustomStringConvertible {
|
public enum HTTPContentType: Sendable, CustomStringConvertible {
|
||||||
|
|
||||||
/// application/x-www-form-urlencoded
|
/// application/x-www-form-urlencoded
|
||||||
case formEncoded
|
case formEncoded
|
||||||
|
|
@ -21,9 +21,6 @@ public enum HTTPContentType: Sendable, Equatable, CustomStringConvertible {
|
||||||
/// multipart/form-data (set automatically when parts are added)
|
/// multipart/form-data (set automatically when parts are added)
|
||||||
case multipart
|
case multipart
|
||||||
|
|
||||||
/// Custom content type with arbitrary MIME type
|
|
||||||
case custom(String)
|
|
||||||
|
|
||||||
public var description: String {
|
public var description: String {
|
||||||
switch self {
|
switch self {
|
||||||
case .formEncoded:
|
case .formEncoded:
|
||||||
|
|
@ -34,8 +31,6 @@ public enum HTTPContentType: Sendable, Equatable, CustomStringConvertible {
|
||||||
return "application/json"
|
return "application/json"
|
||||||
case .multipart:
|
case .multipart:
|
||||||
return "multipart/form-data"
|
return "multipart/form-data"
|
||||||
case .custom(let mimeType):
|
|
||||||
return mimeType
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,50 +0,0 @@
|
||||||
//
|
|
||||||
// Created by Sami Samhuri on 2025-06-23.
|
|
||||||
// Copyright © 2025 Sami Samhuri. All rights reserved.
|
|
||||||
// Released under the terms of the MIT license.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
/// Errors that can occur during HTTP operations, outside of the network layer which is already covered by `URLError`.
|
|
||||||
public enum HTTPError: Error {
|
|
||||||
/// The server returned a non-success HTTP status code.
|
|
||||||
case failure(statusCode: Int, data: Data, response: HTTPURLResponse)
|
|
||||||
|
|
||||||
/// The response was not a valid HTTP response.
|
|
||||||
case invalidResponse
|
|
||||||
}
|
|
||||||
|
|
||||||
private extension String {
|
|
||||||
func truncated(to maxCharacters: Int = 50) -> String {
|
|
||||||
count < 50 ? self : "\(prefix(maxCharacters))..."
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension HTTPError: LocalizedError {
|
|
||||||
public var errorDescription: String? {
|
|
||||||
switch self {
|
|
||||||
case let .failure(statusCode, data, _):
|
|
||||||
let bodyString = String(data: data, encoding: .utf8) ?? "<non-UTF8 data>"
|
|
||||||
return "HTTP \(statusCode) error. Response body: \(bodyString.truncated())"
|
|
||||||
case .invalidResponse:
|
|
||||||
return "Invalid HTTP response"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
extension HTTPError: CustomDebugStringConvertible {
|
|
||||||
public var debugDescription: String {
|
|
||||||
switch self {
|
|
||||||
case let .failure(statusCode, data, response):
|
|
||||||
let bodyString = String(data: data, encoding: .utf8) ?? "<\(data.count) bytes of non-UTF8 data>"
|
|
||||||
return """
|
|
||||||
HTTPError: \(statusCode) \(HTTPURLResponse.localizedString(forStatusCode: statusCode))
|
|
||||||
URL: \(response.url?.absoluteString ?? "nil")
|
|
||||||
Body: \(bodyString.truncated())
|
|
||||||
"""
|
|
||||||
case .invalidResponse:
|
|
||||||
return "HTTPError: Invalid HTTP response"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -6,39 +6,12 @@
|
||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
import OSLog
|
import OSLog
|
||||||
import UniformTypeIdentifiers
|
|
||||||
|
|
||||||
#if canImport(UIKit)
|
#if canImport(UIKit)
|
||||||
import UIKit
|
import UIKit
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
private let log = Logger(subsystem: "net.samhuri.Osiris", category: "HTTPRequest")
|
private let log = Logger(subsystem: "co.1se.Osiris", category: "HTTPRequest")
|
||||||
|
|
||||||
/// The body content of an HTTP request.
|
|
||||||
public enum HTTPRequestBody: Sendable {
|
|
||||||
/// No body content.
|
|
||||||
case none
|
|
||||||
/// Parameters to be encoded as form data.
|
|
||||||
case formParameters([String: any Sendable])
|
|
||||||
/// Parameters to be encoded as JSON.
|
|
||||||
case jsonParameters([String: any Sendable])
|
|
||||||
/// Raw data with specified content type.
|
|
||||||
case data(Data, contentType: UTType)
|
|
||||||
/// Multipart form data parts.
|
|
||||||
case multipart([MultipartFormEncoder.Part])
|
|
||||||
/// File data to be streamed from disk.
|
|
||||||
case fileData(URL)
|
|
||||||
|
|
||||||
/// Returns true if this body represents no content.
|
|
||||||
public var isEmpty: Bool {
|
|
||||||
switch self {
|
|
||||||
case .none:
|
|
||||||
return true
|
|
||||||
default:
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A structure representing an HTTP request with support for various content types and multipart forms.
|
/// A structure representing an HTTP request with support for various content types and multipart forms.
|
||||||
///
|
///
|
||||||
|
|
@ -54,10 +27,11 @@ public enum HTTPRequestBody: Sendable {
|
||||||
/// parameters: ["page": "1", "limit": "10"]
|
/// parameters: ["page": "1", "limit": "10"]
|
||||||
/// )
|
/// )
|
||||||
///
|
///
|
||||||
/// // POST with JSON body
|
/// // POST with JSON parameters
|
||||||
/// let jsonRequest = HTTPRequest.postJSON(
|
/// let jsonRequest = HTTPRequest.post(
|
||||||
/// URL(string: "https://api.example.net/users")!,
|
/// URL(string: "https://api.example.net/users")!,
|
||||||
/// body: ["name": "Chali 2na", "email": "chali@example.net"]
|
/// contentType: .json,
|
||||||
|
/// parameters: ["name": "Jane", "email": "jane@example.net"]
|
||||||
/// )
|
/// )
|
||||||
///
|
///
|
||||||
/// // DELETE with query parameters
|
/// // DELETE with query parameters
|
||||||
|
|
@ -67,25 +41,11 @@ public enum HTTPRequestBody: Sendable {
|
||||||
/// )
|
/// )
|
||||||
///
|
///
|
||||||
/// // Multipart form with file upload
|
/// // Multipart form with file upload
|
||||||
/// let uploadURL = URL(string: "https://api.example.net/upload")!
|
/// var multipartRequest = HTTPRequest.post(URL(string: "https://api.example.net/upload")!)
|
||||||
/// let multipartRequest = HTTPRequest.postMultipart(uploadURL, parts: [
|
/// multipartRequest.parts = [
|
||||||
/// .text("Trent Reznor", name: "name"),
|
/// .text("Jane Doe", name: "name"),
|
||||||
/// .data(imageData, name: "avatar", type: "image/jpeg", filename: "avatar.jpg")
|
/// .data(imageData, name: "avatar", type: "image/jpeg", filename: "avatar.jpg")
|
||||||
/// ])
|
/// ]
|
||||||
///
|
|
||||||
/// // File streaming for large request bodies
|
|
||||||
/// let fileRequest = HTTPRequest.postFile(
|
|
||||||
/// URL(string: "https://api.example.net/upload")!,
|
|
||||||
/// fileURL: URL(fileURLWithPath: "/path/to/large/file.zip")
|
|
||||||
/// )
|
|
||||||
///
|
|
||||||
/// // Custom content types like XML
|
|
||||||
/// let xmlData = "<request><artist>Nine Inch Nails</artist></request>".data(using: .utf8)!
|
|
||||||
/// let xmlRequest = HTTPRequest.post(
|
|
||||||
/// URL(string: "https://api.example.net/music")!,
|
|
||||||
/// data: xmlData,
|
|
||||||
/// contentType: .xml
|
|
||||||
/// )
|
|
||||||
/// ```
|
/// ```
|
||||||
public struct HTTPRequest: Sendable, CustomStringConvertible {
|
public struct HTTPRequest: Sendable, CustomStringConvertible {
|
||||||
|
|
||||||
|
|
@ -95,145 +55,33 @@ public struct HTTPRequest: Sendable, CustomStringConvertible {
|
||||||
/// The target URL for this request.
|
/// The target URL for this request.
|
||||||
public var url: URL
|
public var url: URL
|
||||||
|
|
||||||
/// The body content for this request.
|
/// The content type for the request body.
|
||||||
public var body: HTTPRequestBody
|
public var contentType: HTTPContentType
|
||||||
|
|
||||||
|
/// Parameters to be encoded according to the content type.
|
||||||
|
public var parameters: [String: any Sendable]?
|
||||||
|
|
||||||
/// Additional HTTP headers for the request.
|
/// Additional HTTP headers for the request.
|
||||||
public var headers: [String: String] = [:]
|
public var headers: [String: String] = [:]
|
||||||
|
|
||||||
// MARK: - Deprecated Properties
|
/// Multipart form parts (automatically sets contentType to .multipart when non-empty).
|
||||||
|
public var parts: [MultipartFormEncoder.Part] = [] {
|
||||||
/// Parameters to be encoded according to the content type.
|
didSet {
|
||||||
@available(*, deprecated, message: "Access parameters through the body property instead")
|
if !parts.isEmpty { contentType = .multipart }
|
||||||
public var parameters: [String: any Sendable]? {
|
|
||||||
get {
|
|
||||||
switch body {
|
|
||||||
case .formParameters(let params), .jsonParameters(let params):
|
|
||||||
return params
|
|
||||||
default:
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
}
|
|
||||||
set {
|
|
||||||
guard let newValue = newValue else {
|
|
||||||
body = .none
|
|
||||||
return
|
|
||||||
}
|
|
||||||
// Preserve existing encoding type if possible
|
|
||||||
switch body {
|
|
||||||
case .jsonParameters:
|
|
||||||
body = .jsonParameters(newValue)
|
|
||||||
case .formParameters, .none:
|
|
||||||
body = .formParameters(newValue)
|
|
||||||
default:
|
|
||||||
// Can't set parameters on other body types
|
|
||||||
break
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Multipart form parts.
|
/// Creates a new HTTP request.
|
||||||
@available(*, deprecated, message: "Use postMultipart(_:parts:) or access parts through the body property")
|
|
||||||
public var parts: [MultipartFormEncoder.Part] {
|
|
||||||
get {
|
|
||||||
if case .multipart(let parts) = body {
|
|
||||||
return parts
|
|
||||||
}
|
|
||||||
return []
|
|
||||||
}
|
|
||||||
set {
|
|
||||||
body = .multipart(newValue)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The content type for the request body (computed from body content).
|
|
||||||
public var contentType: HTTPContentType {
|
|
||||||
switch body {
|
|
||||||
case .none:
|
|
||||||
return .none
|
|
||||||
case .formParameters:
|
|
||||||
// For GET/DELETE, parameters go in query string, so no body content type
|
|
||||||
if method == .get || method == .delete {
|
|
||||||
return .none
|
|
||||||
}
|
|
||||||
return .formEncoded
|
|
||||||
case .jsonParameters:
|
|
||||||
// For GET/DELETE, parameters go in query string, so no body content type
|
|
||||||
if method == .get || method == .delete {
|
|
||||||
return .none
|
|
||||||
}
|
|
||||||
return .json
|
|
||||||
case let .data(_, contentType):
|
|
||||||
if let mimeType = contentType.preferredMIMEType {
|
|
||||||
return .custom(mimeType)
|
|
||||||
} else {
|
|
||||||
log.warning("No MIME type found for UTType \(contentType), falling back to application/octet-stream")
|
|
||||||
return .custom("application/octet-stream")
|
|
||||||
}
|
|
||||||
case .multipart:
|
|
||||||
return .multipart
|
|
||||||
case .fileData:
|
|
||||||
return .none
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a new HTTP request, verifying that no body is provided for GET and DELETE requests. When a body is provided with
|
|
||||||
/// those requests then an error is thrown.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - method: The HTTP method to use
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - body: The body content for the request
|
|
||||||
/// - Throws: HTTPRequestError.invalidRequestBody if GET or DELETE request has a body
|
|
||||||
public init(method: HTTPMethod, url: URL, body: HTTPRequestBody = .none) throws {
|
|
||||||
guard method != .get && method != .delete || body.isEmpty else {
|
|
||||||
throw HTTPRequestError.invalidRequestBody
|
|
||||||
}
|
|
||||||
self.method = method
|
|
||||||
self.url = url
|
|
||||||
self.body = body
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Internal initializer that bypasses validation for convenience methods that we don't want to be throwing in the public API.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - method: The HTTP method to use
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - body: The body content for the request
|
|
||||||
init(uncheckedMethod method: HTTPMethod, url: URL, body: HTTPRequestBody = .none) {
|
|
||||||
self.method = method
|
|
||||||
self.url = url
|
|
||||||
self.body = body
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a new HTTP request with the old API.
|
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - method: The HTTP method to use
|
/// - method: The HTTP method to use
|
||||||
/// - url: The target URL
|
/// - url: The target URL
|
||||||
/// - contentType: The content type for encoding parameters
|
/// - contentType: The content type for encoding parameters
|
||||||
/// - parameters: Optional parameters to include in the request body
|
/// - parameters: Optional parameters to include in the request body
|
||||||
@available(*, deprecated, message: "Use the new initializer or convenience methods like postJSON() instead. Note: GET/DELETE with parameters now use query strings.")
|
|
||||||
public init(method: HTTPMethod, url: URL, contentType: HTTPContentType = .none, parameters: [String: any Sendable]? = nil) {
|
public init(method: HTTPMethod, url: URL, contentType: HTTPContentType = .none, parameters: [String: any Sendable]? = nil) {
|
||||||
self.method = method
|
self.method = method
|
||||||
self.url = url
|
self.url = url
|
||||||
|
self.contentType = contentType
|
||||||
// Convert old API to new body format
|
self.parameters = parameters
|
||||||
if let parameters = parameters {
|
|
||||||
if method == .get || method == .delete {
|
|
||||||
// For backward compatibility, GET/DELETE with parameters were previously ignored
|
|
||||||
// Now they're encoded as query parameters via formParameters
|
|
||||||
self.body = .formParameters(parameters)
|
|
||||||
} else {
|
|
||||||
switch contentType {
|
|
||||||
case .json:
|
|
||||||
self.body = .jsonParameters(parameters)
|
|
||||||
case .formEncoded:
|
|
||||||
self.body = .formParameters(parameters)
|
|
||||||
default:
|
|
||||||
self.body = .formParameters(parameters)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
self.body = .none
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates a GET request.
|
/// Creates a GET request.
|
||||||
|
|
@ -242,46 +90,27 @@ public struct HTTPRequest: Sendable, CustomStringConvertible {
|
||||||
/// - parameters: Optional parameters to include as query string
|
/// - parameters: Optional parameters to include as query string
|
||||||
/// - Returns: A configured HTTPRequest
|
/// - Returns: A configured HTTPRequest
|
||||||
public static func get(_ url: URL, parameters: [String: any Sendable]? = nil) -> HTTPRequest {
|
public static func get(_ url: URL, parameters: [String: any Sendable]? = nil) -> HTTPRequest {
|
||||||
let body: HTTPRequestBody = parameters.map { .formParameters($0) } ?? .none
|
HTTPRequest(method: .get, url: url, contentType: .none, parameters: parameters)
|
||||||
return HTTPRequest(uncheckedMethod: .get, url: url, body: body)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates a PUT request with a URL-encoded form body.
|
/// Creates a PUT request.
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - url: The target URL
|
/// - url: The target URL
|
||||||
/// - parameters: Parameters to encode as URL-encoded form body
|
/// - contentType: The content type for encoding parameters
|
||||||
|
/// - parameters: Optional parameters to include in the request body
|
||||||
/// - Returns: A configured HTTPRequest
|
/// - Returns: A configured HTTPRequest
|
||||||
public static func putForm(_ url: URL, parameters: [String: any Sendable]? = nil) -> HTTPRequest {
|
public static func put(_ url: URL, contentType: HTTPContentType = .none, parameters: [String: any Sendable]? = nil) -> HTTPRequest {
|
||||||
let body: HTTPRequestBody = parameters.map { .formParameters($0) } ?? .none
|
HTTPRequest(method: .put, url: url, contentType: contentType, parameters: parameters)
|
||||||
return HTTPRequest(uncheckedMethod: .put, url: url, body: body)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates a PUT request with a JSON body.
|
/// Creates a POST request.
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - url: The target URL
|
/// - url: The target URL
|
||||||
/// - body: Dictionary to encode as JSON body
|
/// - contentType: The content type for encoding parameters
|
||||||
|
/// - parameters: Optional parameters to include in the request body
|
||||||
/// - Returns: A configured HTTPRequest
|
/// - Returns: A configured HTTPRequest
|
||||||
public static func putJSON(_ url: URL, body: [String: any Sendable]) -> HTTPRequest {
|
public static func post(_ url: URL, contentType: HTTPContentType = .none, parameters: [String: any Sendable]? = nil) -> HTTPRequest {
|
||||||
HTTPRequest(uncheckedMethod: .put, url: url, body: .jsonParameters(body))
|
HTTPRequest(method: .post, url: url, contentType: contentType, parameters: parameters)
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a POST request with a URL-encoded form body.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - parameters: Parameters to encode as URL-encoded form body
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
public static func postForm(_ url: URL, parameters: [String: any Sendable]? = nil) -> HTTPRequest {
|
|
||||||
let body: HTTPRequestBody = parameters.map { .formParameters($0) } ?? .none
|
|
||||||
return HTTPRequest(uncheckedMethod: .post, url: url, body: body)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a POST request with a JSON body.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - body: Dictionary to encode as JSON body
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
public static func postJSON(_ url: URL, body: [String: any Sendable]) -> HTTPRequest {
|
|
||||||
HTTPRequest(uncheckedMethod: .post, url: url, body: .jsonParameters(body))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Creates a DELETE request.
|
/// Creates a DELETE request.
|
||||||
|
|
@ -290,242 +119,7 @@ public struct HTTPRequest: Sendable, CustomStringConvertible {
|
||||||
/// - parameters: Optional parameters to include as query string
|
/// - parameters: Optional parameters to include as query string
|
||||||
/// - Returns: A configured HTTPRequest
|
/// - Returns: A configured HTTPRequest
|
||||||
public static func delete(_ url: URL, parameters: [String: any Sendable]? = nil) -> HTTPRequest {
|
public static func delete(_ url: URL, parameters: [String: any Sendable]? = nil) -> HTTPRequest {
|
||||||
let body: HTTPRequestBody = parameters.map { .formParameters($0) } ?? .none
|
HTTPRequest(method: .delete, url: url, contentType: .none, parameters: parameters)
|
||||||
return HTTPRequest(uncheckedMethod: .delete, url: url, body: body)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a basic POST request with no body.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
public static func post(_ url: URL) -> HTTPRequest {
|
|
||||||
HTTPRequest(uncheckedMethod: .post, url: url, body: .none)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a basic PUT request with no body.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
public static func put(_ url: URL) -> HTTPRequest {
|
|
||||||
HTTPRequest(uncheckedMethod: .put, url: url, body: .none)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a basic PATCH request with no body.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
public static func patch(_ url: URL) -> HTTPRequest {
|
|
||||||
HTTPRequest(uncheckedMethod: .patch, url: url, body: .none)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a POST request with a Codable body.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - body: The Codable object to encode as JSON
|
|
||||||
/// - encoder: The JSONEncoder to use (defaults to standard encoder)
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
/// - Throws: EncodingError if the body cannot be encoded
|
|
||||||
public static func post<T: Codable>(_ url: URL, body: T, encoder: JSONEncoder = JSONEncoder()) throws -> HTTPRequest {
|
|
||||||
let jsonData = try encoder.encode(body)
|
|
||||||
return HTTPRequest(uncheckedMethod: .post, url: url, body: .data(jsonData, contentType: .json))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a PUT request with a Codable body.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - body: The Codable object to encode as JSON
|
|
||||||
/// - encoder: The JSONEncoder to use (defaults to standard encoder)
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
/// - Throws: EncodingError if the body cannot be encoded
|
|
||||||
public static func put<T: Codable>(_ url: URL, body: T, encoder: JSONEncoder = JSONEncoder()) throws -> HTTPRequest {
|
|
||||||
let jsonData = try encoder.encode(body)
|
|
||||||
return HTTPRequest(uncheckedMethod: .put, url: url, body: .data(jsonData, contentType: .json))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a PATCH request with a URL-encoded form body.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - parameters: Parameters to encode as URL-encoded form body
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
public static func patchForm(_ url: URL, parameters: [String: any Sendable]? = nil) -> HTTPRequest {
|
|
||||||
let body: HTTPRequestBody = parameters.map { .formParameters($0) } ?? .none
|
|
||||||
return HTTPRequest(uncheckedMethod: .patch, url: url, body: body)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a PATCH request with a JSON body.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - body: Dictionary to encode as JSON body
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
public static func patchJSON(_ url: URL, body: [String: any Sendable]) -> HTTPRequest {
|
|
||||||
HTTPRequest(uncheckedMethod: .patch, url: url, body: .jsonParameters(body))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a PATCH request with a Codable body.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - body: The Codable object to encode as JSON
|
|
||||||
/// - encoder: The JSONEncoder to use (defaults to standard encoder)
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
/// - Throws: EncodingError if the body cannot be encoded
|
|
||||||
public static func patch<T: Codable>(_ url: URL, body: T, encoder: JSONEncoder = JSONEncoder()) throws -> HTTPRequest {
|
|
||||||
let jsonData = try encoder.encode(body)
|
|
||||||
return HTTPRequest(uncheckedMethod: .patch, url: url, body: .data(jsonData, contentType: .json))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a POST request with multipart form data.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - parts: The multipart form parts
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
public static func postMultipart(_ url: URL, parts: [MultipartFormEncoder.Part]) -> HTTPRequest {
|
|
||||||
HTTPRequest(uncheckedMethod: .post, url: url, body: .multipart(parts))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a PUT request with multipart form data.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - parts: The multipart form parts
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
public static func putMultipart(_ url: URL, parts: [MultipartFormEncoder.Part]) -> HTTPRequest {
|
|
||||||
HTTPRequest(uncheckedMethod: .put, url: url, body: .multipart(parts))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a PATCH request with multipart form data.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - parts: The multipart form parts
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
public static func patchMultipart(_ url: URL, parts: [MultipartFormEncoder.Part]) -> HTTPRequest {
|
|
||||||
HTTPRequest(uncheckedMethod: .patch, url: url, body: .multipart(parts))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a POST request with raw data and content type.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - data: The raw data to send
|
|
||||||
/// - contentType: The uniform type identifier for the data
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
public static func post(_ url: URL, data: Data, contentType: UTType) -> HTTPRequest {
|
|
||||||
HTTPRequest(uncheckedMethod: .post, url: url, body: .data(data, contentType: contentType))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a PUT request with raw data and content type.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - data: The raw data to send
|
|
||||||
/// - contentType: The uniform type identifier for the data
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
public static func put(_ url: URL, data: Data, contentType: UTType) -> HTTPRequest {
|
|
||||||
HTTPRequest(uncheckedMethod: .put, url: url, body: .data(data, contentType: contentType))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a PATCH request with raw data and content type.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - data: The raw data to send
|
|
||||||
/// - contentType: The uniform type identifier for the data
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
public static func patch(_ url: URL, data: Data, contentType: UTType) -> HTTPRequest {
|
|
||||||
HTTPRequest(uncheckedMethod: .patch, url: url, body: .data(data, contentType: contentType))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a POST request with file data to be streamed from disk.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - fileURL: The file URL to stream as the request body
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
public static func postFile(_ url: URL, fileURL: URL) -> HTTPRequest {
|
|
||||||
HTTPRequest(uncheckedMethod: .post, url: url, body: .fileData(fileURL))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a PUT request with file data to be streamed from disk.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - fileURL: The file URL to stream as the request body
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
public static func putFile(_ url: URL, fileURL: URL) -> HTTPRequest {
|
|
||||||
HTTPRequest(uncheckedMethod: .put, url: url, body: .fileData(fileURL))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a PATCH request with file data to be streamed from disk.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - fileURL: The file URL to stream as the request body
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
public static func patchFile(_ url: URL, fileURL: URL) -> HTTPRequest {
|
|
||||||
HTTPRequest(uncheckedMethod: .patch, url: url, body: .fileData(fileURL))
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Deprecated Methods
|
|
||||||
|
|
||||||
/// Creates a POST request with parameters.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - contentType: The content type for encoding parameters
|
|
||||||
/// - parameters: Optional parameters to include in the request body
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
@available(*, deprecated, message: "Use postJSON(_:body:) or postForm(_:parameters:) instead")
|
|
||||||
public static func post(_ url: URL, contentType: HTTPContentType = .none, parameters: [String: any Sendable]? = nil) -> HTTPRequest {
|
|
||||||
guard let parameters = parameters else {
|
|
||||||
return HTTPRequest(uncheckedMethod: .post, url: url)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch contentType {
|
|
||||||
case .json:
|
|
||||||
return postJSON(url, body: parameters)
|
|
||||||
case .formEncoded:
|
|
||||||
return postForm(url, parameters: parameters)
|
|
||||||
default:
|
|
||||||
// For backward compatibility, treat as form encoded
|
|
||||||
return postForm(url, parameters: parameters)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a PUT request with parameters.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - contentType: The content type for encoding parameters
|
|
||||||
/// - parameters: Optional parameters to include in the request body
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
@available(*, deprecated, message: "Use putJSON(_:body:) or putForm(_:parameters:) instead")
|
|
||||||
public static func put(_ url: URL, contentType: HTTPContentType = .none, parameters: [String: any Sendable]? = nil) -> HTTPRequest {
|
|
||||||
guard let parameters = parameters else {
|
|
||||||
return HTTPRequest(uncheckedMethod: .put, url: url)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch contentType {
|
|
||||||
case .json:
|
|
||||||
return putJSON(url, body: parameters)
|
|
||||||
case .formEncoded:
|
|
||||||
return putForm(url, parameters: parameters)
|
|
||||||
default:
|
|
||||||
// For backward compatibility, treat as form encoded
|
|
||||||
return putForm(url, parameters: parameters)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Creates a PATCH request with parameters.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - url: The target URL
|
|
||||||
/// - contentType: The content type for encoding parameters
|
|
||||||
/// - parameters: Optional parameters to include in the request body
|
|
||||||
/// - Returns: A configured HTTPRequest
|
|
||||||
@available(*, deprecated, message: "Use patchJSON(_:body:) or patchForm(_:parameters:) instead")
|
|
||||||
public static func patch(_ url: URL, contentType: HTTPContentType = .none, parameters: [String: any Sendable]? = nil) -> HTTPRequest {
|
|
||||||
guard let parameters = parameters else {
|
|
||||||
return HTTPRequest(uncheckedMethod: .patch, url: url)
|
|
||||||
}
|
|
||||||
|
|
||||||
switch contentType {
|
|
||||||
case .json:
|
|
||||||
return patchJSON(url, body: parameters)
|
|
||||||
case .formEncoded:
|
|
||||||
return patchForm(url, parameters: parameters)
|
|
||||||
default:
|
|
||||||
// For backward compatibility, treat as form encoded
|
|
||||||
return patchForm(url, parameters: parameters)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#if canImport(UIKit)
|
#if canImport(UIKit)
|
||||||
|
|
@ -541,23 +135,16 @@ public struct HTTPRequest: Sendable, CustomStringConvertible {
|
||||||
log.error("Cannot compress image as JPEG data for parameter \(name) (\(filename ?? ""))")
|
log.error("Cannot compress image as JPEG data for parameter \(name) (\(filename ?? ""))")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
parts.append(
|
||||||
let newPart = MultipartFormEncoder.Part.data(data, name: name, type: "image/jpeg", filename: filename ?? "image.jpeg")
|
.data(data, name: name, type: "image/jpeg", filename: filename ?? "image.jpeg")
|
||||||
|
)
|
||||||
switch body {
|
|
||||||
case let .multipart(existingParts):
|
|
||||||
body = .multipart(existingParts + [newPart])
|
|
||||||
default:
|
|
||||||
body = .multipart([newPart])
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
/// Adds a header to this request. Deprecated in favour of directly modifying the ``headers`` dictionary.
|
/// Adds a header to this request.
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - name: The header name
|
/// - name: The header name
|
||||||
/// - value: The header value
|
/// - value: The header value
|
||||||
@available(*, deprecated, message: "Modify the headers dictionary directly on this request instead.")
|
|
||||||
public mutating func addHeader(name: String, value: String) {
|
public mutating func addHeader(name: String, value: String) {
|
||||||
headers[name] = value
|
headers[name] = value
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -15,17 +15,12 @@ public enum HTTPRequestError: Error, LocalizedError, CustomStringConvertible {
|
||||||
/// An unknown error occurred (typically when URLResponse isn't HTTPURLResponse).
|
/// An unknown error occurred (typically when URLResponse isn't HTTPURLResponse).
|
||||||
case unknown
|
case unknown
|
||||||
|
|
||||||
/// Invalid request body for the HTTP method.
|
|
||||||
case invalidRequestBody
|
|
||||||
|
|
||||||
public var errorDescription: String? {
|
public var errorDescription: String? {
|
||||||
switch self {
|
switch self {
|
||||||
case .http:
|
case .http:
|
||||||
return "HTTP request failed with non-2xx status code"
|
return "HTTP request failed with non-2xx status code"
|
||||||
case .unknown:
|
case .unknown:
|
||||||
return "An unknown error occurred"
|
return "An unknown error occurred"
|
||||||
case .invalidRequestBody:
|
|
||||||
return "GET and DELETE requests cannot have a body"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -35,8 +30,6 @@ public enum HTTPRequestError: Error, LocalizedError, CustomStringConvertible {
|
||||||
return "The server returned an error status code"
|
return "The server returned an error status code"
|
||||||
case .unknown:
|
case .unknown:
|
||||||
return "An unexpected error occurred during the request"
|
return "An unexpected error occurred during the request"
|
||||||
case .invalidRequestBody:
|
|
||||||
return "The HTTP method does not support a request body"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -46,8 +39,6 @@ public enum HTTPRequestError: Error, LocalizedError, CustomStringConvertible {
|
||||||
return "Check the server response for error details"
|
return "Check the server response for error details"
|
||||||
case .unknown:
|
case .unknown:
|
||||||
return "Check network connectivity and try again"
|
return "Check network connectivity and try again"
|
||||||
case .invalidRequestBody:
|
|
||||||
return "Use query parameters instead of a request body for GET and DELETE requests"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -57,8 +48,6 @@ public enum HTTPRequestError: Error, LocalizedError, CustomStringConvertible {
|
||||||
"HTTPRequestError.http"
|
"HTTPRequestError.http"
|
||||||
case .unknown:
|
case .unknown:
|
||||||
"HTTPRequestError.unknown"
|
"HTTPRequestError.unknown"
|
||||||
case .invalidRequestBody:
|
|
||||||
"HTTPRequestError.invalidRequestBody"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,7 @@
|
||||||
import Foundation
|
import Foundation
|
||||||
import OSLog
|
import OSLog
|
||||||
|
|
||||||
private let log = Logger(subsystem: "net.samhuri.Osiris", category: "HTTPResponse")
|
private let log = Logger(subsystem: "co.1se.Osiris", category: "HTTPResponse")
|
||||||
|
|
||||||
/// A response from an HTTP request that simplifies URLSession's completion handler parameters.
|
/// A response from an HTTP request that simplifies URLSession's completion handler parameters.
|
||||||
///
|
///
|
||||||
|
|
@ -22,10 +22,10 @@ private let log = Logger(subsystem: "net.samhuri.Osiris", category: "HTTPRespons
|
||||||
/// let httpResponse = HTTPResponse(response: response, data: data, error: error)
|
/// let httpResponse = HTTPResponse(response: response, data: data, error: error)
|
||||||
///
|
///
|
||||||
/// switch httpResponse {
|
/// switch httpResponse {
|
||||||
/// case let .success(httpURLResponse, data):
|
/// case .success(let httpURLResponse, let data):
|
||||||
/// print("Success: \(httpURLResponse.statusCode)")
|
/// print("Success: \(httpURLResponse.statusCode)")
|
||||||
/// // Handle successful response
|
/// // Handle successful response
|
||||||
/// case let .failure(error, httpURLResponse, data):
|
/// case .failure(let error, let httpURLResponse, let data):
|
||||||
/// print("Failed: \(error)")
|
/// print("Failed: \(error)")
|
||||||
/// // Handle error response
|
/// // Handle error response
|
||||||
/// }
|
/// }
|
||||||
|
|
|
||||||
|
|
@ -59,21 +59,6 @@ extension MultipartFormEncoder {
|
||||||
public var description: String {
|
public var description: String {
|
||||||
"<BodyFile file=\(url.lastPathComponent) size=\(contentLength)>"
|
"<BodyFile file=\(url.lastPathComponent) size=\(contentLength)>"
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Removes the temporary file from disk.
|
|
||||||
///
|
|
||||||
/// Call this method when you're done with the file to clean up disk space.
|
|
||||||
/// This is especially important for large files or when creating many requests.
|
|
||||||
///
|
|
||||||
/// - Returns: `true` if the file was successfully removed, `false` otherwise
|
|
||||||
public func cleanup() -> Bool {
|
|
||||||
do {
|
|
||||||
try FileManager.default.removeItem(at: url)
|
|
||||||
return true
|
|
||||||
} catch {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Represents a single part in a multipart form.
|
/// Represents a single part in a multipart form.
|
||||||
|
|
|
||||||
|
|
@ -6,30 +6,30 @@
|
||||||
|
|
||||||
import Foundation
|
import Foundation
|
||||||
import OSLog
|
import OSLog
|
||||||
import UniformTypeIdentifiers
|
|
||||||
|
|
||||||
private let log = Logger(subsystem: "net.samhuri.Osiris", category: "RequestBuilder")
|
private let log = Logger(subsystem: "co.1se.Osiris", category: "RequestBuilder")
|
||||||
|
|
||||||
/// Errors that can occur when building URLRequest from ``HTTPRequest``.
|
/// Errors that can occur when building URLRequest from HTTPRequest.
|
||||||
public enum RequestBuilderError: Error {
|
public enum RequestBuilderError: Error {
|
||||||
|
|
||||||
/// The form data could not be encoded properly.
|
/// The form data could not be encoded properly.
|
||||||
case invalidFormData(HTTPRequest)
|
case invalidFormData(HTTPRequest)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Converts ``HTTPRequest`` instances to URLRequest for use with URLSession.
|
/// Converts HTTPRequest instances to URLRequest for use with URLSession.
|
||||||
///
|
///
|
||||||
/// ``RequestBuilder`` handles the encoding of different content types including JSON,
|
/// RequestBuilder handles the encoding of different content types including JSON,
|
||||||
/// form-encoded parameters, and multipart forms. For multipart forms, it encodes
|
/// form-encoded parameters, and multipart forms. For multipart forms, it encodes
|
||||||
/// everything in memory, so consider using the ``MultipartFormEncoder`` directly to
|
/// everything in memory, so consider using the MultipartFormEncoder directly for
|
||||||
/// encode large files to disk for streaming.
|
/// large files that should be streamed.
|
||||||
///
|
///
|
||||||
/// ## Usage
|
/// ## Usage
|
||||||
///
|
///
|
||||||
/// ```swift
|
/// ```swift
|
||||||
/// let httpRequest = HTTPRequest.postJSON(
|
/// let httpRequest = HTTPRequest.post(
|
||||||
/// URL(string: "https://trails.example.net/riders")!,
|
/// URL(string: "https://api.example.net/users")!,
|
||||||
/// body: ["name": "Trent Reznor", "email": "trent@example.net", "bike": "Santa Cruz Nomad"]
|
/// contentType: .json,
|
||||||
|
/// parameters: ["name": "Jane", "email": "jane@example.net"]
|
||||||
/// )
|
/// )
|
||||||
///
|
///
|
||||||
/// let urlRequest = try RequestBuilder.build(request: httpRequest)
|
/// let urlRequest = try RequestBuilder.build(request: httpRequest)
|
||||||
|
|
@ -40,7 +40,7 @@ public enum RequestBuilderError: Error {
|
||||||
/// ```
|
/// ```
|
||||||
public final class RequestBuilder {
|
public final class RequestBuilder {
|
||||||
|
|
||||||
/// Converts an ``HTTPRequest`` to a URLRequest ready for use with URLSession.
|
/// Converts an HTTPRequest to a URLRequest ready for use with URLSession.
|
||||||
///
|
///
|
||||||
/// This method handles encoding of parameters according to the request's method and content type:
|
/// This method handles encoding of parameters according to the request's method and content type:
|
||||||
/// - **GET/DELETE**: Parameters are encoded as query string parameters
|
/// - **GET/DELETE**: Parameters are encoded as query string parameters
|
||||||
|
|
@ -49,14 +49,14 @@ public final class RequestBuilder {
|
||||||
/// - `.multipart`: Parts are encoded as multipart/form-data (in memory)
|
/// - `.multipart`: Parts are encoded as multipart/form-data (in memory)
|
||||||
/// - `.none`: Falls back to form encoding for compatibility
|
/// - `.none`: Falls back to form encoding for compatibility
|
||||||
///
|
///
|
||||||
/// - Parameter request: The ``HTTPRequest`` to convert
|
/// - Parameter request: The HTTPRequest to convert
|
||||||
/// - Returns: A URLRequest ready for URLSession
|
/// - Returns: A URLRequest ready for URLSession
|
||||||
/// - Throws: ``RequestBuilderError/invalidFormData(_:)`` if form encoding fails, if GET/DELETE
|
/// - Throws: `RequestBuilderError.invalidFormData` if form encoding fails, if GET/DELETE
|
||||||
/// requests contain multipart parts, or various encoding errors from JSONSerialization
|
/// requests contain multipart parts, or various encoding errors from JSONSerialization
|
||||||
/// or ``MultipartFormEncoder``
|
/// or MultipartFormEncoder
|
||||||
///
|
///
|
||||||
/// - Warning: Multipart requests are encoded entirely in memory. For large files,
|
/// - Warning: Multipart requests are encoded entirely in memory. For large files,
|
||||||
/// consider using ``MultipartFormEncoder/encodeFile(parts:to:)`` to encode to disk first
|
/// consider using MultipartFormEncoder.encodeFile() directly
|
||||||
public class func build(request: HTTPRequest) throws -> URLRequest {
|
public class func build(request: HTTPRequest) throws -> URLRequest {
|
||||||
var result = URLRequest(url: request.url)
|
var result = URLRequest(url: request.url)
|
||||||
result.httpMethod = request.method.string
|
result.httpMethod = request.method.string
|
||||||
|
|
@ -65,67 +65,55 @@ public final class RequestBuilder {
|
||||||
result.addValue(value, forHTTPHeaderField: name)
|
result.addValue(value, forHTTPHeaderField: name)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Handle body content based on HTTP method and body type
|
// Handle parameters based on HTTP method
|
||||||
switch request.body {
|
if request.method == .get || request.method == .delete, let params = request.parameters {
|
||||||
case .none:
|
// Validate that GET and DELETE requests don't want request bodies, which we don't support.
|
||||||
break
|
guard request.contentType != .multipart, request.parts.isEmpty else {
|
||||||
case let .formParameters(params):
|
throw RequestBuilderError.invalidFormData(request)
|
||||||
if request.method == .get || request.method == .delete {
|
|
||||||
try encodeQueryParameters(to: &result, parameters: params)
|
|
||||||
} else {
|
|
||||||
try encodeFormParameters(to: &result, request: request, parameters: params)
|
|
||||||
}
|
}
|
||||||
case let .jsonParameters(params):
|
try encodeQueryParameters(to: &result, parameters: params)
|
||||||
if request.method == .get || request.method == .delete {
|
} else if !request.parts.isEmpty || request.contentType == .multipart {
|
||||||
try encodeQueryParameters(to: &result, parameters: params)
|
if request.contentType != .multipart {
|
||||||
} else {
|
log.info("Encoding request as multipart, overriding its content type of \(request.contentType)")
|
||||||
try encodeJSONParameters(to: &result, parameters: params)
|
|
||||||
}
|
}
|
||||||
case let .data(data, contentType):
|
try encodeMultipartContent(to: &result, request: request)
|
||||||
result.httpBody = data
|
} else if let params = request.parameters {
|
||||||
let mimeType = contentType.preferredMIMEType ?? "application/octet-stream"
|
try encodeParameters(to: &result, request: request, parameters: params)
|
||||||
if request.headers["Content-Type"] != nil {
|
|
||||||
log.warning("Overriding existing Content-Type header with \(mimeType) for data body")
|
|
||||||
}
|
|
||||||
result.addValue(mimeType, forHTTPHeaderField: "Content-Type")
|
|
||||||
case let .multipart(parts):
|
|
||||||
try encodeMultipartContent(to: &result, parts: parts)
|
|
||||||
case let .fileData(fileURL):
|
|
||||||
try encodeFileData(to: &result, fileURL: fileURL)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return result
|
return result
|
||||||
}
|
}
|
||||||
|
|
||||||
private class func encodeMultipartContent(to urlRequest: inout URLRequest, parts: [MultipartFormEncoder.Part]) throws {
|
private class func encodeMultipartContent(to urlRequest: inout URLRequest, request: HTTPRequest) throws {
|
||||||
let encoder = MultipartFormEncoder()
|
let encoder = MultipartFormEncoder()
|
||||||
let body = try encoder.encodeData(parts: parts)
|
let body = try encoder.encodeData(parts: request.parts)
|
||||||
|
|
||||||
if urlRequest.value(forHTTPHeaderField: "Content-Type") != nil {
|
|
||||||
log.warning("Overriding existing Content-Type header with \(body.contentType) for multipart body")
|
|
||||||
}
|
|
||||||
if urlRequest.value(forHTTPHeaderField: "Content-Length") != nil {
|
|
||||||
log.warning("Overriding existing Content-Length header with \(body.contentLength) for multipart body")
|
|
||||||
}
|
|
||||||
|
|
||||||
urlRequest.addValue(body.contentType, forHTTPHeaderField: "Content-Type")
|
urlRequest.addValue(body.contentType, forHTTPHeaderField: "Content-Type")
|
||||||
urlRequest.addValue("\(body.contentLength)", forHTTPHeaderField: "Content-Length")
|
urlRequest.addValue("\(body.contentLength)", forHTTPHeaderField: "Content-Length")
|
||||||
urlRequest.httpBody = body.data
|
urlRequest.httpBody = body.data
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private class func encodeParameters(to urlRequest: inout URLRequest, request: HTTPRequest, parameters: [String: any Sendable]) throws {
|
||||||
|
switch request.contentType {
|
||||||
|
case .json:
|
||||||
|
try encodeJSONParameters(to: &urlRequest, parameters: parameters)
|
||||||
|
|
||||||
|
case .none:
|
||||||
|
log.warning("Cannot serialize parameters without a content type, falling back to form encoding")
|
||||||
|
fallthrough
|
||||||
|
case .formEncoded:
|
||||||
|
try encodeFormParameters(to: &urlRequest, request: request, parameters: parameters)
|
||||||
|
|
||||||
|
case .multipart:
|
||||||
|
try encodeMultipartContent(to: &urlRequest, request: request)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private class func encodeJSONParameters(to urlRequest: inout URLRequest, parameters: [String: any Sendable]) throws {
|
private class func encodeJSONParameters(to urlRequest: inout URLRequest, parameters: [String: any Sendable]) throws {
|
||||||
if urlRequest.value(forHTTPHeaderField: "Content-Type") != nil {
|
|
||||||
log.warning("Overriding existing Content-Type header with application/json for JSON body")
|
|
||||||
}
|
|
||||||
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
|
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
|
||||||
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
|
urlRequest.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: [])
|
||||||
}
|
}
|
||||||
|
|
||||||
private class func encodeFormParameters(to urlRequest: inout URLRequest, request: HTTPRequest, parameters: [String: any Sendable]) throws {
|
private class func encodeFormParameters(to urlRequest: inout URLRequest, request: HTTPRequest, parameters: [String: any Sendable]) throws {
|
||||||
if urlRequest.value(forHTTPHeaderField: "Content-Type") != nil {
|
|
||||||
log.warning("Overriding existing Content-Type header with application/x-www-form-urlencoded for form body")
|
|
||||||
}
|
|
||||||
urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
|
urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
|
||||||
guard let formData = FormEncoder.encode(parameters).data(using: .utf8) else {
|
guard let formData = FormEncoder.encode(parameters).data(using: .utf8) else {
|
||||||
throw RequestBuilderError.invalidFormData(request)
|
throw RequestBuilderError.invalidFormData(request)
|
||||||
|
|
@ -151,30 +139,4 @@ public final class RequestBuilder {
|
||||||
|
|
||||||
urlRequest.url = components?.url ?? url
|
urlRequest.url = components?.url ?? url
|
||||||
}
|
}
|
||||||
|
|
||||||
private class func encodeFileData(to urlRequest: inout URLRequest, fileURL: URL) throws {
|
|
||||||
let inputStream = InputStream(url: fileURL)
|
|
||||||
urlRequest.httpBodyStream = inputStream
|
|
||||||
|
|
||||||
// Try to get file size for Content-Length header
|
|
||||||
if let fileAttributes = try? FileManager.default.attributesOfItem(atPath: fileURL.path),
|
|
||||||
let fileSize = fileAttributes[.size] as? Int {
|
|
||||||
if urlRequest.value(forHTTPHeaderField: "Content-Length") != nil {
|
|
||||||
log.warning("Overriding existing Content-Length header with \(fileSize) for file data")
|
|
||||||
}
|
|
||||||
urlRequest.addValue("\(fileSize)", forHTTPHeaderField: "Content-Length")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Try to determine Content-Type from file extension
|
|
||||||
let fileExtension = fileURL.pathExtension
|
|
||||||
if !fileExtension.isEmpty,
|
|
||||||
let utType = UTType(filenameExtension: fileExtension),
|
|
||||||
let mimeType = utType.preferredMIMEType {
|
|
||||||
if urlRequest.value(forHTTPHeaderField: "Content-Type") != nil {
|
|
||||||
log.warning("Overriding existing Content-Type header with \(mimeType) for file data")
|
|
||||||
}
|
|
||||||
urlRequest.addValue(mimeType, forHTTPHeaderField: "Content-Type")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,70 +0,0 @@
|
||||||
//
|
|
||||||
// Created by Sami Samhuri on 2025-06-23.
|
|
||||||
// Copyright © 2025 Sami Samhuri. All rights reserved.
|
|
||||||
// Released under the terms of the MIT license.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
/// URLSession extensions for Osiris HTTP requests with automatic JSON decoding.
|
|
||||||
extension URLSession {
|
|
||||||
|
|
||||||
/// Performs an ``HTTPRequest`` and returns decoded JSON response.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - request: The ``HTTPRequest`` to perform
|
|
||||||
/// - type: The expected response type
|
|
||||||
/// - decoder: JSONDecoder to use (defaults to standard decoder)
|
|
||||||
/// - Returns: Decoded response of the specified type
|
|
||||||
/// - Throws: ``HTTPError`` for HTTP errors, URLError for network issues, DecodingError for JSON parsing issues
|
|
||||||
public func perform<T: Decodable>(
|
|
||||||
_ request: HTTPRequest,
|
|
||||||
expecting type: T.Type,
|
|
||||||
decoder: JSONDecoder = JSONDecoder()
|
|
||||||
) async throws -> T {
|
|
||||||
let urlRequest = try RequestBuilder.build(request: request)
|
|
||||||
let (data, response) = try await self.data(for: urlRequest)
|
|
||||||
|
|
||||||
guard let httpResponse = response as? HTTPURLResponse else {
|
|
||||||
throw HTTPError.invalidResponse
|
|
||||||
}
|
|
||||||
|
|
||||||
guard (200..<300).contains(httpResponse.statusCode) else {
|
|
||||||
throw HTTPError.failure(statusCode: httpResponse.statusCode, data: data, response: httpResponse)
|
|
||||||
}
|
|
||||||
|
|
||||||
do {
|
|
||||||
return try decoder.decode(type, from: data)
|
|
||||||
} catch let decodingError as DecodingError {
|
|
||||||
throw decodingError
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Performs an ``HTTPRequest`` and returns decoded JSON response with type inference.
|
|
||||||
/// - Parameters:
|
|
||||||
/// - request: The ``HTTPRequest`` to perform
|
|
||||||
/// - decoder: JSONDecoder to use (defaults to standard decoder)
|
|
||||||
/// - Returns: Decoded response inferred from the return type
|
|
||||||
/// - Throws: ``HTTPError`` for HTTP errors, URLError for network issues, DecodingError for JSON parsing issues
|
|
||||||
public func perform<T: Decodable>(
|
|
||||||
_ request: HTTPRequest,
|
|
||||||
decoder: JSONDecoder = JSONDecoder()
|
|
||||||
) async throws -> T {
|
|
||||||
try await perform(request, expecting: T.self, decoder: decoder)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Performs an ``HTTPRequest`` expecting no content (e.g., 204 No Content).
|
|
||||||
/// - Parameter request: The ``HTTPRequest`` to perform
|
|
||||||
/// - Throws: ``HTTPError`` for HTTP errors, URLError for network issues
|
|
||||||
public func perform(_ request: HTTPRequest) async throws {
|
|
||||||
let urlRequest = try RequestBuilder.build(request: request)
|
|
||||||
let (data, response) = try await self.data(for: urlRequest)
|
|
||||||
|
|
||||||
guard let httpResponse = response as? HTTPURLResponse else {
|
|
||||||
throw HTTPError.invalidResponse
|
|
||||||
}
|
|
||||||
|
|
||||||
guard (200..<300).contains(httpResponse.statusCode) else {
|
|
||||||
throw HTTPError.failure(statusCode: httpResponse.statusCode, data: data, response: httpResponse)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -1,146 +0,0 @@
|
||||||
//
|
|
||||||
// Created by Sami Samhuri on 2025-06-23.
|
|
||||||
// Copyright © 2025 Sami Samhuri. All rights reserved.
|
|
||||||
// Released under the terms of the MIT license.
|
|
||||||
//
|
|
||||||
|
|
||||||
import XCTest
|
|
||||||
@testable import Osiris
|
|
||||||
|
|
||||||
class HTTPRequestCodableTests: XCTestCase {
|
|
||||||
let baseURL = URL(string: "https://trails.example.net")!
|
|
||||||
|
|
||||||
func testPOSTWithCodableBody() throws {
|
|
||||||
let rachel = CreateRiderRequest(name: "Rachel Atherton", email: "rachel@trails.example.net", bike: "Trek Session")
|
|
||||||
let request = try HTTPRequest.post(baseURL.appendingPathComponent("riders"), body: rachel)
|
|
||||||
|
|
||||||
XCTAssertEqual(request.method, .post)
|
|
||||||
XCTAssertEqual(request.url.path, "/riders")
|
|
||||||
|
|
||||||
// Verify the body contains JSON data
|
|
||||||
if case let .data(data, contentType) = request.body {
|
|
||||||
XCTAssertEqual(contentType, .json)
|
|
||||||
let decodedRider = try JSONDecoder().decode(CreateRiderRequest.self, from: data)
|
|
||||||
XCTAssertEqual(decodedRider.name, rachel.name)
|
|
||||||
XCTAssertEqual(decodedRider.email, rachel.email)
|
|
||||||
XCTAssertEqual(decodedRider.bike, rachel.bike)
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected data body with JSON content type")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testPOSTWithCustomEncoder() throws {
|
|
||||||
let encoder = JSONEncoder()
|
|
||||||
encoder.keyEncodingStrategy = .convertToSnakeCase
|
|
||||||
|
|
||||||
let danny = CreateRiderRequest(name: "Danny MacAskill", email: "danny@trails.example.net", bike: "Santa Cruz 5010")
|
|
||||||
let request = try HTTPRequest.post(baseURL.appendingPathComponent("riders"), body: danny, encoder: encoder)
|
|
||||||
|
|
||||||
XCTAssertEqual(request.method, .post)
|
|
||||||
|
|
||||||
if case let .data(data, _) = request.body {
|
|
||||||
let jsonString = String(data: data, encoding: .utf8)!
|
|
||||||
// Should use snake_case for JSON keys - verify the raw JSON contains the right keys
|
|
||||||
XCTAssertTrue(jsonString.contains("name"))
|
|
||||||
XCTAssertTrue(jsonString.contains("email"))
|
|
||||||
XCTAssertTrue(jsonString.contains("bike"))
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected data body")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testPUTWithCodableBody() throws {
|
|
||||||
let updateRider = CreateRiderRequest(name: "Greg Minnaar", email: "greg@trails.example.net", bike: "Santa Cruz V10")
|
|
||||||
let request = try HTTPRequest.put(baseURL.appendingPathComponent("riders/greg-minnaar"), body: updateRider)
|
|
||||||
|
|
||||||
XCTAssertEqual(request.method, .put)
|
|
||||||
XCTAssertEqual(request.url.path, "/riders/greg-minnaar")
|
|
||||||
|
|
||||||
if case let .data(data, contentType) = request.body {
|
|
||||||
XCTAssertEqual(contentType, .json)
|
|
||||||
XCTAssertNotNil(data)
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected data body")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testPATCHWithCodableBody() throws {
|
|
||||||
let patchData = CreateRiderRequest(name: "Brandon Semenuk", email: "brandon@trails.example.net", bike: "Trek Ticket S")
|
|
||||||
let request = try HTTPRequest.patch(baseURL.appendingPathComponent("riders/brandon-semenuk"), body: patchData)
|
|
||||||
|
|
||||||
XCTAssertEqual(request.method, .patch)
|
|
||||||
XCTAssertEqual(request.url.path, "/riders/brandon-semenuk")
|
|
||||||
|
|
||||||
if case .data = request.body {
|
|
||||||
// Success - has data body
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected data body")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testRequestBuilderWithCodableBody() throws {
|
|
||||||
let aaron = CreateRiderRequest(name: "Aaron Gwin", email: "aaron@trails.example.net", bike: "Intense M29")
|
|
||||||
let request = try HTTPRequest.post(baseURL.appendingPathComponent("riders"), body: aaron)
|
|
||||||
|
|
||||||
let urlRequest = try RequestBuilder.build(request: request)
|
|
||||||
|
|
||||||
XCTAssertEqual(urlRequest.httpMethod, "POST")
|
|
||||||
XCTAssertEqual(urlRequest.value(forHTTPHeaderField: "Content-Type"), "application/json")
|
|
||||||
XCTAssertNotNil(urlRequest.httpBody)
|
|
||||||
|
|
||||||
// Test that the JSON is valid
|
|
||||||
if let body = urlRequest.httpBody {
|
|
||||||
let decodedRider = try JSONDecoder().decode(CreateRiderRequest.self, from: body)
|
|
||||||
XCTAssertEqual(decodedRider.name, "Aaron Gwin")
|
|
||||||
XCTAssertEqual(decodedRider.email, "aaron@trails.example.net")
|
|
||||||
XCTAssertEqual(decodedRider.bike, "Intense M29")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testURLSessionExtensionWithCustomDecoder() async throws {
|
|
||||||
// Test the URLSession extension methods exist and compile
|
|
||||||
let decoder = JSONDecoder()
|
|
||||||
decoder.keyDecodingStrategy = .convertFromSnakeCase
|
|
||||||
|
|
||||||
let request = HTTPRequest.get(baseURL.appendingPathComponent("riders"))
|
|
||||||
|
|
||||||
// These would work with a real server, but we're just testing compilation
|
|
||||||
Task {
|
|
||||||
do {
|
|
||||||
// Test type inference version
|
|
||||||
let inferred: [RiderProfile] = try await URLSession.shared.perform(request, decoder: decoder)
|
|
||||||
|
|
||||||
// Test explicit type version
|
|
||||||
let explicit: [RiderProfile] = try await URLSession.shared.perform(request, expecting: [RiderProfile].self, decoder: decoder)
|
|
||||||
|
|
||||||
XCTAssertEqual(inferred, explicit)
|
|
||||||
|
|
||||||
// Test perform version (no return value)
|
|
||||||
try await URLSession.shared.perform(request)
|
|
||||||
} catch {
|
|
||||||
// Expected to fail without a real server
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// If we get here, the methods exist and compile correctly
|
|
||||||
XCTAssertTrue(true)
|
|
||||||
}
|
|
||||||
|
|
||||||
func testHTTPErrorTypes() {
|
|
||||||
// Test HTTPError enum cases exist and provide useful information
|
|
||||||
let data = "Error message".data(using: .utf8)!
|
|
||||||
let response = HTTPURLResponse(url: baseURL, statusCode: 404, httpVersion: nil, headerFields: nil)!
|
|
||||||
|
|
||||||
let httpError = HTTPError.failure(statusCode: 404, data: data, response: response)
|
|
||||||
let invalidResponse = HTTPError.invalidResponse
|
|
||||||
|
|
||||||
// Test error descriptions are helpful
|
|
||||||
XCTAssertTrue(httpError.errorDescription?.contains("404") ?? false)
|
|
||||||
XCTAssertTrue(httpError.errorDescription?.contains("Error message") ?? false)
|
|
||||||
XCTAssertNotNil(invalidResponse.errorDescription)
|
|
||||||
|
|
||||||
// Test debug descriptions
|
|
||||||
XCTAssertTrue(httpError.debugDescription.contains("404"))
|
|
||||||
XCTAssertTrue(httpError.debugDescription.contains("Error message"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
@ -27,8 +27,7 @@ class HTTPRequestErrorTests: XCTestCase {
|
||||||
func testErrorDescriptionIsNeverNil() {
|
func testErrorDescriptionIsNeverNil() {
|
||||||
let allErrors: [HTTPRequestError] = [
|
let allErrors: [HTTPRequestError] = [
|
||||||
.http,
|
.http,
|
||||||
.unknown,
|
.unknown
|
||||||
.invalidRequestBody
|
|
||||||
]
|
]
|
||||||
|
|
||||||
for error in allErrors {
|
for error in allErrors {
|
||||||
|
|
@ -40,8 +39,7 @@ class HTTPRequestErrorTests: XCTestCase {
|
||||||
func testFailureReasonIsNeverNil() {
|
func testFailureReasonIsNeverNil() {
|
||||||
let allErrors: [HTTPRequestError] = [
|
let allErrors: [HTTPRequestError] = [
|
||||||
.http,
|
.http,
|
||||||
.unknown,
|
.unknown
|
||||||
.invalidRequestBody
|
|
||||||
]
|
]
|
||||||
|
|
||||||
for error in allErrors {
|
for error in allErrors {
|
||||||
|
|
@ -53,8 +51,7 @@ class HTTPRequestErrorTests: XCTestCase {
|
||||||
func testRecoverySuggestionIsNeverNil() {
|
func testRecoverySuggestionIsNeverNil() {
|
||||||
let allErrors: [HTTPRequestError] = [
|
let allErrors: [HTTPRequestError] = [
|
||||||
.http,
|
.http,
|
||||||
.unknown,
|
.unknown
|
||||||
.invalidRequestBody
|
|
||||||
]
|
]
|
||||||
|
|
||||||
for error in allErrors {
|
for error in allErrors {
|
||||||
|
|
@ -62,11 +59,4 @@ class HTTPRequestErrorTests: XCTestCase {
|
||||||
XCTAssertFalse(error.recoverySuggestion!.isEmpty)
|
XCTAssertFalse(error.recoverySuggestion!.isEmpty)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func testInvalidRequestBodyError() {
|
|
||||||
let error = HTTPRequestError.invalidRequestBody
|
|
||||||
XCTAssertEqual(error.localizedDescription, "GET and DELETE requests cannot have a body")
|
|
||||||
XCTAssertEqual(error.failureReason, "The HTTP method does not support a request body")
|
|
||||||
XCTAssertEqual(error.recoverySuggestion, "Use query parameters instead of a request body for GET and DELETE requests")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
@ -6,105 +6,68 @@
|
||||||
//
|
//
|
||||||
|
|
||||||
@testable import Osiris
|
@testable import Osiris
|
||||||
import UniformTypeIdentifiers
|
|
||||||
import XCTest
|
import XCTest
|
||||||
|
|
||||||
class HTTPRequestTests: XCTestCase {
|
class HTTPRequestTests: XCTestCase {
|
||||||
let baseURL = URL(string: "https://api.example.net")!
|
let baseURL = URL(string: "https://api.example.net")!
|
||||||
|
|
||||||
func testHTTPRequestInitialization() {
|
func testHTTPRequestInitialization() {
|
||||||
let request = HTTPRequest.get(baseURL)
|
let request = HTTPRequest(method: .get, url: baseURL)
|
||||||
XCTAssertEqual(request.method, .get)
|
XCTAssertEqual(request.method, .get)
|
||||||
XCTAssertEqual(request.url, baseURL)
|
XCTAssertEqual(request.url, baseURL)
|
||||||
XCTAssertEqual(request.contentType, .none)
|
XCTAssertEqual(request.contentType, .none)
|
||||||
XCTAssertTrue(request.body.isEmpty)
|
XCTAssertNil(request.parameters)
|
||||||
XCTAssertTrue(request.headers.isEmpty)
|
XCTAssertTrue(request.headers.isEmpty)
|
||||||
}
|
XCTAssertTrue(request.parts.isEmpty)
|
||||||
|
|
||||||
func testHTTPRequestInitializerValidation() throws {
|
|
||||||
// Valid requests should work
|
|
||||||
XCTAssertNoThrow(try HTTPRequest(method: .post, url: baseURL, body: .data(Data(), contentType: .json)))
|
|
||||||
XCTAssertNoThrow(try HTTPRequest(method: .put, url: baseURL, body: .formParameters(["test": "value"])))
|
|
||||||
XCTAssertNoThrow(try HTTPRequest(method: .patch, url: baseURL, body: .multipart([])))
|
|
||||||
|
|
||||||
// GET and DELETE with no body should work
|
|
||||||
XCTAssertNoThrow(try HTTPRequest(method: .get, url: baseURL))
|
|
||||||
XCTAssertNoThrow(try HTTPRequest(method: .delete, url: baseURL))
|
|
||||||
|
|
||||||
// GET with body should throw
|
|
||||||
XCTAssertThrowsError(try HTTPRequest(method: .get, url: baseURL, body: .data(Data(), contentType: .json))) { error in
|
|
||||||
XCTAssertEqual(error as? HTTPRequestError, .invalidRequestBody)
|
|
||||||
}
|
|
||||||
|
|
||||||
// DELETE with body should throw
|
|
||||||
XCTAssertThrowsError(try HTTPRequest(method: .delete, url: baseURL, body: .formParameters(["test": "value"]))) { error in
|
|
||||||
XCTAssertEqual(error as? HTTPRequestError, .invalidRequestBody)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func testHTTPRequestWithParameters() {
|
func testHTTPRequestWithParameters() {
|
||||||
let params = ["key": "value", "number": 42] as [String: any Sendable]
|
let params = ["key": "value", "number": 42] as [String: any Sendable]
|
||||||
let request = HTTPRequest.postJSON(baseURL, body: params)
|
let request = HTTPRequest(method: .post, url: baseURL, contentType: .json, parameters: params)
|
||||||
|
|
||||||
XCTAssertEqual(request.method, HTTPMethod.post)
|
XCTAssertEqual(request.method, .post)
|
||||||
XCTAssertEqual(request.contentType, HTTPContentType.json)
|
XCTAssertEqual(request.contentType, .json)
|
||||||
if case .jsonParameters(let bodyParams) = request.body {
|
XCTAssertNotNil(request.parameters)
|
||||||
XCTAssertEqual(bodyParams.count, 2)
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected jsonParameters body")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func testGETConvenience() {
|
func testGETConvenience() {
|
||||||
let request = HTTPRequest.get(baseURL)
|
let request = HTTPRequest.get(baseURL)
|
||||||
XCTAssertEqual(request.method, HTTPMethod.get)
|
XCTAssertEqual(request.method, .get)
|
||||||
XCTAssertEqual(request.url, baseURL)
|
XCTAssertEqual(request.url, baseURL)
|
||||||
XCTAssertEqual(request.contentType, HTTPContentType.none)
|
XCTAssertEqual(request.contentType, .none)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testPOSTConvenience() {
|
func testPOSTConvenience() {
|
||||||
let params = ["name": "Trent"]
|
let params = ["name": "Jane"]
|
||||||
let request = HTTPRequest.postJSON(baseURL, body: params)
|
let request = HTTPRequest.post(baseURL, contentType: .json, parameters: params)
|
||||||
|
|
||||||
XCTAssertEqual(request.method, HTTPMethod.post)
|
XCTAssertEqual(request.method, .post)
|
||||||
XCTAssertEqual(request.contentType, HTTPContentType.json)
|
XCTAssertEqual(request.contentType, .json)
|
||||||
if case .jsonParameters(let bodyParams) = request.body {
|
XCTAssertNotNil(request.parameters)
|
||||||
XCTAssertEqual(bodyParams.count, 1)
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected jsonParameters body")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func testPUTConvenience() {
|
func testPUTConvenience() {
|
||||||
let params = ["name": "Trent"]
|
let params = ["name": "Jane"]
|
||||||
let request = HTTPRequest.putForm(baseURL, parameters: params)
|
let request = HTTPRequest.put(baseURL, contentType: .formEncoded, parameters: params)
|
||||||
|
|
||||||
XCTAssertEqual(request.method, HTTPMethod.put)
|
XCTAssertEqual(request.method, .put)
|
||||||
XCTAssertEqual(request.contentType, HTTPContentType.formEncoded)
|
XCTAssertEqual(request.contentType, .formEncoded)
|
||||||
if case .formParameters(let bodyParams) = request.body {
|
XCTAssertNotNil(request.parameters)
|
||||||
XCTAssertEqual(bodyParams.count, 1)
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected formParameters body")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func testDELETEConvenience() {
|
func testDELETEConvenience() {
|
||||||
let request = HTTPRequest.delete(baseURL)
|
let request = HTTPRequest.delete(baseURL)
|
||||||
XCTAssertEqual(request.method, HTTPMethod.delete)
|
XCTAssertEqual(request.method, .delete)
|
||||||
XCTAssertEqual(request.url, baseURL)
|
XCTAssertEqual(request.url, baseURL)
|
||||||
XCTAssertEqual(request.contentType, HTTPContentType.none)
|
XCTAssertEqual(request.contentType, .none)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testMultipartPartsAutomaticallySetContentType() {
|
func testMultipartPartsAutomaticallySetContentType() {
|
||||||
let parts = [MultipartFormEncoder.Part.text("value", name: "field")]
|
var request = HTTPRequest.post(baseURL)
|
||||||
let request = HTTPRequest.postMultipart(baseURL, parts: parts)
|
XCTAssertEqual(request.contentType, .none)
|
||||||
|
|
||||||
XCTAssertEqual(request.contentType, HTTPContentType.multipart)
|
request.parts = [.text("value", name: "field")]
|
||||||
if case .multipart(let bodyParts) = request.body {
|
XCTAssertEqual(request.contentType, .multipart)
|
||||||
XCTAssertEqual(bodyParts.count, 1)
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected multipart body")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#if canImport(UIKit)
|
#if canImport(UIKit)
|
||||||
|
|
@ -119,21 +82,17 @@ class HTTPRequestTests: XCTestCase {
|
||||||
|
|
||||||
request.addMultipartJPEG(name: "avatar", image: image, quality: 0.8, filename: "test.jpg")
|
request.addMultipartJPEG(name: "avatar", image: image, quality: 0.8, filename: "test.jpg")
|
||||||
|
|
||||||
XCTAssertEqual(request.contentType, HTTPContentType.multipart)
|
XCTAssertEqual(request.parts.count, 1)
|
||||||
|
XCTAssertEqual(request.contentType, .multipart)
|
||||||
|
|
||||||
if case .multipart(let parts) = request.body {
|
let part = request.parts.first!
|
||||||
XCTAssertEqual(parts.count, 1)
|
XCTAssertEqual(part.name, "avatar")
|
||||||
let part = parts.first!
|
|
||||||
XCTAssertEqual(part.name, "avatar")
|
|
||||||
|
|
||||||
if case let .binaryData(_, type, filename) = part.content {
|
if case let .binaryData(_, type, filename) = part.content {
|
||||||
XCTAssertEqual(type, "image/jpeg")
|
XCTAssertEqual(type, "image/jpeg")
|
||||||
XCTAssertEqual(filename, "test.jpg")
|
XCTAssertEqual(filename, "test.jpg")
|
||||||
} else {
|
|
||||||
XCTFail("Expected binary data content")
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
XCTFail("Expected multipart body")
|
XCTFail("Expected binary data content")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -152,259 +111,56 @@ class HTTPRequestTests: XCTestCase {
|
||||||
|
|
||||||
// The method should handle extreme quality values gracefully
|
// The method should handle extreme quality values gracefully
|
||||||
// Either by clamping them or by having jpegData handle them
|
// Either by clamping them or by having jpegData handle them
|
||||||
if case .multipart(let parts) = request.body {
|
XCTAssertTrue(request.parts.count >= 0) // Should not crash
|
||||||
XCTAssertTrue(parts.count >= 0) // Should not crash
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
func testHTTPRequestPATCHConvenience() {
|
func testHTTPRequestPATCHConvenience() {
|
||||||
let params = ["status": "active"]
|
let params = ["status": "active"]
|
||||||
let request = HTTPRequest.patchJSON(baseURL, body: params)
|
let request = HTTPRequest(method: .patch, url: baseURL, contentType: .json, parameters: params)
|
||||||
|
|
||||||
XCTAssertEqual(request.method, HTTPMethod.patch)
|
XCTAssertEqual(request.method, .patch)
|
||||||
XCTAssertEqual(request.contentType, HTTPContentType.json)
|
XCTAssertEqual(request.contentType, .json)
|
||||||
if case .jsonParameters(let bodyParams) = request.body {
|
XCTAssertNotNil(request.parameters)
|
||||||
XCTAssertEqual(bodyParams.count, 1)
|
}
|
||||||
} else {
|
|
||||||
XCTFail("Expected jsonParameters body")
|
func testHTTPRequestWithMultipleHeaders() {
|
||||||
}
|
var request = HTTPRequest.get(baseURL)
|
||||||
|
request.addHeader(name: "Authorization", value: "Bearer token123")
|
||||||
|
request.addHeader(name: "User-Agent", value: "Osiris/2.0")
|
||||||
|
request.addHeader(name: "Accept", value: "application/json")
|
||||||
|
|
||||||
|
XCTAssertEqual(request.headers["Authorization"], "Bearer token123")
|
||||||
|
XCTAssertEqual(request.headers["User-Agent"], "Osiris/2.0")
|
||||||
|
XCTAssertEqual(request.headers["Accept"], "application/json")
|
||||||
|
XCTAssertEqual(request.headers.count, 3)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testHTTPRequestOverwriteHeaders() {
|
||||||
|
var request = HTTPRequest.get(baseURL)
|
||||||
|
request.addHeader(name: "Accept", value: "application/xml")
|
||||||
|
request.addHeader(name: "Accept", value: "application/json") // Should overwrite
|
||||||
|
|
||||||
|
XCTAssertEqual(request.headers["Accept"], "application/json")
|
||||||
|
XCTAssertEqual(request.headers.count, 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testHTTPRequestWithEmptyMultipartParts() {
|
func testHTTPRequestWithEmptyMultipartParts() {
|
||||||
let request = HTTPRequest.postMultipart(baseURL, parts: [])
|
var request = HTTPRequest.post(baseURL)
|
||||||
|
request.parts = [] // Empty parts array
|
||||||
|
|
||||||
XCTAssertEqual(request.contentType, HTTPContentType.multipart) // Multipart even with empty parts
|
XCTAssertEqual(request.contentType, .none) // Should not be set to multipart
|
||||||
if case .multipart(let parts) = request.body {
|
XCTAssertTrue(request.parts.isEmpty)
|
||||||
XCTAssertTrue(parts.isEmpty)
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected multipart body")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func testHTTPRequestBodyTypeDeterminesContentType() {
|
func testHTTPRequestMultipartPartsResetContentType() {
|
||||||
let jsonRequest = HTTPRequest.postJSON(baseURL, body: ["test": "value"])
|
var request = HTTPRequest.post(baseURL, contentType: .json)
|
||||||
XCTAssertEqual(jsonRequest.contentType, HTTPContentType.json)
|
|
||||||
|
|
||||||
let formRequest = HTTPRequest.postForm(baseURL, parameters: ["test": "value"])
|
|
||||||
XCTAssertEqual(formRequest.contentType, HTTPContentType.formEncoded)
|
|
||||||
|
|
||||||
let multipartRequest = HTTPRequest.postMultipart(baseURL, parts: [])
|
|
||||||
XCTAssertEqual(multipartRequest.contentType, HTTPContentType.multipart)
|
|
||||||
}
|
|
||||||
|
|
||||||
func testFileStreamingConveniences() {
|
|
||||||
let fileURL = URL(fileURLWithPath: "/tmp/test.txt")
|
|
||||||
|
|
||||||
let postRequest = HTTPRequest.postFile(baseURL, fileURL: fileURL)
|
|
||||||
XCTAssertEqual(postRequest.method, HTTPMethod.post)
|
|
||||||
XCTAssertEqual(postRequest.contentType, HTTPContentType.none)
|
|
||||||
if case .fileData(let url) = postRequest.body {
|
|
||||||
XCTAssertEqual(url, fileURL)
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected fileData body")
|
|
||||||
}
|
|
||||||
|
|
||||||
let putRequest = HTTPRequest.putFile(baseURL, fileURL: fileURL)
|
|
||||||
XCTAssertEqual(putRequest.method, HTTPMethod.put)
|
|
||||||
if case .fileData(let url) = putRequest.body {
|
|
||||||
XCTAssertEqual(url, fileURL)
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected fileData body")
|
|
||||||
}
|
|
||||||
|
|
||||||
let patchRequest = HTTPRequest.patchFile(baseURL, fileURL: fileURL)
|
|
||||||
XCTAssertEqual(patchRequest.method, HTTPMethod.patch)
|
|
||||||
if case .fileData(let url) = patchRequest.body {
|
|
||||||
XCTAssertEqual(url, fileURL)
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected fileData body")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testRawDataConveniences() {
|
|
||||||
let xmlData = "<xml><test>value</test></xml>".data(using: .utf8)!
|
|
||||||
|
|
||||||
let postRequest = HTTPRequest.post(baseURL, data: xmlData, contentType: .xml)
|
|
||||||
XCTAssertEqual(postRequest.method, HTTPMethod.post)
|
|
||||||
XCTAssertEqual(postRequest.contentType, HTTPContentType.custom("application/xml"))
|
|
||||||
if case let .data(data, contentType) = postRequest.body {
|
|
||||||
XCTAssertEqual(data, xmlData)
|
|
||||||
XCTAssertEqual(contentType, .xml)
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected data body")
|
|
||||||
}
|
|
||||||
|
|
||||||
let putRequest = HTTPRequest.put(baseURL, data: xmlData, contentType: .plainText)
|
|
||||||
XCTAssertEqual(putRequest.method, HTTPMethod.put)
|
|
||||||
XCTAssertEqual(putRequest.contentType, HTTPContentType.custom("text/plain"))
|
|
||||||
|
|
||||||
let patchRequest = HTTPRequest.patch(baseURL, data: xmlData, contentType: .xml)
|
|
||||||
XCTAssertEqual(patchRequest.method, HTTPMethod.patch)
|
|
||||||
XCTAssertEqual(patchRequest.contentType, HTTPContentType.custom("application/xml"))
|
|
||||||
}
|
|
||||||
|
|
||||||
func testUTTypeIntegration() {
|
|
||||||
let data = Data("test".utf8)
|
|
||||||
|
|
||||||
// Test common UTTypes
|
|
||||||
let jsonRequest = HTTPRequest.post(baseURL, data: data, contentType: .json)
|
|
||||||
XCTAssertEqual(jsonRequest.contentType, HTTPContentType.custom("application/json"))
|
|
||||||
|
|
||||||
let xmlRequest = HTTPRequest.post(baseURL, data: data, contentType: .xml)
|
|
||||||
XCTAssertEqual(xmlRequest.contentType, HTTPContentType.custom("application/xml"))
|
|
||||||
|
|
||||||
let textRequest = HTTPRequest.post(baseURL, data: data, contentType: .plainText)
|
|
||||||
XCTAssertEqual(textRequest.contentType, HTTPContentType.custom("text/plain"))
|
|
||||||
|
|
||||||
let pngRequest = HTTPRequest.post(baseURL, data: data, contentType: .png)
|
|
||||||
XCTAssertEqual(pngRequest.contentType, HTTPContentType.custom("image/png"))
|
|
||||||
|
|
||||||
// Test custom UTType
|
|
||||||
if let customType = UTType(mimeType: "application/custom") {
|
|
||||||
let customRequest = HTTPRequest.post(baseURL, data: data, contentType: customType)
|
|
||||||
XCTAssertEqual(customRequest.contentType, HTTPContentType.custom("application/custom"))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Deprecated API Tests
|
|
||||||
|
|
||||||
func testDeprecatedPOSTWithContentType() {
|
|
||||||
let params = ["name": "Chali 2na", "email": "chali@example.net"]
|
|
||||||
|
|
||||||
// Test JSON content type
|
|
||||||
let jsonRequest = HTTPRequest.post(baseURL, contentType: .json, parameters: params)
|
|
||||||
XCTAssertEqual(jsonRequest.method, .post)
|
|
||||||
XCTAssertEqual(jsonRequest.contentType, .json)
|
|
||||||
if case .jsonParameters(let bodyParams) = jsonRequest.body {
|
|
||||||
XCTAssertEqual(bodyParams.count, 2)
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected jsonParameters body")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test form encoded content type
|
|
||||||
let formRequest = HTTPRequest.post(baseURL, contentType: .formEncoded, parameters: params)
|
|
||||||
XCTAssertEqual(formRequest.method, .post)
|
|
||||||
XCTAssertEqual(formRequest.contentType, .formEncoded)
|
|
||||||
if case .formParameters(let bodyParams) = formRequest.body {
|
|
||||||
XCTAssertEqual(bodyParams.count, 2)
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected formParameters body")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test with no parameters
|
|
||||||
let emptyRequest = HTTPRequest.post(baseURL, contentType: .json, parameters: nil)
|
|
||||||
XCTAssertTrue(emptyRequest.body.isEmpty)
|
|
||||||
}
|
|
||||||
|
|
||||||
func testDeprecatedPUTWithContentType() {
|
|
||||||
let params = ["status": "active"]
|
|
||||||
|
|
||||||
let request = HTTPRequest.put(baseURL, contentType: .json, parameters: params)
|
|
||||||
XCTAssertEqual(request.method, .put)
|
|
||||||
XCTAssertEqual(request.contentType, .json)
|
XCTAssertEqual(request.contentType, .json)
|
||||||
if case .jsonParameters(let bodyParams) = request.body {
|
|
||||||
XCTAssertEqual(bodyParams.count, 1)
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected jsonParameters body")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testDeprecatedPATCHWithContentType() {
|
request.parts = [.text("test", name: "field")]
|
||||||
let params = ["field": "value"]
|
XCTAssertEqual(request.contentType, .multipart) // Should be automatically changed
|
||||||
|
|
||||||
let request = HTTPRequest.patch(baseURL, contentType: .formEncoded, parameters: params)
|
request.parts = [] // Clear parts
|
||||||
XCTAssertEqual(request.method, .patch)
|
XCTAssertEqual(request.contentType, .multipart) // Should remain multipart
|
||||||
XCTAssertEqual(request.contentType, .formEncoded)
|
|
||||||
if case .formParameters(let bodyParams) = request.body {
|
|
||||||
XCTAssertEqual(bodyParams.count, 1)
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected formParameters body")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testDeprecatedInitializer() {
|
|
||||||
let params = ["key": "value"]
|
|
||||||
|
|
||||||
// Test POST with JSON
|
|
||||||
let postRequest = HTTPRequest(method: .post, url: baseURL, contentType: .json, parameters: params)
|
|
||||||
XCTAssertEqual(postRequest.method, .post)
|
|
||||||
XCTAssertEqual(postRequest.contentType, .json)
|
|
||||||
if case .jsonParameters(let bodyParams) = postRequest.body {
|
|
||||||
XCTAssertEqual(bodyParams.count, 1)
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected jsonParameters body")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test GET with parameters (should use query strings)
|
|
||||||
let getRequest = HTTPRequest(method: .get, url: baseURL, contentType: .none, parameters: params)
|
|
||||||
XCTAssertEqual(getRequest.method, .get)
|
|
||||||
if case .formParameters(let bodyParams) = getRequest.body {
|
|
||||||
XCTAssertEqual(bodyParams.count, 1)
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected formParameters body for query encoding")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test DELETE with parameters (should use query strings)
|
|
||||||
let deleteRequest = HTTPRequest(method: .delete, url: baseURL, contentType: .none, parameters: params)
|
|
||||||
XCTAssertEqual(deleteRequest.method, .delete)
|
|
||||||
if case .formParameters(let bodyParams) = deleteRequest.body {
|
|
||||||
XCTAssertEqual(bodyParams.count, 1)
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected formParameters body for query encoding")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func testDeprecatedParametersProperty() {
|
|
||||||
let params = ["test": "value", "number": 42] as [String: any Sendable]
|
|
||||||
|
|
||||||
// Test reading parameters from JSON body
|
|
||||||
let jsonRequest = HTTPRequest.postJSON(baseURL, body: params)
|
|
||||||
XCTAssertEqual(jsonRequest.parameters?.count, 2)
|
|
||||||
|
|
||||||
// Test reading parameters from form body
|
|
||||||
let formRequest = HTTPRequest.postForm(baseURL, parameters: params)
|
|
||||||
XCTAssertEqual(formRequest.parameters?.count, 2)
|
|
||||||
|
|
||||||
// Test setting parameters
|
|
||||||
var request = HTTPRequest.post(baseURL)
|
|
||||||
request.parameters = params
|
|
||||||
XCTAssertEqual(request.parameters?.count, 2)
|
|
||||||
if case .formParameters = request.body {
|
|
||||||
// Good, defaults to form parameters
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected formParameters body")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Test setting nil parameters
|
|
||||||
request.parameters = nil
|
|
||||||
XCTAssertNil(request.parameters)
|
|
||||||
XCTAssertTrue(request.body.isEmpty)
|
|
||||||
}
|
|
||||||
|
|
||||||
func testDeprecatedPartsProperty() {
|
|
||||||
let parts = [
|
|
||||||
MultipartFormEncoder.Part.text("value", name: "field"),
|
|
||||||
MultipartFormEncoder.Part.data(Data("test".utf8), name: "file", type: "text/plain", filename: "test.txt")
|
|
||||||
]
|
|
||||||
|
|
||||||
// Test reading parts
|
|
||||||
let multipartRequest = HTTPRequest.postMultipart(baseURL, parts: parts)
|
|
||||||
XCTAssertEqual(multipartRequest.parts.count, 2)
|
|
||||||
|
|
||||||
// Test setting parts
|
|
||||||
var request = HTTPRequest.post(baseURL)
|
|
||||||
request.parts = parts
|
|
||||||
XCTAssertEqual(request.parts.count, 2)
|
|
||||||
XCTAssertEqual(request.contentType, .multipart)
|
|
||||||
|
|
||||||
// Test empty parts
|
|
||||||
request.parts = []
|
|
||||||
XCTAssertEqual(request.parts.count, 0)
|
|
||||||
if case .multipart(let bodyParts) = request.body {
|
|
||||||
XCTAssertTrue(bodyParts.isEmpty)
|
|
||||||
} else {
|
|
||||||
XCTFail("Expected multipart body")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,309 +0,0 @@
|
||||||
//
|
|
||||||
// Created by Sami Samhuri on 2025-06-23.
|
|
||||||
// Copyright © 2025 Sami Samhuri. All rights reserved.
|
|
||||||
// Released under the terms of the MIT license.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
@testable import Osiris
|
|
||||||
|
|
||||||
func httpRequestWithCodableSupport() async throws {
|
|
||||||
let url = URL(string: "https://trails.example.net/riders")!
|
|
||||||
|
|
||||||
// GET request with automatic JSON decoding
|
|
||||||
let riders: [RiderProfile] = try await URLSession.shared.perform(.get(url))
|
|
||||||
|
|
||||||
// POST with Codable body and automatic response decoding
|
|
||||||
struct CreateRiderRequest: Codable {
|
|
||||||
let name: String
|
|
||||||
let email: String
|
|
||||||
let bike: String
|
|
||||||
}
|
|
||||||
|
|
||||||
let danny = CreateRiderRequest(name: "Danny MacAskill", email: "danny@trails.example.net", bike: "Santa Cruz 5010")
|
|
||||||
let created: RiderProfile = try await URLSession.shared.perform(.post(url, body: danny))
|
|
||||||
|
|
||||||
// Custom encoder/decoder
|
|
||||||
let encoder = JSONEncoder()
|
|
||||||
encoder.keyEncodingStrategy = .convertToSnakeCase
|
|
||||||
let customRequest = try HTTPRequest.post(url, body: danny, encoder: encoder)
|
|
||||||
|
|
||||||
let decoder = JSONDecoder()
|
|
||||||
decoder.keyDecodingStrategy = .convertFromSnakeCase
|
|
||||||
let createdAgain: RiderProfile = try await URLSession.shared.perform(customRequest, decoder: decoder)
|
|
||||||
|
|
||||||
// For requests expecting no content (204, etc.)
|
|
||||||
try await URLSession.shared.perform(.delete(url.appendingPathComponent("123")))
|
|
||||||
|
|
||||||
_ = riders
|
|
||||||
_ = created
|
|
||||||
_ = createdAgain
|
|
||||||
}
|
|
||||||
|
|
||||||
func basicHTTPRequest() throws {
|
|
||||||
let url = URL(string: "https://example.net/kittens")!
|
|
||||||
|
|
||||||
// Basic GET request
|
|
||||||
let request = HTTPRequest.get(url)
|
|
||||||
|
|
||||||
// GET request with query parameters
|
|
||||||
let getRequest = HTTPRequest.get(url, parameters: ["page": 1, "limit": 10])
|
|
||||||
|
|
||||||
// DELETE request with query parameters
|
|
||||||
let deleteRequest = HTTPRequest.delete(url, parameters: ["confirm": "true"])
|
|
||||||
|
|
||||||
_ = request
|
|
||||||
_ = getRequest
|
|
||||||
_ = deleteRequest
|
|
||||||
}
|
|
||||||
|
|
||||||
func moreComplicatedPOSTRequest() throws {
|
|
||||||
let url = URL(string: "https://example.net/band")!
|
|
||||||
let params = ["email": "fatmike@example.net", "password": "LinoleumSupportsMyHead"]
|
|
||||||
|
|
||||||
// POST with JSON body
|
|
||||||
let jsonRequest = HTTPRequest.postJSON(url, body: params)
|
|
||||||
|
|
||||||
// POST with form-encoded body
|
|
||||||
let formRequest = HTTPRequest.postForm(url, parameters: params)
|
|
||||||
|
|
||||||
// POST with multipart body
|
|
||||||
let multipartRequest = HTTPRequest.postMultipart(url, parts: [.text("all day", name: "album")])
|
|
||||||
|
|
||||||
_ = jsonRequest
|
|
||||||
_ = formRequest
|
|
||||||
_ = multipartRequest
|
|
||||||
}
|
|
||||||
|
|
||||||
func requestBuilderExample() throws {
|
|
||||||
let url = URL(string: "https://example.net/band")!
|
|
||||||
let params = ["email": "fatmike@example.net", "password": "LinoleumSupportsMyHead"]
|
|
||||||
let request = HTTPRequest.postJSON(url, body: params)
|
|
||||||
let urlRequest = try RequestBuilder.build(request: request)
|
|
||||||
_ = urlRequest
|
|
||||||
}
|
|
||||||
|
|
||||||
func moreCodableExamples() throws {
|
|
||||||
struct Artist: Codable {
|
|
||||||
let name: String
|
|
||||||
let email: String
|
|
||||||
let genre: String
|
|
||||||
}
|
|
||||||
|
|
||||||
let url = URL(string: "https://beats.example.net/artists")!
|
|
||||||
let artist = Artist(name: "Trent Reznor", email: "trent@example.net", genre: "Industrial")
|
|
||||||
|
|
||||||
// POST with Codable body
|
|
||||||
let postRequest = try HTTPRequest.post(url, body: artist)
|
|
||||||
|
|
||||||
// PUT with Codable body
|
|
||||||
let putRequest = try HTTPRequest.put(url, body: artist)
|
|
||||||
|
|
||||||
// PATCH with Codable body
|
|
||||||
let patchRequest = try HTTPRequest.patch(url, body: artist)
|
|
||||||
|
|
||||||
// Custom encoder for different JSON formatting
|
|
||||||
let encoder = JSONEncoder()
|
|
||||||
encoder.keyEncodingStrategy = .convertToSnakeCase
|
|
||||||
let customRequest = try HTTPRequest.post(url, body: artist, encoder: encoder)
|
|
||||||
|
|
||||||
_ = postRequest
|
|
||||||
_ = putRequest
|
|
||||||
_ = patchRequest
|
|
||||||
_ = customRequest
|
|
||||||
}
|
|
||||||
|
|
||||||
func formEncoderExample() {
|
|
||||||
let body = FormEncoder.encode(["email": "trent@example.net", "password": "CloserToGod"])
|
|
||||||
_ = body
|
|
||||||
}
|
|
||||||
|
|
||||||
func multipartFormExample() throws {
|
|
||||||
let avatarData = Data("fake image data".utf8) // Simplified for compilation
|
|
||||||
let encoder = MultipartFormEncoder()
|
|
||||||
let body = try encoder.encodeData(parts: [
|
|
||||||
.text("chali@example.net", name: "email"),
|
|
||||||
.text("QualityControl", name: "password"),
|
|
||||||
.data(avatarData, name: "avatar", type: "image/jpeg", filename: "avatar.jpg"),
|
|
||||||
])
|
|
||||||
_ = body
|
|
||||||
}
|
|
||||||
|
|
||||||
func completeExample() async throws {
|
|
||||||
struct ArtistProfile: Codable {
|
|
||||||
let name: String
|
|
||||||
let email: String
|
|
||||||
let genre: String
|
|
||||||
}
|
|
||||||
|
|
||||||
struct UpdateProfileRequest: Codable {
|
|
||||||
let name: String
|
|
||||||
let email: String
|
|
||||||
let genre: String
|
|
||||||
}
|
|
||||||
|
|
||||||
func updateProfile(name: String, email: String, genre: String) async throws -> ArtistProfile {
|
|
||||||
let url = URL(string: "https://beats.example.net/profile")!
|
|
||||||
let updateRequest = UpdateProfileRequest(name: name, email: email, genre: genre)
|
|
||||||
|
|
||||||
// Use Codable body instead of dictionary
|
|
||||||
let request = try HTTPRequest.put(url, body: updateRequest)
|
|
||||||
|
|
||||||
// URLSession extension handles status checking and JSON decoding
|
|
||||||
return try await URLSession.shared.perform(request)
|
|
||||||
}
|
|
||||||
|
|
||||||
// For varied data structures, dictionaries are still available as an escape hatch:
|
|
||||||
func updateProfileWithDictionary(fields: [String: String]) async throws -> ArtistProfile {
|
|
||||||
let url = URL(string: "https://beats.example.net/profile")!
|
|
||||||
let request = HTTPRequest.putJSON(url, body: fields)
|
|
||||||
return try await URLSession.shared.perform(request)
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = updateProfile
|
|
||||||
_ = updateProfileWithDictionary
|
|
||||||
}
|
|
||||||
|
|
||||||
func httpResponseExample() throws {
|
|
||||||
let url = URL(string: "https://example.net/test")!
|
|
||||||
let urlRequest = URLRequest(url: url)
|
|
||||||
|
|
||||||
let task = URLSession.shared.dataTask(with: urlRequest) { data, response, error in
|
|
||||||
let httpResponse = HTTPResponse(response: response, data: data, error: error)
|
|
||||||
|
|
||||||
switch httpResponse {
|
|
||||||
case let .success(httpURLResponse, data):
|
|
||||||
print("Success: \(httpURLResponse.statusCode)")
|
|
||||||
if let data = data {
|
|
||||||
print("Response: \(String(data: data, encoding: .utf8) ?? "")")
|
|
||||||
}
|
|
||||||
case let .failure(error, httpURLResponse, _):
|
|
||||||
print("Failed: \(error)")
|
|
||||||
if let httpURLResponse = httpURLResponse {
|
|
||||||
print("Status: \(httpURLResponse.statusCode)")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ = task
|
|
||||||
}
|
|
||||||
|
|
||||||
func multipartFileStreamingExample() throws {
|
|
||||||
let encoder = MultipartFormEncoder()
|
|
||||||
let avatarData = Data("fake image data".utf8)
|
|
||||||
|
|
||||||
let body = try encoder.encodeFile(parts: [
|
|
||||||
.text("chali@example.net", name: "email"),
|
|
||||||
.text("QualityControl", name: "password"),
|
|
||||||
.data(avatarData, name: "avatar", type: "image/jpeg", filename: "avatar.jpg"),
|
|
||||||
])
|
|
||||||
defer { _ = body.cleanup() }
|
|
||||||
|
|
||||||
var request = URLRequest(url: URL(string: "https://example.net/accounts")!)
|
|
||||||
request.httpMethod = "POST"
|
|
||||||
request.httpBodyStream = InputStream(url: body.url)
|
|
||||||
request.addValue(body.contentType, forHTTPHeaderField: "Content-Type")
|
|
||||||
request.addValue("\(body.contentLength)", forHTTPHeaderField: "Content-Length")
|
|
||||||
|
|
||||||
_ = request
|
|
||||||
}
|
|
||||||
|
|
||||||
func errorHandlingExample() throws {
|
|
||||||
func handleErrors() async {
|
|
||||||
do {
|
|
||||||
let url = URL(string: "https://example.net/test")!
|
|
||||||
let request = HTTPRequest.get(url)
|
|
||||||
let response: [String] = try await URLSession.shared.perform(request)
|
|
||||||
|
|
||||||
_ = response
|
|
||||||
} catch let httpError as HTTPError {
|
|
||||||
switch httpError {
|
|
||||||
case let .failure(statusCode, data, _):
|
|
||||||
print("HTTP \(statusCode) error: \(String(data: data, encoding: .utf8) ?? "No body")")
|
|
||||||
case .invalidResponse:
|
|
||||||
print("Invalid response from server")
|
|
||||||
}
|
|
||||||
} catch is DecodingError {
|
|
||||||
print("Failed to decode response JSON")
|
|
||||||
} catch {
|
|
||||||
print("Network error: \(error)")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
_ = handleErrors
|
|
||||||
}
|
|
||||||
|
|
||||||
func migrationGuideExamples() throws {
|
|
||||||
let url = URL(string: "https://example.net/test")!
|
|
||||||
|
|
||||||
// Explicit methods for different encodings
|
|
||||||
let jsonRequest = HTTPRequest.postJSON(url, body: ["key": "value"])
|
|
||||||
let formRequest = HTTPRequest.putForm(url, parameters: ["key": "value"])
|
|
||||||
|
|
||||||
// Multipart convenience methods
|
|
||||||
let multipartRequest = HTTPRequest.postMultipart(url, parts: [.text("value", name: "field")])
|
|
||||||
|
|
||||||
// Codable support
|
|
||||||
struct Artist: Codable {
|
|
||||||
let name: String
|
|
||||||
let genre: String
|
|
||||||
}
|
|
||||||
let codableRequest = try HTTPRequest.post(url, body: Artist(name: "Trent Reznor", genre: "Industrial"))
|
|
||||||
|
|
||||||
_ = jsonRequest
|
|
||||||
_ = formRequest
|
|
||||||
_ = multipartRequest
|
|
||||||
_ = codableRequest
|
|
||||||
}
|
|
||||||
|
|
||||||
func additionalHTTPRequestExamples() throws {
|
|
||||||
// Examples from HTTPRequest documentation
|
|
||||||
|
|
||||||
// GET request with query parameters
|
|
||||||
let getRequest = HTTPRequest.get(
|
|
||||||
URL(string: "https://api.example.net/users")!,
|
|
||||||
parameters: ["page": "1", "limit": "10"]
|
|
||||||
)
|
|
||||||
|
|
||||||
// POST with JSON body
|
|
||||||
let jsonRequest = HTTPRequest.postJSON(
|
|
||||||
URL(string: "https://api.example.net/users")!,
|
|
||||||
body: ["name": "Chali 2na", "email": "chali@example.net"]
|
|
||||||
)
|
|
||||||
|
|
||||||
// DELETE with query parameters
|
|
||||||
let deleteRequest = HTTPRequest.delete(
|
|
||||||
URL(string: "https://api.example.net/users/123")!,
|
|
||||||
parameters: ["confirm": "true"]
|
|
||||||
)
|
|
||||||
|
|
||||||
// Multipart form with file upload
|
|
||||||
let uploadURL = URL(string: "https://api.example.net/upload")!
|
|
||||||
let imageData = Data("fake image".utf8)
|
|
||||||
let multipartRequest = HTTPRequest.postMultipart(uploadURL, parts: [
|
|
||||||
.text("Trent Reznor", name: "name"),
|
|
||||||
.data(imageData, name: "avatar", type: "image/jpeg", filename: "avatar.jpg")
|
|
||||||
])
|
|
||||||
|
|
||||||
// File streaming for large request bodies
|
|
||||||
let tempFile = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("test.txt")
|
|
||||||
try "test content".write(to: tempFile, atomically: true, encoding: .utf8)
|
|
||||||
let fileRequest = HTTPRequest.postFile(
|
|
||||||
URL(string: "https://api.example.net/upload")!,
|
|
||||||
fileURL: tempFile
|
|
||||||
)
|
|
||||||
|
|
||||||
// Custom content types like XML
|
|
||||||
let xmlData = "<request><artist>Nine Inch Nails</artist></request>".data(using: .utf8)!
|
|
||||||
let xmlRequest = HTTPRequest.post(
|
|
||||||
URL(string: "https://api.example.net/music")!,
|
|
||||||
data: xmlData,
|
|
||||||
contentType: .xml
|
|
||||||
)
|
|
||||||
|
|
||||||
_ = getRequest
|
|
||||||
_ = jsonRequest
|
|
||||||
_ = deleteRequest
|
|
||||||
_ = multipartRequest
|
|
||||||
_ = fileRequest
|
|
||||||
_ = xmlRequest
|
|
||||||
}
|
|
||||||
|
|
@ -9,7 +9,7 @@
|
||||||
import XCTest
|
import XCTest
|
||||||
|
|
||||||
class RequestBuilderTests: XCTestCase {
|
class RequestBuilderTests: XCTestCase {
|
||||||
let baseURL = URL(string: "https://api.example.net/riders")!
|
let baseURL = URL(string: "https://api.example.net/users")!
|
||||||
|
|
||||||
func testBuildBasicGETRequest() throws {
|
func testBuildBasicGETRequest() throws {
|
||||||
let httpRequest = HTTPRequest.get(baseURL)
|
let httpRequest = HTTPRequest.get(baseURL)
|
||||||
|
|
@ -41,7 +41,7 @@ class RequestBuilderTests: XCTestCase {
|
||||||
|
|
||||||
func testBuildJSONRequest() throws {
|
func testBuildJSONRequest() throws {
|
||||||
let parameters = ["name": "Jane", "age": 30] as [String: any Sendable]
|
let parameters = ["name": "Jane", "age": 30] as [String: any Sendable]
|
||||||
let httpRequest = HTTPRequest.postJSON(baseURL, body: parameters)
|
let httpRequest = HTTPRequest.post(baseURL, contentType: .json, parameters: parameters)
|
||||||
|
|
||||||
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
||||||
|
|
||||||
|
|
@ -57,7 +57,7 @@ class RequestBuilderTests: XCTestCase {
|
||||||
|
|
||||||
func testBuildFormEncodedRequest() throws {
|
func testBuildFormEncodedRequest() throws {
|
||||||
let parameters = ["email": "john@example.net", "password": "TaylorSwift1989"]
|
let parameters = ["email": "john@example.net", "password": "TaylorSwift1989"]
|
||||||
let httpRequest = HTTPRequest.postForm(baseURL, parameters: parameters)
|
let httpRequest = HTTPRequest.post(baseURL, contentType: .formEncoded, parameters: parameters)
|
||||||
|
|
||||||
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
||||||
|
|
||||||
|
|
@ -73,11 +73,11 @@ class RequestBuilderTests: XCTestCase {
|
||||||
// This is by design - developers should specify an appropriate content type
|
// This is by design - developers should specify an appropriate content type
|
||||||
|
|
||||||
func testBuildMultipartRequest() throws {
|
func testBuildMultipartRequest() throws {
|
||||||
let parts = [
|
var httpRequest = HTTPRequest.post(baseURL)
|
||||||
MultipartFormEncoder.Part.text("Jane Doe", name: "name"),
|
httpRequest.parts = [
|
||||||
MultipartFormEncoder.Part.data(Data("test".utf8), name: "file", type: "text/plain", filename: "test.txt")
|
.text("Jane Doe", name: "name"),
|
||||||
|
.data(Data("test".utf8), name: "file", type: "text/plain", filename: "test.txt")
|
||||||
]
|
]
|
||||||
let httpRequest = HTTPRequest.postMultipart(baseURL, parts: parts)
|
|
||||||
|
|
||||||
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
||||||
|
|
||||||
|
|
@ -100,14 +100,14 @@ class RequestBuilderTests: XCTestCase {
|
||||||
// Since FormEncoder is quite robust and UTF-8 encoding rarely fails,
|
// Since FormEncoder is quite robust and UTF-8 encoding rarely fails,
|
||||||
// we'll test this by creating a subclass that can force the failure
|
// we'll test this by creating a subclass that can force the failure
|
||||||
// But for now, we'll document this edge case exists
|
// But for now, we'll document this edge case exists
|
||||||
XCTAssertNoThrow(try RequestBuilder.build(request: HTTPRequest.postForm(baseURL, parameters: ["test": "value"])))
|
XCTAssertNoThrow(try RequestBuilder.build(request: HTTPRequest.post(baseURL, contentType: .formEncoded, parameters: ["test": "value"])))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testBuildRequestWithAllHTTPMethods() throws {
|
func testBuildRequestWithAllHTTPMethods() throws {
|
||||||
let methods: [HTTPMethod] = [.get, .post, .put, .patch, .delete]
|
let methods: [HTTPMethod] = [.get, .post, .put, .patch, .delete]
|
||||||
|
|
||||||
for method in methods {
|
for method in methods {
|
||||||
let httpRequest = try HTTPRequest(method: method, url: baseURL)
|
let httpRequest = HTTPRequest(method: method, url: baseURL)
|
||||||
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
||||||
|
|
||||||
XCTAssertEqual(urlRequest.httpMethod, method.string)
|
XCTAssertEqual(urlRequest.httpMethod, method.string)
|
||||||
|
|
@ -115,7 +115,7 @@ class RequestBuilderTests: XCTestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
func testBuildRequestPreservesURL() throws {
|
func testBuildRequestPreservesURL() throws {
|
||||||
let complexURL = URL(string: "https://api.example.net/riders?page=1#section")!
|
let complexURL = URL(string: "https://api.example.net/users?page=1#section")!
|
||||||
let httpRequest = HTTPRequest.get(complexURL)
|
let httpRequest = HTTPRequest.get(complexURL)
|
||||||
|
|
||||||
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
||||||
|
|
@ -133,7 +133,9 @@ class RequestBuilderTests: XCTestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
func testBuildRequestWithEmptyMultipartParts() throws {
|
func testBuildRequestWithEmptyMultipartParts() throws {
|
||||||
let httpRequest = HTTPRequest.postMultipart(baseURL, parts: [])
|
var httpRequest = HTTPRequest.post(baseURL)
|
||||||
|
httpRequest.parts = []
|
||||||
|
httpRequest.contentType = .multipart // Explicitly set to multipart
|
||||||
|
|
||||||
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
||||||
|
|
||||||
|
|
@ -143,11 +145,11 @@ class RequestBuilderTests: XCTestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
func testBuildRequestWithLargeMultipartData() throws {
|
func testBuildRequestWithLargeMultipartData() throws {
|
||||||
|
var httpRequest = HTTPRequest.post(baseURL)
|
||||||
let largeData = Data(repeating: 65, count: 1024 * 1024) // 1MB of 'A' characters
|
let largeData = Data(repeating: 65, count: 1024 * 1024) // 1MB of 'A' characters
|
||||||
let parts = [
|
httpRequest.parts = [
|
||||||
MultipartFormEncoder.Part.data(largeData, name: "largefile", type: "application/octet-stream", filename: "large.bin")
|
.data(largeData, name: "largefile", type: "application/octet-stream", filename: "large.bin")
|
||||||
]
|
]
|
||||||
let httpRequest = HTTPRequest.postMultipart(baseURL, parts: parts)
|
|
||||||
|
|
||||||
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
||||||
|
|
||||||
|
|
@ -171,7 +173,7 @@ class RequestBuilderTests: XCTestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
func testBuildRequestWithNilParameters() throws {
|
func testBuildRequestWithNilParameters() throws {
|
||||||
let httpRequest = HTTPRequest.post(baseURL)
|
let httpRequest = HTTPRequest.post(baseURL, contentType: .json, parameters: nil)
|
||||||
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
||||||
|
|
||||||
// RequestBuilder may not set Content-Type if there are no parameters to encode
|
// RequestBuilder may not set Content-Type if there are no parameters to encode
|
||||||
|
|
@ -179,7 +181,7 @@ class RequestBuilderTests: XCTestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
func testBuildRequestWithEmptyParameters() throws {
|
func testBuildRequestWithEmptyParameters() throws {
|
||||||
let httpRequest = HTTPRequest.postJSON(baseURL, body: [:])
|
let httpRequest = HTTPRequest.post(baseURL, contentType: .json, parameters: [:])
|
||||||
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
||||||
|
|
||||||
XCTAssertEqual(urlRequest.value(forHTTPHeaderField: "Content-Type"), "application/json")
|
XCTAssertEqual(urlRequest.value(forHTTPHeaderField: "Content-Type"), "application/json")
|
||||||
|
|
@ -190,7 +192,7 @@ class RequestBuilderTests: XCTestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
func testBuildRequestSetsContentType() throws {
|
func testBuildRequestSetsContentType() throws {
|
||||||
let httpRequest = HTTPRequest.postJSON(baseURL, body: ["test": "value"])
|
let httpRequest = HTTPRequest.post(baseURL, contentType: .json, parameters: ["test": "value"])
|
||||||
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
||||||
|
|
||||||
// RequestBuilder should set the correct content type when there are parameters to encode
|
// RequestBuilder should set the correct content type when there are parameters to encode
|
||||||
|
|
@ -210,7 +212,7 @@ class RequestBuilderTests: XCTestCase {
|
||||||
] as [String: any Sendable]
|
] as [String: any Sendable]
|
||||||
]
|
]
|
||||||
|
|
||||||
let httpRequest = HTTPRequest.postJSON(baseURL, body: complexParams)
|
let httpRequest = HTTPRequest.post(baseURL, contentType: .json, parameters: complexParams)
|
||||||
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
||||||
|
|
||||||
XCTAssertNotNil(urlRequest.httpBody)
|
XCTAssertNotNil(urlRequest.httpBody)
|
||||||
|
|
@ -220,21 +222,22 @@ class RequestBuilderTests: XCTestCase {
|
||||||
XCTAssertEqual(person["age"] as? Int, 69)
|
XCTAssertEqual(person["age"] as? Int, 69)
|
||||||
}
|
}
|
||||||
|
|
||||||
func testBuildRequestWithExplicitFormEncoding() throws {
|
func testBuildRequestWithNoneContentTypeFallsBackToFormEncoding() throws {
|
||||||
// Test explicit form encoding
|
// Test the .none content type fallthrough case with a warning
|
||||||
let httpRequest = HTTPRequest.postForm(baseURL, parameters: ["email": "freddie@example.net", "band": "Queen"])
|
let httpRequest = HTTPRequest.post(baseURL, contentType: .none, parameters: ["email": "freddie@example.net", "band": "Queen"])
|
||||||
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
||||||
|
|
||||||
|
// Should fall back to form encoding and log a warning
|
||||||
XCTAssertEqual(urlRequest.value(forHTTPHeaderField: "Content-Type"), "application/x-www-form-urlencoded")
|
XCTAssertEqual(urlRequest.value(forHTTPHeaderField: "Content-Type"), "application/x-www-form-urlencoded")
|
||||||
XCTAssertNotNil(urlRequest.httpBody)
|
XCTAssertNotNil(urlRequest.httpBody)
|
||||||
|
|
||||||
let bodyString = String(bytes: urlRequest.httpBody!, encoding: .utf8)
|
let bodyString = String(data: urlRequest.httpBody!, encoding: .utf8)!
|
||||||
XCTAssertTrue(bodyString?.contains("email=freddie%40example.net") ?? false)
|
XCTAssertTrue(bodyString.contains("email=freddie%40example.net"))
|
||||||
XCTAssertTrue(bodyString?.contains("band=Queen") ?? false)
|
XCTAssertTrue(bodyString.contains("band=Queen"))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testBuildGETRequestWithQueryParameters() throws {
|
func testBuildGETRequestWithQueryParameters() throws {
|
||||||
let httpRequest = HTTPRequest.get(baseURL, parameters: ["name": "Neko Case", "email": "neko@example.net"])
|
let httpRequest = HTTPRequest.get(baseURL, parameters: ["name": "John Doe", "email": "john@example.net"])
|
||||||
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
||||||
|
|
||||||
XCTAssertEqual(urlRequest.httpMethod, "GET")
|
XCTAssertEqual(urlRequest.httpMethod, "GET")
|
||||||
|
|
@ -242,8 +245,8 @@ class RequestBuilderTests: XCTestCase {
|
||||||
XCTAssertNil(urlRequest.value(forHTTPHeaderField: "Content-Type"))
|
XCTAssertNil(urlRequest.value(forHTTPHeaderField: "Content-Type"))
|
||||||
|
|
||||||
let urlString = urlRequest.url?.absoluteString ?? ""
|
let urlString = urlRequest.url?.absoluteString ?? ""
|
||||||
XCTAssertTrue(urlString.contains("name=Neko%20Case"), "URL should contain encoded name parameter")
|
XCTAssertTrue(urlString.contains("name=John%20Doe"), "URL should contain encoded name parameter")
|
||||||
XCTAssertTrue(urlString.contains("email=neko@example.net"), "URL should contain email parameter")
|
XCTAssertTrue(urlString.contains("email=john@example.net"), "URL should contain email parameter")
|
||||||
XCTAssertTrue(urlString.contains("?"), "URL should contain query separator")
|
XCTAssertTrue(urlString.contains("?"), "URL should contain query separator")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -262,7 +265,7 @@ class RequestBuilderTests: XCTestCase {
|
||||||
}
|
}
|
||||||
|
|
||||||
func testBuildGETRequestWithExistingQueryString() throws {
|
func testBuildGETRequestWithExistingQueryString() throws {
|
||||||
let urlWithQuery = URL(string: "https://api.example.net/riders?existing=param")!
|
let urlWithQuery = URL(string: "https://api.example.net/users?existing=param")!
|
||||||
let httpRequest = HTTPRequest.get(urlWithQuery, parameters: ["new": "value"])
|
let httpRequest = HTTPRequest.get(urlWithQuery, parameters: ["new": "value"])
|
||||||
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
||||||
|
|
||||||
|
|
@ -272,22 +275,22 @@ class RequestBuilderTests: XCTestCase {
|
||||||
XCTAssertTrue(urlString.contains("&"))
|
XCTAssertTrue(urlString.contains("&"))
|
||||||
}
|
}
|
||||||
|
|
||||||
func testBuildGETRequestWithFormParameters() throws {
|
func testBuildGETRequestWithMultipartThrowsError() throws {
|
||||||
let httpRequest = HTTPRequest.get(baseURL, parameters: ["name": "value"])
|
var httpRequest = HTTPRequest.get(baseURL, parameters: ["name": "value"])
|
||||||
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
httpRequest.contentType = HTTPContentType.multipart
|
||||||
|
|
||||||
// GET parameters should be encoded as query string
|
XCTAssertThrowsError(try RequestBuilder.build(request: httpRequest)) { error in
|
||||||
XCTAssertTrue(urlRequest.url?.query?.contains("name=value") ?? false)
|
XCTAssertTrue(error is RequestBuilderError)
|
||||||
XCTAssertNil(urlRequest.httpBody)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func testBuildDELETERequestWithParameters() throws {
|
func testBuildDELETERequestWithPartsThrowsError() throws {
|
||||||
let httpRequest = HTTPRequest.delete(baseURL, parameters: ["id": "123"])
|
var httpRequest = HTTPRequest.delete(baseURL, parameters: ["id": "123"])
|
||||||
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
httpRequest.parts = [MultipartFormEncoder.Part.text("value", name: "test")]
|
||||||
|
|
||||||
// DELETE parameters should be encoded as query string
|
XCTAssertThrowsError(try RequestBuilder.build(request: httpRequest)) { error in
|
||||||
XCTAssertTrue(urlRequest.url?.query?.contains("id=123") ?? false)
|
XCTAssertTrue(error is RequestBuilderError)
|
||||||
XCTAssertNil(urlRequest.httpBody)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func testBuildGETRequestWithEmptyParametersDoesNotIncludeQueryString() throws {
|
func testBuildGETRequestWithEmptyParametersDoesNotIncludeQueryString() throws {
|
||||||
|
|
@ -303,55 +306,4 @@ class RequestBuilderTests: XCTestCase {
|
||||||
XCTAssertFalse(urlString.contains("?"), "URL should not contain question mark when parameters are empty")
|
XCTAssertFalse(urlString.contains("?"), "URL should not contain question mark when parameters are empty")
|
||||||
}
|
}
|
||||||
|
|
||||||
func testBuildRequestWithFileData() throws {
|
|
||||||
// Create a temporary file for testing
|
|
||||||
let tempDir = FileManager.default.temporaryDirectory
|
|
||||||
let testFileURL = tempDir.appendingPathComponent("test_file.txt")
|
|
||||||
let testContent = "This is test file content for streaming"
|
|
||||||
try testContent.write(to: testFileURL, atomically: true, encoding: .utf8)
|
|
||||||
|
|
||||||
defer {
|
|
||||||
try? FileManager.default.removeItem(at: testFileURL)
|
|
||||||
}
|
|
||||||
|
|
||||||
let httpRequest = HTTPRequest.postFile(baseURL, fileURL: testFileURL)
|
|
||||||
let urlRequest = try RequestBuilder.build(request: httpRequest)
|
|
||||||
|
|
||||||
XCTAssertEqual(urlRequest.httpMethod, "POST")
|
|
||||||
XCTAssertNotNil(urlRequest.httpBodyStream)
|
|
||||||
XCTAssertNil(urlRequest.httpBody) // Should use stream, not body
|
|
||||||
|
|
||||||
// Should set Content-Length if file size is available
|
|
||||||
let contentLength = urlRequest.value(forHTTPHeaderField: "Content-Length")
|
|
||||||
XCTAssertNotNil(contentLength)
|
|
||||||
XCTAssertEqual(Int(contentLength!), testContent.utf8.count)
|
|
||||||
|
|
||||||
// Should set Content-Type based on file extension
|
|
||||||
let contentType = urlRequest.value(forHTTPHeaderField: "Content-Type")
|
|
||||||
XCTAssertEqual(contentType, "text/plain")
|
|
||||||
}
|
|
||||||
|
|
||||||
func testBuildRequestWithFileDataSetsCorrectContentType() throws {
|
|
||||||
let tempDir = FileManager.default.temporaryDirectory
|
|
||||||
|
|
||||||
// Test JSON file
|
|
||||||
let jsonFileURL = tempDir.appendingPathComponent("test.json")
|
|
||||||
try "{}".write(to: jsonFileURL, atomically: true, encoding: .utf8)
|
|
||||||
defer { try? FileManager.default.removeItem(at: jsonFileURL) }
|
|
||||||
|
|
||||||
let jsonRequest = HTTPRequest.postFile(baseURL, fileURL: jsonFileURL)
|
|
||||||
let jsonURLRequest = try RequestBuilder.build(request: jsonRequest)
|
|
||||||
|
|
||||||
XCTAssertEqual(jsonURLRequest.value(forHTTPHeaderField: "Content-Type"), "application/json")
|
|
||||||
|
|
||||||
// Test PNG file
|
|
||||||
let pngFileURL = tempDir.appendingPathComponent("test.png")
|
|
||||||
try Data().write(to: pngFileURL)
|
|
||||||
defer { try? FileManager.default.removeItem(at: pngFileURL) }
|
|
||||||
|
|
||||||
let pngRequest = HTTPRequest.putFile(baseURL, fileURL: pngFileURL)
|
|
||||||
let pngURLRequest = try RequestBuilder.build(request: pngRequest)
|
|
||||||
|
|
||||||
XCTAssertEqual(pngURLRequest.value(forHTTPHeaderField: "Content-Type"), "image/png")
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,48 +0,0 @@
|
||||||
//
|
|
||||||
// Created by Sami Samhuri on 2025-06-23.
|
|
||||||
// Copyright © 2025 Sami Samhuri. All rights reserved.
|
|
||||||
// Released under the terms of the MIT license.
|
|
||||||
//
|
|
||||||
|
|
||||||
import Foundation
|
|
||||||
|
|
||||||
// MARK: - Rider Models
|
|
||||||
|
|
||||||
struct RiderProfile: Codable, Equatable {
|
|
||||||
let id: Int
|
|
||||||
let name: String
|
|
||||||
let email: String
|
|
||||||
let bike: String
|
|
||||||
}
|
|
||||||
|
|
||||||
struct CreateRiderRequest: Codable {
|
|
||||||
let name: String
|
|
||||||
let email: String
|
|
||||||
let bike: String
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Artist Models
|
|
||||||
|
|
||||||
struct ArtistProfile: Codable {
|
|
||||||
let name: String
|
|
||||||
let email: String
|
|
||||||
let genre: String
|
|
||||||
}
|
|
||||||
|
|
||||||
struct UpdateProfileRequest: Codable {
|
|
||||||
let name: String
|
|
||||||
let email: String
|
|
||||||
let genre: String
|
|
||||||
}
|
|
||||||
|
|
||||||
// MARK: - Generic Test Models
|
|
||||||
|
|
||||||
struct TestResponse: Codable {
|
|
||||||
let message: String
|
|
||||||
let success: Bool
|
|
||||||
}
|
|
||||||
|
|
||||||
struct TestRequestData: Codable {
|
|
||||||
let name: String
|
|
||||||
let email: String
|
|
||||||
}
|
|
||||||
Loading…
Reference in a new issue