Git Product home page Git Product logo

perfect-middleware's Introduction

PerfectMiddleware

Swift Version Twitter

Perfect middleware swift allows developer to register middlewares inside a Perfect HTTPServer

Installation

Swift Package Manager

To install PerfectMiddleware with SPM, add the following lines to your Package.swift.

let package = Package(
    name: "XXX",
    products: [
        .library(
            name: "XXX",
            targets: ["XXX"]),
    ],
    dependencies: [
        .package(url: "https://github.com/Digipolitan/perfect-middleware-swift.git", from: "1.1.0")
    ],
    targets: [
        .target(
            name: "XXX",
            dependencies: ["PerfectMiddleware"])
    ]
)

The Basics

Create an HTTPServer and register routes in the RouterMiddleware

let server = HTTPServer()

let router = RouterMiddleware()

router.get(path: "/").bind { (context) in
    context.response.setBody(string: "It Works !").completed()
    context.next()
}

server.use(router: router)

server.serverPort = 8887

do {
    try server.start()
    print("Server listening on port \(server.serverPort)")
} catch PerfectError.networkError(let err, let msg) {
    print("Network error thrown: \(err) \(msg)")
}

Passing data between middlewares, you can provide 2 or more middleware for the same route and shared data across each middleware using the context

router.get(path: "/")
  .bind { (context) in
    context["name"] = "Steve"
    context.next()
  }
  .bind { (context) in
    guard let name = context["name"] as? String else {
        return
    }
    context.response.setBody(string: "hello mr. \(name)!").completed()
    context.next()
  }

It's possible to create and register Middleware subsclasses instead of closures

class RandomMiddleware: Middleware {

    func handle(context: RouteContext) throws {
        context["rand"] = arc4random()
        context.next()
    }
}

Register Middleware as follow :

router.post(path: "/random")
  .bind(RandomMiddleware())
  .bind { (context) in
    guard let rand = context["rand"] as? UInt32 else {
        return
    }
    context.response.setBody(string: "the result \(rand)").completed()
    context.next()
  }

Advanced

Register middleware for all routes

it's possible to register middlewares before & after all child routes of the router

router.use(event: .beforeAll) { (context) in
    context["start_date"] = Date()
    context.next()
}.use(event: .afterAll) { (context) in
    guard let startDate = context["start_date"] as? Date else {
        return
    }
    let duration = Date().timeIntervalSince1970 - startDate.timeIntervalSince1970
    print(String(duration * 1000) + " ms")
    context.next()
}

This code will print the duration in second of the process for each route

404 handler

router.use(event: .notFound) { (context) in
    context.response.setBody(string: "404").completed()
    context.next()
}

Error handler

router.use { (err, context) in
    context.response.setBody(string: err.localizedDescription).completed()
    context.next()
}

Register sub routers

This code print "My name is" by calling "/user/name" path in your server

let router = RouterMiddleware()

let childRouter = RouterMiddleware()

childRouter.get(path: "/name")
  .bind { (context) in
    context.response.setBody(string: "My name is").completed()
    context.next()
  }

router.use(path: "/user", child: childRouter)

server.use(router: router)

Contributing

See CONTRIBUTING.md for more details!

This project adheres to the Contributor Covenant Code of Conduct. By participating, you are expected to uphold this code. Please report unacceptable behavior to [email protected].

License

PerfectMiddleware is licensed under the BSD 3-Clause license.

perfect-middleware's People

Contributors

bbriatte avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

nitishmakhija

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.