Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
doxuto authored and doxuto committed Mar 6, 2024
0 parents commit a620285
Show file tree
Hide file tree
Showing 16 changed files with 750 additions and 0 deletions.
34 changes: 34 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
name: CI

on:
push:
branches:
- main
pull_request:
branches:
- '*'
workflow_dispatch:

concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true

jobs:
library:
runs-on: macos-13
strategy:
matrix:
xcode:
- '15.2'
- '15.1'
- '15.0'
- '14.3.1'

steps:
- uses: actions/checkout@v4
- name: Select Xcode ${{ matrix.xcode }}
run: sudo xcode-select -s /Applications/Xcode_${{ matrix.xcode }}.app
- name: Skip macro validation
run: defaults write com.apple.dt.Xcode IDESkipMacroFingerprintValidation -bool YES
- name: Run tests
run: swift test
90 changes: 90 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Xcode
#
# gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore

## User settings
xcuserdata/

## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)
*.xcscmblueprint
*.xccheckout

## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)
build/
DerivedData/
*.moved-aside
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3

## Obj-C/Swift specific
*.hmap

## App packaging
*.ipa
*.dSYM.zip
*.dSYM

## Playgrounds
timeline.xctimeline
playground.xcworkspace

# Swift Package Manager
#
# Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
# Packages/
# Package.pins
# Package.resolved
# *.xcodeproj
#
# Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata
# hence it is not needed unless you have added a package configuration file to your project
# .swiftpm

.build/

# CocoaPods
#
# We recommend against adding the Pods directory to your .gitignore. However
# you should judge for yourself, the pros and cons are mentioned at:
# https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
#
# Pods/
#
# Add this line if you want to avoid checking in source code from the Xcode workspace
# *.xcworkspace

# Carthage
#
# Add this line if you want to avoid checking in source code from Carthage dependencies.
# Carthage/Checkouts

Carthage/Build/

# Accio dependency management
Dependencies/
.accio/

# fastlane
#
# It is recommended to not store the screenshots in the git repo.
# Instead, use fastlane to re-generate the screenshots whenever they are needed.
# For more information about the recommended setup visit:
# https://docs.fastlane.tools/best-practices/source-control/#source-control

fastlane/report.xml
fastlane/Preview.html
fastlane/screenshots/**/*.png
fastlane/test_output

# Code Injection
#
# After new code Injection tools there's a generated folder /iOSInjectionProject
# https://github.com/johnno1962/injectionforxcode

