DBNetworkStack is a network abstraction for fetching request and mapping them to model objects

Overview

DBNetworkStack

Build Status codebeat badge codecov Swift Package Manager compatible

Main Features
πŸ›‘ Typed network resources
🏠 Value oriented architecture
πŸ”€ Exchangeable implementations
πŸš„ Extendable API
🎹         Composable Features          
βœ… Fully unit tested
πŸ“•   Documented here           

The idea behind this project comes from this talk.objc.io article.

Basic Demo

Lets say you want to fetch a html string.

First you have to create a service, by providing a network access. You can use URLSession out of the box or provide your own custom solution by implementing NetworkAccess.

let networkAccess = URLSession(configuration: .default)
let networkService = BasicNetworkService(networkAccess: networkAccess)

Create a resource with a request to fetch your data.

let url = URL(staticString: "https://httpbin.org")
let request = URLRequest(path: "/", baseURL: url, HTTPMethod: .GET)
let resource = Resource(request: request, parse: { String(data: $0, encoding: .utf8) })

Request your resource and handle the result

networkService.request(resource, onCompletion: { htmlText in
    print(htmlText)
}, onError: { error in
    //Handle errors
})

Load types conforming to Swift-Decodable

struct IPOrigin: Decodable {
    let origin: String
}

let url = URL(staticString: "https://www.httpbin.org")
let request = URLRequest(path: "ip", baseURL: url)

let resource = Resource<IPOrigin>(request: request, decoder: JSONDecoder())

networkService.request(resource, onCompletion: { origin in
    print(origin)
}, onError: { error in
    //Handle errors
})

Accessing HTTPResponse

Request your resource and handle the result & http response. This is similar to just requesting a resulting model.

networkService.request(resource, onCompletionWithResponse: { origin, response in
    print(origin, response)
}, onError: { error in
    //Handle errors
})

Protocol oriented architecture / Exchangability

The following table shows all the protocols and their default implementations.

Protocol Default Implementation
NetworkAccess URLSession
NetworkService BasicNetworkService
NetworkTask URLSessionTask

Composable Features

Class Feature
RetryNetworkService Retrys requests after a given delay when an error meets given criteria.
ModifyRequestNetworkService Modify matching requests. Can be used to add auth tokens or API Keys
NetworkServiceMock Mocks a NetworkService. Can be use during unit tests

Requirements

  • iOS 9.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+
  • Xcode 10.2+
  • Swift 5.0

Installation

Swift Package Manager

SPM is integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies.

Specify the following in your Package.swift:

.package(url: "https://github.com/dbsystel/DBNetworkStack", from: "2.0.0"),

Contributing

Feel free to submit a pull request with new features, improvements on tests or documentation and bug fixes. Keep in mind that we welcome code that is well tested and documented.

Contact

Lukas Schmidt (Mail, @lightsprint09), Christian Himmelsbach (Mail)

License

DBNetworkStack is released under the MIT license. See LICENSE for details.

