Skip to content

Commit

Permalink
Added support for different post types, fixes #1
Browse files Browse the repository at this point in the history
  • Loading branch information
0xWDG committed Feb 26, 2024
1 parent 977893e commit cc480f9
Show file tree
Hide file tree
Showing 6 changed files with 156 additions and 37 deletions.
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ networking.set(userAgent: "STRING")
networking.set(authorization: "STRING")
```

### Set post type (optional)
```swift
networking.set(postType: .json) // .plain, .json, .graphQL
```

### GET data Async/Await
```swift
import SimpleNetworking
Expand Down Expand Up @@ -157,6 +162,25 @@ let cookie = HTTPCookie.init(properties: [
SimpleNetworking.shared.add(cookie: "cookie")
```

### Debugging
```swift

/// Debug: NSURLRequest
SimpleNetworking.shared.debug.requestURL = false
/// Debug: sent HTTP Headers
SimpleNetworking.shared.requestHeaders = false
/// Debug: sent Cookies
SimpleNetworking.shared.requestCookies = false
/// Debug: sent Body
SimpleNetworking.shared.requestBody = false
/// Debug: received HTTP Headers
SimpleNetworking.shared.responseHeaders = false
/// Debug: received Body
SimpleNetworking.shared.responseBody = false
/// Debug: received JSON (if any)
SimpleNetworking.shared.responseJSON = false
```

## Contact

We can get in touch via [Twitter/X](https://twitter.com/0xWDG), [Discord](https://discordapp.com/users/918438083861573692), [Mastodon](https://iosdev.space/@0xWDG), [Threads](http://threads.net/@0xwdg), [Bluesky](https://bsky.app/profile/0xwdg.bsky.social).
Expand Down
10 changes: 10 additions & 0 deletions Sources/SimpleNetworking/SimpleNetworking.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ open class SimpleNetworking {
/// Custom authorization token
internal var authToken: String?

/// Post Type
internal var postType: POSTType = .json

/// custom session
internal var session: URLSession? = URLSession(configuration: .ephemeral)

Expand Down Expand Up @@ -72,6 +75,13 @@ open class SimpleNetworking {
self.authToken = authorization
}

/// Set the post type
/// - Parameter postType: post type
public func set(postType: POSTType) {
self.postType = postType
}


/// Add a cookie to the storage
/// - Parameter add: cookie
public func cookie(add: HTTPCookie) {
Expand Down
89 changes: 89 additions & 0 deletions Sources/SimpleNetworking/SimpleNetworking/createHTTPBody.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
//
// createHTTPBody.swift
// Simple Networking
//
// Created by Wesley de Groot on 26/02/2024.
// https://wesleydegroot.nl
//
// https://github.com/0xWDG/SimpleNetworking
// MIT LICENCE
//

import Foundation

extension SimpleNetworking {
/// httpBody Method for internal use
func createHTTPBody(with value: Any?) -> Data? {
switch self.postType {
case .json:
if let contents = value as? [String: Codable] {
return try? JSONSerialization.data(withJSONObject: contents)
}

if let contents = value as? Codable {
return try? JSONEncoder().encode(contents)
}

case .plain:
if let contents = value as? String {
return contents.data(using: .utf8)
}

if let contents = value as? [String: Codable] {
return contents.map { key, value in
let escapedKey = "\(key)".addingPercentEncoding(
withAllowedCharacters: urlQueryValueAllowed()
) ?? ""
let escapedValue = "\(value)".addingPercentEncoding(
withAllowedCharacters: urlQueryValueAllowed()
) ?? ""
return escapedKey + "=" + escapedValue
}
.joined(separator: "&")
.data(using: .utf8)
}

if let contents = value as? [String: Any] {
return contents.map { key, value in
let escapedKey = "\(key)".addingPercentEncoding(
withAllowedCharacters: urlQueryValueAllowed()
) ?? ""
let escapedValue = "\(value)".addingPercentEncoding(
withAllowedCharacters: urlQueryValueAllowed()
) ?? ""
return escapedKey + "=" + escapedValue
}
.joined(separator: "&")
.data(using: .utf8)
}

case .graphQL:
if let query = value as? String {
return try? JSONSerialization.data(withJSONObject: [
"query": query
])
}
}

return nil
}

/// Content-Type Header for internal use
func getContentType() -> String {
switch postType {
case .plain:
return "application/x-www-form-urlencoded"
case .json, .graphQL:
return "application/json"
}
}

private func urlQueryValueAllowed() -> CharacterSet {
let generalDelimitersToEncode = ":#[]@"
let subDelimitersToEncode = "!$&'()*+,;="

var allowed: CharacterSet = .urlQueryAllowed
allowed.remove(charactersIn: "\(generalDelimitersToEncode)\(subDelimitersToEncode)")
return allowed
}
}
38 changes: 8 additions & 30 deletions Sources/SimpleNetworking/SimpleNetworking/request.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,12 @@ extension SimpleNetworking {
request.httpMethod = method.method

switch method {
case .delete(let data):
parseMethodData(data: data, request: &request)

case .post(let data):
parseMethodData(data: data, request: &request)

case .put(let data):
parseMethodData(data: data, request: &request)
case .delete(let data), .post(let data), .put(let data):
request.setValue(getContentType(), forHTTPHeaderField: "Content-Type")
request.httpBody = createHTTPBody(with: data)

case .get:
_ = ""
request.setValue(getContentType(), forHTTPHeaderField: "Content-Type")
}

return await exec(with: request, file: file, line: line, function: function)
Expand Down Expand Up @@ -88,17 +83,12 @@ extension SimpleNetworking {
request.httpMethod = method.method

switch method {
case .delete(let data):
parseMethodData(data: data, request: &request)

case .post(let data):
parseMethodData(data: data, request: &request)

case .put(let data):
parseMethodData(data: data, request: &request)
case .delete(let data), .post(let data), .put(let data):
request.setValue(getContentType(), forHTTPHeaderField: "Content-Type")
request.httpBody = createHTTPBody(with: data)

case .get:
_ = ""
request.setValue(getContentType(), forHTTPHeaderField: "Content-Type")
}

exec(with: request, completionHandler: { response in
Expand Down Expand Up @@ -130,16 +120,4 @@ extension SimpleNetworking {

return request
}

internal func parseMethodData(data: Any?, request: inout URLRequest) {
request.setValue("application/json", forHTTPHeaderField: "Content-Type")

if let contents = data as? [String: Codable] {
request.httpBody = try? JSONSerialization.data(withJSONObject: contents)
}

if let contents = data as? Codable {
request.httpBody = try? JSONEncoder().encode(contents)
}
}
}
14 changes: 7 additions & 7 deletions Sources/SimpleNetworking/Structs/Debug.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,18 @@ extension SimpleNetworking {
/// Debug parameters
public struct Debug {
/// Debug: NSURLRequest
var requestURL: Bool = false
public var requestURL: Bool = false
/// Debug: sent HTTP Headers
var requestHeaders: Bool = false
public var requestHeaders: Bool = false
/// Debug: sent Cookies
var requestCookies: Bool = false
public var requestCookies: Bool = false
/// Debug: sent Body
var requestBody: Bool = false
public var requestBody: Bool = false
/// Debug: received HTTP Headers
var responseHeaders: Bool = false
public var responseHeaders: Bool = false
/// Debug: received Body
var responseBody: Bool = false
public var responseBody: Bool = false
/// Debug: received JSON (if any)
var responseJSON: Bool = false
public var responseJSON: Bool = false
}
}
18 changes: 18 additions & 0 deletions Sources/SimpleNetworking/Structs/POSTType.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//
// POSTType.swift
// Simple Networking
//
// Created by Wesley de Groot on 26/02/2024.
// https://wesleydegroot.nl
//
// https://github.com/0xWDG/SimpleNetworking
// MIT LICENCE
//

import Foundation

extension SimpleNetworking {
public enum POSTType {
case json, plain, graphQL
}
}

0 comments on commit cc480f9

Please sign in to comment.