iOSInjectionProject/
7 changes: 7 additions & 0 deletions .swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 doxuto

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
24 changes: 24 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// swift-tools-version: 5.5
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
name: "APIClient",
platforms: [.iOS(.v13), .macOS(.v10_15)],
products: [
// Products define the executables and libraries a package produces, making them visible to other packages.
.library(
name: "APIClient",
targets: ["APIClient"]),
],
targets: [
// Targets are the basic building blocks of a package, defining a module or a test suite.
// Targets can depend on other targets in this package and products from dependencies.
.target(
name: "APIClient"),
.testTarget(
name: "APIClientTests",
dependencies: ["APIClient"]),
]
)
87 changes: 87 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
[![CI](https://github.com/doxuto/APIClient/actions/workflows/ci.yml/badge.svg)](https://github.com/doxuto/APIClient/actions/workflows/ci.yml)
[![Swift](https://img.shields.io/badge/Swift-5.5_|_5.6_|_5.7_|_5.8_|_5.9-red)](https://img.shields.io/badge/Swift-5.5_5.6_5.7_5.8_5.9-red)
[![Platforms](https://img.shields.io/badge/Platforms-macOS_|_iOS-red)](https://img.shields.io/badge/Platforms-macOS_iOS-red)
### README.md

```markdown
# APIClient

## Description
A simply networking layer in Swift that allows you to easily make HTTP requests and handle response data.

## Installation
To use the APIClient module in your Swift project, include this package as a dependency in your Package.swift file.

```swift
dependencies: [
.package(url: "https://github.com/doxuto/APIClient.git", from: "1.0.0")
]
```

## Usage
1. Import the APIClient module in your Swift files where you need to make API requests.

```swift
import APIClient

struct UserEndpoint: Endpoint {
var url: URL = URL(string: "https://httpbin.org/get")!
var requestMethod: RequestMethod = RequestMethod.get
var headers: [String : String]? = nil
var parameters: [String : String]? = nil
var timeoutInterval: TimeInterval = 60
}

let apiClient = APIClient(
validator: DefaultValidator(),
urlSession: URLSession.shared,
jsonDecoder: JSONDecoder()
)

let endpoint = UserEndpoint()
let user: User = try await apiClient.request(endpoint: endpoint)
```

Or you can use Combine's `Publisher` type to handle API responses.
```
func fetchUser() -> AnyPublisher<User, Error> {
let endpoint = UserEndpoint()
return apiClient.request(endpoint: endpoint)
}
```

2. If you want to customize the `Validator` of APIClient, you can do that in the contructor `APIClient`
```
struct CustomizedValidator: Validator {
func validate(for response: HTTPURLResponse) -> Bool {
let statusCode = response.statusCode
return statusCode == 200
}
}
let apiClient = APIClient(
validator: CustomizedValidator(),
urlSession: URLSession.shared,
jsonDecoder: JSONDecoder()
)
let endpoint = UserEndpoint()
let user: User = try await apiClient.request(endpoint: endpoint)
```


## Dependencies
- No external dependencies required.

## Structure
- **APIClient:** Main module for handling API requests.
- **APIClientTests:** Unit tests for the APIClient module.

## Contribution
Feel free to contribute by forking the repository and submitting pull requests.

## License
This package is released under the MIT License. See LICENSE file for more details.
```
65 changes: 65 additions & 0 deletions Sources/APIClient/APIClient.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
//
// APIClient.swift
//
//
// Created by doxuto on 05/03/2024.
//

import Foundation
import Combine

public struct APIClient {
private let validator: any Validator
private let urlSession: URLSession
private let jsonDecoder: JSONDecoder

public init(validator: any Validator, urlSession: URLSession, jsonDecoder: JSONDecoder) {
self.validator = validator
self.urlSession = urlSession
self.jsonDecoder = jsonDecoder
}

public func request(endpoint: any Endpoint) async throws -> Data {
let urlRequest = endpoint.toRequest
let data: Data
let urlResponse: URLResponse
do {
let response = try await urlSession.data(for: urlRequest)
data = response.0
urlResponse = response.1 as! HTTPURLResponse
} catch {
throw ApiError.underlying(error)
}

guard try validator.validate(for: urlResponse as! HTTPURLResponse) else {
throw ApiError.invalid
}
return data
}

public func request<T: Decodable>(endpoint: any Endpoint) async throws -> T {
let data = try await self.request(endpoint: endpoint)
do {
let result = try jsonDecoder.decode(T.self, from: data)
return result
} catch {
throw ApiError.parseError(error)
}
}

public func request<T: Decodable>(endpoint: any Endpoint) -> AnyPublisher<T, Error> {
urlSession.dataTaskPublisher(for: endpoint.toRequest)
.tryMap { try process(data: $0, response: $1) }
.eraseToAnyPublisher()
}

private func process<T: Decodable>(data: Data, response: URLResponse) throws -> T {
let httpResponse = response as! HTTPURLResponse
guard try validator.validate(for: httpResponse) else { throw ApiError.invalid }
do {
return try jsonDecoder.decode(T.self, from: data)
} catch {
throw ApiError.parseError(error)
}
}
}
15 changes: 15 additions & 0 deletions Sources/APIClient/Models/ApiError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
//
// ApiError.swift
//
//
// Created by doxuto on 05/03/2024.
//

import Foundation

public enum ApiError: Error, Sendable {
case invalid
case badRequest
case underlying(Error)
case parseError(Error)
}
16 changes: 16 additions & 0 deletions Sources/APIClient/Models/DefaultValidator.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
//
// DefaultValidator.swift
//
//
// Created by doxuto on 05/03/2024.
//

import Foundation

struct DefaultValidator: Validator {
let filteredStatusCodes = 200...299
func validate(for response: HTTPURLResponse) -> Bool {
let statusCode = response.statusCode
return filteredStatusCodes.contains(statusCode)
}
}
Loading

0 comments on commit a620285

Please sign in to comment.