Comments
  • An example for a POST request would be nice

    An example for a POST request would be nice

    I was looking for an example to a POST request but couldn't find it in the readme. And do I also expect a Resource after the POST when my Server is just answering with a 200 ok?

    opened by mltbnz 4
  • Preparation for 2.0

    Preparation for 2.0

    Fixes issues:

    • Removes URLRequestConvertible
    • Removes deprecated methods

    New feature:

    Make sure to check all boxes before merging

    • [x] Method/Class documentation
    • [x] README.md documentation
    • [x] Unit tests for new features/regressions
    opened by lightsprint09 3
  • Release 1.1

    Release 1.1

    New feature: Version bump

    Make sure to check all boxes before merging

    • [x] Method/Class documentation
    • [x] README.md documentation
    • [x] Unit tests for new features/regressions
    opened by lightsprint09 3
  • Error when building with Carthage

    Error when building with Carthage

    When building DBNetworkStack with Carthage I get the following errors.

    Done linting! Found 0 violations, 0 serious in 41 files.
    swiftlint(8910,0x7000075e5000) malloc: *** error for object 0x7000075e2150: Non-aligned pointer being freed (2)
    *** set a breakpoint in malloc_error_break to debug
    /Users/dennis/Library/Caches/org.carthage.CarthageKit/DerivedData/9.4_9Q1019a/DBNetworkStack/1.1/Build/Intermediates.noindex/ArchiveIntermediates/DBNetworkStack/IntermediateBuildFilesPath/DBNetworkStack.build/Release-iphoneos/DBNetworkStack.build/Script-C60F0D0D1D9A76B90028C417.sh: line 6:  8910 Abort trap: 6           swiftlint
    Command /bin/sh failed with exit code 134
    
    ** ARCHIVE FAILED **
    
    
    The following build commands failed:
    	PhaseScriptExecution 🚧\ Swift\ Lint /Users/dennis/Library/Caches/org.carthage.CarthageKit/DerivedData/9.4_9Q1019a/DBNetworkStack/1.1/Build/Intermediates.noindex/ArchiveIntermediates/DBNetworkStack/IntermediateBuildFilesPath/DBNetworkStack.build/Release-iphoneos/DBNetworkStack.build/Script-C60F0D0D1D9A76B90028C417.sh
    (1 failure)
    

    My current solution is to remove the SwiftLint build phase.

    bug 
    opened by dennispost 2
  • Feature/fixes network service mock return execusion

    Feature/fixes network service mock return execusion

    Fixes issues: #63 , When mocking a returning result with NetworkServiceMock you expect a single call of success or error block.

    At the moment the success or error block is called n+1 which is wrong.

    Make sure to check all boxes before merging

    • [x] Method/Class documentation
    • [x] README.md documentation
    • [x] Unit tests for new features/regressions
    bug 
    opened by lightsprint09 2
  • Update README.md

    Update README.md

    Fixes issues: #26 partially

    New feature:

    Make sure to check all boxes before merging

    • [x] Method/Class documentation
    • [x] README.md documentation
    • [x] Unit tests for new features/regressions
    opened by lightsprint09 2
  • [WIP]Access http response

    [WIP]Access http response

    Fixes issues: #49 , #39

    New feature: When doing a network request, you may want to access the raw HTTPResponse. In our current implementation is this not possible. This opens up the API to access the HTTPResponse when needed.

    Make sure to check all boxes before merging

    • [x] Method/Class documentation
    • [x] README.md documentation
    • [x] Unit tests for new features/regressions
    opened by lightsprint09 2
  • Failing Request

    Failing Request

    In cases where starting a request is not possible (e.g. base url for BaseUrlKey is missing), requests must be able to fail.

    One way would be to have an optional network task as return type.

    opened by ch-one 2
  • Api refinment

    Api refinment

    Fixes issues:

    New feature:

    Make sure to check all boxes before merging

    • [ ] Method/Class documentation
    • [ ] README.md documentation
    • [ ] Unit tests for new features/regressions
    opened by lightsprint09 1
  • Typed error handling

    Typed error handling

    Fixes issues:

    New feature: A Resource defines it Error type.

    Make sure to check all boxes before merging

    • [ ] Method/Class documentation
    • [ ] README.md documentation
    • [ ] Unit tests for new features/regressions
    opened by lightsprint09 1
  • fixes Package.swift

    fixes Package.swift

    Signed-off-by: Lukas Schmidt [email protected]

    Fixes issues:

    New feature:

    Make sure to check all boxes before merging

    • [x] Method/Class documentation
    • [x] README.md documentation
    • [ ] Unit tests for new features/regressions
    opened by lightsprint09 1
  • NetworkServiceMock where responses can be defined before they are consumed

    NetworkServiceMock where responses can be defined before they are consumed

    In some situations it would be helpful to have a NetworkServiceMock where mocked responses can be defined before they are consumed.

    Having an additional mock would bring the following benefits:

    • Separation of mock setup and test code
    • Response definition can be located in one place (in the beginning of the test method or in setUp method) and is not scattered
    • Cases where it is not clear, when the network call will happen are no longer a problem
    • Freedom of choice: Current NetworkServiceMock is still available

    In addition the possibility to define a timing behaviour may be interesting. Something like:

    • Immediately
    • Delayed (by amount of time)
    opened by ch-one 0
  • Rare Edge-case not implemented

    Rare Edge-case not implemented

    When getting and error & a response, the information of the response ist lost.

    see https://oleb.net/blog/2018/03/making-illegal-states-unrepresentable/

    opened by lightsprint09 0
