Giter Site home page Giter Site logo

retroswift's Introduction

RetroSwift

This library provides the approach to API contract definition in the Retrofit-like fashion on Swift.

It gives possibility to define API in this way:

final class SchedulesApi: ApiDomain {
    @Get("/api/v1/schedule")
    var getSchedules: (GetSchedulesRequest) async throws -> GetSchedulesResponse

    @Put("/api/v1/schedule")
    var createSchedule: (CreateScheduleRequest) async throws -> Empty

    @Post("/api/v1/schedule/{schedule_id}")
    var updateSchedule: (UpdateScheduleRequest) async throws -> UpdateScheduleResponse

    @Delete("/api/v1/schedule/{schedule_id}")
    var deleteSchedule: (DeleteScheduleRequest) async throws -> Either<DeleteScheduleResponse, DeleteScheduleErrorResponse>
}

*Request types provide more details on endpoints contracts, namely define parameters and their mapping to the HTTP params - Query, Header, Path, JsonBody:

struct GetSchedulesRequest {
    @Query var page: Int
    @Query("limit") var schedulesPerPage: Int = 0
    @Header("X-Account-Id") var accountId: String = ""
}

struct CreateScheduleRequest {
    @Header("X-Account-Id") var accountId: String = ""
    @JsonBody var scheduleBody: Schedule
}

struct DeleteScheduleRequest {
    @Path("schedule_id") var ScheduleId: String = ""
    @Header("X-Account-Id") var accountId: String = ""
}

Usage is quite simple:

let transport: HttpTransport = ....
let api = SchedulesApi(transport: transport)

let request = GetSchedulesRequest(page: 1, schedulesPerPage: 30, accountId: "acc_id")
let response = try await api.getSchedules(request)

Additionally responses can be mocked in a straightforward and self-describing way:

api.getSchedules = { _ in
    GetSchedulesResponse(....)
}

api.deleteSchedule = { _ in
    throw URLError(.userAuthenticationRequired)
}

api.deleteSchedule = { _ in
    .errorResponse(DeleteScheduleErrorResponse(errorMessage: "Schedule not found"))
}

ApiDomain in the simplest case can be implemented as follow:

class ApiDomain: Domain {
    override init(transport: HttpTransport) {
        super.init(transport: transport)
        transport.setConfiguration(scheme: "https", host: "rest.bandsintown.com", sharedHeaders: nil)
    }
}

More complex solutions can include, for example, session token management.

HttpTransport is the protocol describing HTTP network communication layer.

public protocol HttpTransport {
    func setConfiguration(scheme: String, host: String, sharedHeaders: [String: String]?)
    func sendRequest(with params: HttpRequestParams) async throws -> HttpOperationResult
}

DemoProject contains simple implementation based on the UrlSession, but you can provide yours depending on your needs.

Features

Supported HTTP methods:

  • @Delete
  • @Get
  • @Head
  • @Patch
  • @Post
  • @Put

Supported parameter types:

  • @Header
  • @Path
  • @Query
  • @JsonBody

By default parameter name is taken from the variable name, but it can be customized:

@Header("X-Account-Id") var accountId: String = ""

Supported response types:

  • any type conforming to Decodable
  • Either<Response: Decodable, ErrorResponse: Decodable>
  • Empty

Either type allows to get either success or error response.

Response mocking. You can easily mock response by assigning directly to the api's endpoint definition:

api.deleteSchedule = { _ in
    .errorResponse(DeleteScheduleErrorResponse(errorMessage: "Schedule not found"))
}

Adding RetroSwift as a Dependency

Xcode

If you're working with a project in Xcode RetroSwift can be easily integrated:

  1. In Xcode, select File > Add Packages...
  2. Or go to the project's settings, select your project from the list, go to the Package Dependencies and click + button
  3. Specify the Repository: https://github.com/level-two/RetroSwift
  4. Go to the Target, on General tab find Frameworks, Libraries and Embedded content section, click '+' and add RetroSwift library as a dependency

Swift Package Manager

To use this library in a SwiftPM project, add the following line to the dependencies in your Package.swift file:

.package(url: "https://github.com/level-two/RetroSwift", from: "0.0.1"),

and include it as a dependency for your target:

.target(
    ...
    dependencies: [
        "RetroSwift",
    ],
    ...
),

Finally, add import RetroSwift to your source code.

retroswift's People

Stargazers

 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.