Giter VIP home page Giter VIP logo

d3-network-service's Introduction

Network service layer Combine REST API CRUD

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

Features

  • Stand alone package without any dependencies using just Apple's Combine facilities
  • Error handling from forming URLRequest object to getting data on a subscription
  • Customizable for different environments development, production...
  • Customizable for different requests schemes from classic CRUD Rest to what suits to your own custom routes
  • Based on interfaces not implementations
  • Ability to log and customize logers for different environment
  • Ability to chain requests layering with predicate logic analyzing previous result
  • Do in parallel infinite amount of requests collecting their results in Array and waiting until they are all done

1. Environment

Define enum with interface IEnvironment

enum Environment: IEnvironment {

    case development

    case production

    var baseURL: String {
        switch self {
            case .development: return "http://localhost:3000"
            case .production: return "https://apple.com"
        }
    }
    
    var headers: [IRequestHeader]? {
        switch self {
            case .development: return [ContentType.applicationJSON]
            case .production: return [ContentType.textJSON]
        }
    }
    
    var logger : ILogger? {
        switch self {
            case .development: return ServiceLogger()
            case .production: return nil
        }
    }  
}

Request headers

All headers for a request have to conform to the interface IRequestHeader

The example implementation for content type headers is here ContentType.swift

Logger

You can use out of the box standard logger ServiceLogger if you don't need some specific data from URLRequest and URLResponse or define your own with interface ILogger

2. API for endpoint

Define endpoint API enum

enum UserRestAPI {

    case index
    case read(id: Int)
    case create
    case update
    case delete(id: Int)
}

Extend the enum with interface IRequest

field type
route String
method RequestMethod
extension UserRestAPI: IRequest {
    
    var route: String {
        switch self {
            case .index: return "/user"
            case .read(let id): return "/user/\(id)"
            case .create: return "/user"
            case .update: return "/user"
            case .delete(let id): return "/user/\(id)"
        }
    }
    
    var method: RequestMethod {
        switch self {
            case .index: return .get
            case .read(_): return .get
            case .create: return .post
            case .update: return .put
            case .delete(_): return .delete
        }
    }
}

The example implementation is here UserRestAPI.swift UserRestAPI.swift

3. Create network sevice

    let network = NetworkService(environment: Environment.development)
  • execute - Do request from the endpoint configuration GET, POST, PUT, DELETE

There are four methods are available currently GET, POST, PUT, DELETE

Parameters

Pass a [String: CustomStringConvertible] dictionary to the parameter that available for GET, POST, PUT requests. It's an optional parameter.

Read

   let cfg = UserRestAPI.read(id: 1)
   
   let publisher: Output = network.execute(with: cfg, ["token" : 65678])

Create

    let cfg = UserRestAPI.create
    let user = Model(id: 11, name: "Igor")

    let publisher: Output = network.execute(body: user, with: cfg)

Update

    let cfg = UserRestAPI.update
    let user = Model(id: 11, name: "Igor")    

    let publisher: Output = network.execute(body: user, with: cfg)

Delete

    let cfg = UserRestAPI.delete(id: 11)
    
    let publisher: Output = network.execute(with: cfg)

4. Managing requests

Chaining requests

        let read: Output = network.execute(with: UserRestAPI.index)

        let user = Model(id: 11, name: "Igor")
        let create: Output = network.execute(body: user, with: UserRestAPI.create)
        
        read.then(create)
            
        // or chain it using predicate to analyze previous result
        
        read.then(ifTrue : {$0.count > 1}, create)

Do in parallel infinite amount of requests

Collecting their results in Array and waiting until they are all done

All requests are expected the same output and failure

       [read, create, delete, update, read, read ].doTogether

Mixing

First create and update requests as a group and then read

        [create, update]
                       .waitEverybody
                       .then(read)
                      
        [create, delete]
                        .waitEverybody
                        .then([delete, read].doTogether)               

Package installation

In Xcode - Select Xcode>File> Swift Packages>Add Package Dependency...
and add https://github.com/The-Igor/d3-network-service

Try it in the real environment

Simple server installation (mocking with NodeJS Express)

To try it in the real environment. I suggest installing the basic NodeJS Express boilerplate. Take a look on the video snippet how easy it is to get it through Webstorm that is accessible for free for a trial period.

Server instalation (NodeJS Express)

Real SwiftUI example

d3-rest-combine-swift-example

  • Run server NodeJS Express
  • Run SwiftUI project

Documentation(API)

  • You need to have Xcode 13 installed in order to have access to Documentation Compiler (DocC)
  • Go to Product > Build Documentation or ⌃⇧⌘ D

d3-network-service's People

Contributors

the-igor avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.