Skip to content

Commit

Permalink
Merge branch 'release/1.0.0'
Browse files Browse the repository at this point in the history
  • Loading branch information
bbriatte committed Apr 25, 2017
2 parents d7b0bb8 + bb04b24 commit 587fa6e
Show file tree
Hide file tree
Showing 11 changed files with 672 additions and 55 deletions.
46 changes: 46 additions & 0 deletions CODE_OF_CONDUCT.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
# Contributor Covenant Code of Conduct

## Our Pledge

In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.

## Our Standards

Examples of behavior that contributes to creating a positive environment include:

* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members

Examples of unacceptable behavior by participants include:

* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting

## Our Responsibilities

Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.

Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.

## Scope

This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.

## Enforcement

Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at [contact@digipolitan.com](mailto:contact@digipolitan.com). All complaints will be reviewed and investigated and will result in a response that is deemed necessary and appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.

Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.

## Attribution

This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]

[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
94 changes: 94 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
# Contributing to perfect-middleware-swift

First off, thanks for taking the time to contribute! :tada::+1:

The following is a set of guidelines for contributing to Digipolitan and its packages, which are hosted in the [Digipolitan Organization](https://github.com/digipolitan) on GitHub.
These are just guidelines, not rules. Use your best judgment, and feel free to propose changes to this document in a pull request.

#### Table Of Contents

[What should I know before I get started?](#what-should-i-know-before-i-get-started)
* [Code of Conduct](#code-of-conduct)

[How Can I Contribute?](#how-can-i-contribute)
* [Reporting Bugs](#reporting-bugs)

## What should I know before I get started?

### Code of Conduct

This project adheres to the Contributor Covenant [code of conduct](CODE_OF_CONDUCT.md).
By participating, you are expected to uphold this code.
Please report unacceptable behavior to [contact@digipolitan.com](mailto:contact@digipolitan.com).

### Reporting Bugs

This section guides you through submitting a bug report for Digipolitan. Following these guidelines helps maintainers and the community understand your report :pencil:, reproduce the behavior :computer: :computer:, and find related reports :mag_right:.

Before creating bug reports, please check [this list](#before-submitting-a-bug-report) as you might find out that you don't need to create one. When you are creating a bug report, please [include as many details as possible](#how-do-i-submit-a-good-bug-report). If you'd like, you can use [this template](#template-for-submitting-bug-reports) to structure the information.

#### Before Submitting A Bug Report

* **Perform a [search](https://github.com/issues?q=+is%3Aissue+user%3Adigipolitan)** to see if the problem has already been reported. If it has, add a comment to the existing issue instead of opening a new one.

#### How Do I Submit A (Good) Bug Report?

Bugs are tracked as [GitHub issues](https://guides.github.com/features/issues/). After you've determined

Explain the problem and include additional details to help maintainers reproduce the problem:

* **Use a clear and descriptive title** for the issue to identify the problem.
* **Describe the exact steps which reproduce the problem** in as many details as possible.
* **Provide specific examples to demonstrate the steps**. Include links to files or GitHub projects, or copy/pasteable snippets, which you use in those examples. If you're providing snippets in the issue, use [Markdown code blocks](https://help.github.com/articles/markdown-basics/#multiple-lines).
* **Describe the behavior you observed after following the steps** and point out what exactly is the problem with that behavior.
* **Explain which behavior you expected to see instead and why.**
* **Include screenshots and animated GIFs** which show you following the described steps and clearly demonstrate the problem.
* **If you're reporting that perfect-middleware-swift crashed**, include a crash report with a stack trace from the operating system. On iOS, the crash report is available in Xcode, on macOS, the crash report will be available in `Console.app` under "Diagnostic and usage information" > "User diagnostic reports". Include the crash report in the issue in a [code block](https://help.github.com/articles/markdown-basics/#multiple-lines), a [file attachment](https://help.github.com/articles/file-attachments-on-issues-and-pull-requests/), or put it in a [gist](https://gist.github.com/) and provide link to that gist.
* **If the problem is related to performance**, include a CPU profile capture and a screenshot with your report.
* **If the problem wasn't triggered by a specific action**, describe what you were doing before the problem happened and share more information using the guidelines below.

Provide more context by answering these questions:

* **Did the problem start happening recently** (e.g. after updating to a new version of perfect-middleware-swift) or was this always a problem?
* If the problem started happening recently, **can you reproduce the problem in an older version of perfect-middleware-swift ?** What's the most recent version in which the problem doesn't happen? You can download older versions of perfect-middleware-swift from [the releases page](https://github.com/digipolitan/perfect-middleware-swift/releases).
* **Can you reliably reproduce the issue?** If not, provide details about how often the problem happens and under which conditions it normally happens.

Include details about your configuration and environment:

* **Which version of perfect-middleware-swift are you using?
* **What's the name and version of the macOS or iOS you're using**?

#### Template For Submitting Bug Reports

[Short description of problem here]

**Reproduction Steps:**

1. [First Step]
2. [Second Step]
3. [Other Steps...]

**Expected behavior:**

[Describe expected behavior here]

**Observed behavior:**

[Describe observed behavior here]

**Screenshots and GIFs**

![Screenshots and GIFs which follow reproduction steps to demonstrate the problem](url)

**perfect-middleware-swift version:** [Enter perfect-middleware-swift version here]
**OS and version:** [Enter macOS / iOS / linux name and version here]

**Installed packages:**

[List of installed packages here]

**Additional information:**

* Problem started happening recently, didn't happen in an older version of perfect-middleware-swift: [Yes/No]
* Problem can be reliably reproduced, doesn't happen randomly: [Yes/No]
* Problem happens with all files and projects, not only some files or projects: [Yes/No]
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import PackageDescription
let package = Package(
name: "DGPerfectMiddleware",
dependencies: [
.Package(url: "https://github.com/PerfectlySoft/Perfect-HTTP.git",
.Package(url: "https://github.com/PerfectlySoft/Perfect-HTTPServer.git",
majorVersion: 2,
minor: 1)
]
Expand Down
164 changes: 163 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1 +1,163 @@
# perfect-middleware-swift
DGPerfectMiddleware
=================================

[![Twitter](https://img.shields.io/badge/twitter-@Digipolitan-blue.svg?style=flat)](http://twitter.com/Digipolitan)

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

## Installation

### Swift Package Manager

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

```swift
import PackageDescription

let package = Package(
name: "XXX",
dependencies: [
.Package(url: "https://github.com/Digipolitan/perfect-middleware-swift.git", majorVersion: 1, minor: 0)
]
)
```

## The Basics

Create an HTTPServer and register routes in the RouterMiddleware

```swift
let server = HTTPServer()

let router = RouterMiddleware()

router.get(path: "/") { (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

```swift
router.get(path: "/") { (context) in
context["name"] = "Steve"
context.next()
}

router.get(path: "/") { (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

```swift
class RandomMiddleware: Middleware {

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

Register Middleware as follow :

```swift
router.post(path: "/random", middleware: RandomMiddleware())

router.post(path: "/random") { (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

```swift
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

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

### Error handler

```swift
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

```swift
let router = RouterMiddleware()

let childRouter = RouterMiddleware()

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

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

server.use(router: router)
```

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md) for more details!

This project adheres to the [Contributor Covenant Code of Conduct](CODE_OF_CONDUCT.md).
By participating, you are expected to uphold this code. Please report
unacceptable behavior to [contact@digipolitan.com](mailto:contact@digipolitan.com).

## License

DGPerfectMiddleware is licensed under the [BSD 3-Clause license](LICENSE).
37 changes: 37 additions & 0 deletions Sources/Middleware.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
//
// Middleware.swift
// DGPerfectMiddleware
//
// Created by Benoit BRIATTE on 17/04/2017.
//
//

import PerfectHTTP

/**
* Middleware handler that must be register in a RouterMiddleware
* This closure handle the request, middleware handler are chainable with the RouterMiddleware
*/
public typealias MiddlewareHandler = (RouteContext) throws -> ()

/**
* Special handler that must be register in a RouterMiddleware
* This closure handler errors that should be raised by a middleware
*/
public typealias ErrorHandler = (Error, RouteContext) -> ()

/**
* Middleware protocol, must be register in a RouterMiddleware
* @author Benoit BRIATTE http://www.digipolitan.com
* @copyright 2017 Digipolitan. All rights reserved.
*/
public protocol Middleware {

/**
* Handle the current route
* @param context The route context which contains all informations about the request
* @throws Error
*/
func handle(context: RouteContext) throws

}
Loading

0 comments on commit 587fa6e

Please sign in to comment.