Releases(3.0.0)
  • 3.0.0(Jan 11, 2022)

  • 2.0.1(Oct 29, 2019)

  • 2.0(Sep 26, 2019)

    Some little improvements and sadly breaking changes.

    • Use brand new Result<T, Error> type
    • Removed unneeded URLRequestConvertible
    • NetworkServiceMock tweaks

    Thanks to @OliverDobner-DBSystel

    Source code(tar.gz)
    Source code(zip)
  • 1.2(Aug 22, 2018)

    During summer we worked on the following improvements.

    • New type called ContainerNetworkTask which supports request chaining.
    • Initialize a URL with a StaticString to get rid of if let/guard let
    • Small documentation improvements

    Enjoy the rest of the summer β˜€οΈπŸ§πŸ–πŸ™.

    Source code(tar.gz)
    Source code(zip)
  • 1.1(Jun 6, 2018)

    From now on testing with a NetworkServiceMock is more flexible. It allows you to test cases where multiple requests are involved.

    • When your code performs multiple requests, NetworkServiceMock now queues them and you are able to respond to all requests independently with success or error.
    • Request chains are now supported: Requests started by responses of requests started by responses of requests started by responses... πŸŒ€
    Source code(tar.gz)
    Source code(zip)
  • 1.0(Jan 15, 2018)

    With Version 1.0, the API is declared as stable and will be maintained by conforming to semantic versioning.

    What’s new

    • Support for introspection of the data of a Resource with Resource inspectData

    • New documentation which can be found here

    • Droping the name schema where protocols would end with β€˜providing’ or representing

    • NetworkAccessProvinding -> NetworkAccess, NetworkServiceProviding -> NetworkService, NetworkTaskRepresenting -> NetworkTask, NetworkService -> BasicNetworkService

    Source code(tar.gz)
    Source code(zip)
  • 0.7(Sep 21, 2017)

    What`s new

    • Support for iOS 11 SDK
    • Support for Swift 4.0
    • Support for new Codeable to use in a Resource
    • Cleans up API by removing deprecated types/methods
    Source code(tar.gz)
    Source code(zip)
  • 0.6.0(Aug 2, 2017)

    What`s new

    • Access HTTPURLResponse when requesting a resource.
    • We deprecate ResourceModeling. By doing so we try to get rid of the complexity. The next release will introduce more simple APIs.
    • Refactoring of internal request processing
    Source code(tar.gz)
    Source code(zip)
  • 0.5.0(Jun 21, 2017)

    As discussed in #34 we remove our own representation of Requests and use native URLRequest. By using URLRequest we replace our hard to understand idea of urlKeys.

    What`s new

    • URLRequestConvertible to bridge custom Request objects to URLRequest
    • official CocoaPods support πŸŽ–
    • new ways of type erase a ResourceModeling
    Source code(tar.gz)
    Source code(zip)
  • 0.4.0(Apr 6, 2017)

    • Migration to Swift 3.1
    • Completion handlers execute on a given Queue
    • Linux Support 🐧
    • NetworkServiceMock to improve testing βœ…
    • SwiftLint 0.17.0
    Source code(tar.gz)
    Source code(zip)
  • 0.3.1(Jan 19, 2017)

  • 0.3.0(Jan 19, 2017)

    Service

    • RetryNetworkService - Retrys requests when given errors occur
    • ModifyRequestNetworkService - Can modify requests before they will be executed
    • NetworkTask are marks as @discardableResult

    Resource

    • Map any ResourceModeling with a transform function to Resource
    • Wrap any ResourceModeling into a standard Resource by calling '.wrap()' (Like a type erasure)

    Other

    • NetworkTaskRepresenting now have reference semantics
    • Support for SwiftPackage Manager
    Source code(tar.gz)
    Source code(zip)
  • 0.2.0(Nov 28, 2016)

  • 0.1.0(Nov 9, 2016)

    This is our first public release. Keep in mind that the API could change during the way up to 1.0.

    Feel free to contribute or share our idea.

    Source code(tar.gz)
    Source code(zip)
Owner
DB Systel GmbH
Official GitHub organisation of DB Systel GmbH, ICT-provider for the Deutsche Bahn.
DB Systel GmbH
NSURLSession network abstraction layer, using Codable and Decodable for response and Encodable for request. βš™οΈπŸš€

SONetworking NSURLSession network abstraction layer, using Codable and Decodable for response and Encodable for request. Project Folder and File Struc

Ahmad AlSofi 4 Jan 28, 2022
Type-safe networking abstraction layer that associates request type with response type.

APIKit APIKit is a type-safe networking abstraction layer that associates request type with response type. // SearchRepositoriesRequest conforms to Re

Yosuke Ishikawa 1.9k Dec 30, 2022
Dratini is a neat network abstraction layer.

Dratini Dratini is a neat network abstraction layer. If you are looking for a solution to make your network layer neat, Dratini is your choice. Dratin

Kevin Lin 37 Jan 29, 2022
Network abstraction layer written in Swift.

Moya 14.0.0 A Chinese version of this document can be found here. You're a smart developer. You probably use Alamofire to abstract away access to URLS

Moya 14.4k Jan 1, 2023
Elegant network abstraction layer in Swift.

Elegant network abstraction layer in Swift. δΈ­ζ–‡ Design Features Requirements Communication Installation Usage Base Usage - Target - Request - Download

null 100 Dec 9, 2022
Lightweight network abstraction layer, written on top of Alamofire

TRON is a lightweight network abstraction layer, built on top of Alamofire. It can be used to dramatically simplify interacting with RESTful JSON web-

MLSDev 528 Dec 26, 2022
Network abstraction layer written in Swift.

Moya 15.0.0 A Chinese version of this document can be found here. You're a smart developer. You probably use Alamofire to abstract away access to URLS

Moya 14.4k Jan 4, 2023
Automatically sets the network activity indicator for any performed request.

BigBrother BIG BROTHER IS WATCHING YOU. BigBrother is a Swift library made for iOS that automatically watches for any performed request and sets the n

Marcelo Fabri 446 Dec 17, 2022
A light weight network library with automated model parser for rapid development

Gem A light weight network library with automated model parser for rapid development. Managing all http request with automated model parser calls in a

Albin CR 10 Nov 19, 2022
Another network wrapper for URLSession. Built to be simple, small and easy to create tests at the network layer of your application.

Another network wrapper for URLSession. Built to be simple, small and easy to create tests at the network layer of your application. Install Carthage

Ronan Rodrigo Nunes 89 Dec 26, 2022
Easy and lightweight network layer for creating different set of network requests like GET, POST, PUT, DELETE customizable with coders conforming to TopLevelDecoder, TopLevelEncoder

Easy and lightweight network layer for creating different set of network requests like GET, POST, PUT, DELETE customizable with coders conforming to TopLevelDecoder, TopLevelEncoder

Igor 2 Sep 16, 2022
A network extension app to block a user input URI. Meant as a network extension filter proof of concept.

URIBlockNE A network extension app to block a user input URI. Meant as a network extension filter proof of concept. This is just a research effort to

Charles Edge 5 Oct 17, 2022
Say goodbye to the Fat ugly singleton Network Manager with this Network Layer

MHNetwork Protocol Oriented Network Layer Aim to avoid having bloated singleton NetworkManager Philosophy the main philosophy behind MHNetwork is to h

Mohamed Emad Hegab 19 Nov 19, 2022
NWReachability - a pure Swift library for monitoring the network connection of iOS devices using Apple's Network framework.

NWReachability is a pure Swift library for monitoring the network connection of iOS devices using Apple's Network framework.

null 4 Dec 2, 2022
A computer-vision-driven app for detecting and mapping smog in public roads. Crowdsourcing is rewarded with NFTs. Uber Global Hackathon.

Smogify Detecting smog using ML and rewarding users with NFTs About The Project app in action: https://youtu.be/awJrP-sHb_I Under the growing uncertai

ASOFI 3 Aug 18, 2022
Manage multi-domain url auto mapping ip address table.

Domainer Multi-domain mapper. This library provides manage multi-domain table. Features Manage multi-domain mapping main domain. Find best domain whic

Felix 6 Apr 4, 2020
Elegant API Abstraction for Swift

Endpoint (Deprecated) ⚠️ This project has been deprecated. Consider using Moya and MoyaSugar instead. ?? Elegant API Abstraction for Swift. At a Glanc

Suyeol Jeon 35 Mar 29, 2019
APIProvider - API Provider Package for easier API management inspired by abstraction

APIProvider Using APIProvider you can easily communicate with all API endpoints

null 1 Apr 21, 2022
Minimalistic Swift HTTP request agent for iOS and OS X

Agent Table of Contents Introduction Usage HTTP Verbs Overloading Method Chaining Response Closure Verbs Methods NSMutableURLRequest Contributing Lice

null 589 Jun 29, 2022