Swiftpack.co - Package - vapor/vapor
Vapor

Documentation Team Chat MIT License Continuous Integration Swift 5.2 Twitter


Vapor is a web framework for Swift. It provides a beautifully expressive and easy to use foundation for your next website, API, or cloud project.

Take a look at some of the awesome stuff created with Vapor.

💧 Community

Join the welcoming community of fellow Vapor developers on Discord.

🚀 Contributing

To contribute a feature or idea to Vapor, create an issue explaining your idea or bring it up on Discord.

If you find a bug, please create an issue.

If you find a security vulnerability, please contact security@vapor.codes as soon as possible.

💛 Sponsors

Support Vapor's development by becoming a sponsor.

Nodes Skelpo Transeo Gwynne Raskind Autimatisering Kyle Browning Jari

💚 Backers

Support Vapor's development by becoming a backer.

analytics

Github

link
Stars: 19193

Releases

Fix Xcode 12 beta 3 warnings - 2020-07-25 02:31:38

This patch was authored and released by @tanner0101.

Fixes Xcode 12 beta 3 warnings and disables some broken CI workflows (#2452).

Allow setting hostname for testable application - 2020-07-22 14:57:25

This patch was authored by @3a4oT and released by @tanner0101.

Adds .running(hostname: String, port: Int) method to allow configure testable application hostname (#2448).


try app.testable(method: .running(hostname: "127.0.0.1", port: 8080))

Make req.auth.require discardable - 2020-07-21 21:18:29

This patch was authored by @SpencerCurtis and released by @tanner0101.

Adds @discardableResult attribute to req.auth.require to allow ignoring the result without a warning (#2446, fixes #2428).

try req.auth.require(User.self) 

Fix array out of bounds error in StackTrace - 2020-07-21 15:55:26

This patch was authored by @klaas and released by @tanner0101.

Fixes an array out of bounds error in StackTrace.description(max:) (#2447).

Add webSocket route overload with array path - 2020-07-20 15:51:44

This patch was authored by @jshier and released by @tanner0101.

Adds a webSocket route overload that accepts an array instead of variadic path (#2445, #2434).

app.webSocket(["foo", "bar"]) { req, ws in 
    // Handle WebSocket client.
}

Fix misspelled property name of class Routes - 2020-07-17 14:54:51

This patch was authored by @wangyanxi and released by @tanner0101.

Fix misspelled property name of class Routes, change from caseInsenstive to caseInsensitive (#2435, fixes #2426).

The misspelled caseInsenstive is now marked as deprecated.

Add FileIO.writeFile - 2020-07-17 02:18:29

This patch was authored by @t-ae and released by @tanner0101.

Adds writeFile method to request's FileIO helper (#2418).

// Writes "hello" to /path/to/file.txt
// Returns a future indicating when the write has completed. 
req.fileio.writeFile(.init(string: "hello"), at: "/path/to/file.txt")

Add support for string interpolation to URI - 2020-07-16 17:24:27

This patch was authored by @dimitribouniol and released by @tanner0101.

Enables call sites that use URIs to allow for string literals that make use of interpolation (#2442).

app.get("hello") { req -> EventLoopFuture<String> in
    return req.client.get("\(Constants.basePath)/status")
    .flatMapThrowing { res throws in
        return "Hello, world!"
    }
}

Add validate(query:) method to Validatable protocol - 2020-07-16 17:15:02

This patch was authored by @odanylewycz and released by @tanner0101.

Adds validate(query:) method to Validatable protocol for validating decoded query parameters (#2419).

Previously, you could only validate the content that came from the request body. Now, this addition allows for validating decoded query parameters that conform to the Content protocol.

struct Hello: Content, Validatable {
    name: String?

    static func validations(_ validations: inout Validations) {
        validations.add("name", as: String.self, is: .alphanumeric)
    }
}

And the following URL, http://localhost:8080/model?name=Vapor, you can now validate the query parameter "name" as follows:

try Hello.validate(query: request)
let hello = try req.query.decode(Hello.self)

The existing content validation method validate(_:) has been renamed to validate(content:) to reduce ambiguity.

try Hello.validate(content: request)
let hello = try req.content.decode(Hello.self)

Add custom validation response example - 2020-07-16 15:43:43

This patch was authored and released by @tanner0101.

Adds a custom validation response example to tests and fixes access to some validator results (#2443).

Header directive parameter quoting - 2020-07-15 18:40:48

This patch was authored and released by @tanner0101.

Adds support for quoting HTTP header value directive parameters containing unsupported characters (#2411, fixes #2439).

For example:

- content-disposition: form-data; filename=foo bar
+ content-disposition: form-data; filename="foo bar"

Header directive parameter quoting - 2020-07-15 18:40:48

This patch was authored and released by @tanner0101.

Adds support for quoting HTTP header value directive parameters containing unsupported characters (#2411, fixes #2439).

For example:

- content-disposition: form-data; filename=foo bar
+ content-disposition: form-data; filename="foo bar"

Add require(_:) extension to Parameters. - 2020-07-15 16:44:34

This patch was authored by @ileitch and released by @tanner0101.

Adds a require(_:) helper to Parameters, allowing for more succinct parameter handling. (#2402)

Previously the optional case needed to be handled explicitly:

guard let name = req.parameters.get("name") else {
    throw Abort(.internalServerError)
}

Now it can be written as:

let name = try req.parameters.require("name")

Allow XCTAssertContent to rethrow errors - 2020-07-15 16:39:12

This patch was authored by @ileitch and released by @tanner0101.

Enables the use of XCTUnwrap within the XCTAssertContent closure (#2403).

Add non-variadic variants of RoutesBuilder group methods. - 2020-07-15 12:36:09

This patch was authored by @ileitch and released by @MrLotU.

This allows for route paths to be passed in as an array. (#2420)

routes.group(["users", ":userID"]) { lists in
    // ...
}

Add method for customizing log handler - 2020-07-14 23:52:07

This patch was authored by @tancred and released by @tanner0101.

Adds a new method for bootstrapping a custom log handler (#2348).

The new LoggingSystem.bootstrap method accepts a LogHandler factory. The detected logging level (configurable with --log or LOG_LEVEL) is passed to the closure.

LoggingSystem.bootstrap(from: &env) { logLevel in 
    MyLogHandler(logLevel: logLevel)
}

There is also a new helper for parsing Logger.Level from the environment.

let logLevel = Logger.Level.detect(from: &env)

Fix query content hooks - 2020-07-14 21:29:36

This patch was authored and released by @tanner0101.

Fixes an issue preventing Content hooks from running when using req.query (#2438, fixes #2416).

Content's beforeEncode and afterDecode now work as expected with URLQueryContainer.

Percent-encoded brackets in query strings - 2020-07-11 16:35:23

This patch was authored and released by @tanner0101.

Adds support for percent-encoded brackets in query strings (fixes #2383, #2384, #2432).

Percent-encoded square brackets are now parsed as array or dictionary delimiters in query strings. For example, both of the following query strings are now equivalent:

page[offset]=0&page[limit]=50
page%5Boffset%5D=0&page%5Blimit%5D=50

Both query strings can now be decoded by the following struct:

struct Info {
    struct Page {
        var offset: Int
        var limit: Int
    }
    let page: Page
}

Previously, the percent-encoded brackets were ignored during array and dictionary parsing.

This change brings Vapor 4's behavior in line with Vapor 3 and other frameworks.

Fix NIOSSL warning - 2020-07-10 19:18:38

This patch was authored and released by @tanner0101.

Fixes a warning caused by a change in NIOSSL 2.8.0 that made NIOSSLServerHandler's initializer non-throwing (#2431).

Support a closure for instantiating RedirectMiddleware - 2020-07-10 18:58:39

This patch was authored by @TomShen1234 and released by @tanner0101.

RedirectMiddleware now supports a closure with a Request object where you can setup a custom redirect based on the original request. (#2364, fixes #2363)

Authenticatable.redirectMiddleware(makePath: { req in
    "/login?orig=\(req.url.path)"
})

Add Vapor 3 API shims - 2020-06-26 18:34:13

This patch was authored and released by @tanner0101.

Adds _Vapor3 module that contains deprecations for Vapor 3 APIs (#2373).

To use this module, add the product as a dependency to your App target in Package.swift. For example:

.target(name: "App", dependencies: [
    .product(name: "Vapor", package: "vapor"),
    .product(name: "_Vapor3", package: "vapor"),
]),

Then import the _Vapor3 module to enable deprecations.

import Vapor
import _Vapor3

...

app.get("test") { req -> Future<String> in
//                       ^~~~~~
// 'Future' is deprecated: renamed to 'EventLoopFuture'
    ...
}

Note: This module only deprecates part of the Vapor 3 API. Some things are missing and not everything can be deprecated. If you'd like to add something, please open up a PR!

Immediate body streaming - 2020-06-26 18:25:26

This patch was authored and released by @tanner0101.

Refactors HTTP request body decoding to immediately make streaming bodies available via req.body.drain (#2413).

Previously, Vapor's HTTP request decoder would wait for a second body chunk to arrive before initiating body streaming. This was done as a performance optimization for single-chunk bodies since streaming has overhead. However, this behavior made it difficult to implement real time streaming handlers, like a ping/pong handler.

The HTTP request decoder has been updated to initiate body streaming immediately upon receiving the first chunk. To avoid impacting performance on small, non-streaming request bodies, a check for content-length has been added. If the request's body is contained entirely in a single chunk, streaming overhead is avoided.

Below are performance numbers on Ubuntu 20.04 in req/s.

|Method|Body Strategy|Previous|New|Delta| |-|-|-|-|-| |GET|.collect|229979.85|229333.16|0.28%| |POST|.collect|198949.90|196567.85|1.21%| |POST|.stream|197916.54|196178.48|0.89%|

The numbers show a negligible change in performance.

Logging improvements - 2020-06-26 16:59:36

This patch was authored and released by @tanner0101.

Improves readability of framework log messages and adds API for controlling error logging (#2412).

  • Downgraded several instances of .error level logging to .debug.

Note: The developer should have control over all .error level logs generated as the result of incoming HTTP requests.

  • Added logLevel property to DebuggableError.

Note: This allows DebuggableError's to control how they are reported to logs. Vapor's default "route not found" error uses this new API to log at .debug level.

  • Fixed an issue causing stack traces to be included when logLevel > .trace.

Note: Stack traces were only meant to be reported at the .trace level as they generate significant output.

  • Error source information is no longer duplicated in logs.

Fix #file usage for 5.3 - 2020-06-25 20:24:42

This patch was authored and released by @tanner0101.

Fixes issue with previous #file warning fix in 4.10.1 that caused incorrect file paths to be passed (#2411).

Wrapping the default #file parameter in parentheses prevents it from forwarding to the call site. The parentheses must be added before passing to the methods accepting #filePath.

See new discussion of SE-0274 for more information.

Add case-insensitive routing - 2020-06-24 19:35:13

This patch was authored by @tdotclare and released by @tanner0101.

Allows configuring case-insensitive routing (#2354).

// Enables case-insensitive routing.
// Defaults to false.
app.routes.caseInsensitive = true

Fix `routes` command symbol usage - 2020-06-24 19:01:51

This patch was authored by @stevapple and released by @tanner0101.

Update routes command to keep consistency with symbols used by RoutingKit like *, :, etc (#2366).

Fix `routes` command symbol usage - 2020-06-24 19:01:51

This patch was authored by @stevapple and released by @tanner0101.

Update routes command to keep consistency with symbols used by RoutingKit like *, :, etc (#2366).

HTTP streaming improvements - 2020-06-24 18:36:30

This patch was authored and released by @tanner0101.

Improves HTTP request and response streaming (#2404).

  • Streaming request body skipping will only happen if the entire response has been sent before the user starts reading the request body (fixes #2393).

Note: Previously, streaming request bodies would be drained automatically by Vapor as soon as the response head was sent. This made it impossible to implement realtime streaming, like an echo server. With these changes, you have much more control over streaming HTTP while still preventing hanging if the request body is ignored entirely.

  • Response body stream now supports omitting the count parameter (fixes #2393).

Note: Previously streaming bodies required a count and would always set the content-length header. Now, setting a count of -1 indicates a stream with indeterminate length. -1 will be used if the stream count is omitted. This results in transfer-encoding: chunked being used automatically.

  • Response writer provides a better error message if stream is never ended (fixes #2390).

  • Fixes an issue causing EOF framing to result in promise leak (fixes #2391).

  • Response streams with determinate length that write too few or too many bytes will now result in an error (fixes #2392).

Follow the 'required' argument for nested validations - 2020-06-24 08:19:14

This patch was authored by @seeppp and released by @MrLotU.

Validations now follows required argument while validating nested validations.

If we add a validation step of a nested object, which is optional, the required flag would be set false.

validations.add("optionalNestedObject", required: false, B.validations)

Therefore, we are now able to have an object like this:

struct A: Codable {
    var name: String
    var optionalNestedObject: A?
}

extension A: Validatable {
    static func validations(_ validations: inout Validations) {
        validations.add("name", as: String.self, is: .ascii)
        validations.add("optionalNestedObject", required: false, A.validations)
    }
}

The validator now validates the nested object only if optionalNestedObject != nil.

If the nested object is non-optional, you can still omit the required argument.

validations.add("nestedObject", B.validations)

Remove percent encoding when logging url path - 2020-06-24 08:01:26

This patch was authored by @valeriomazzeo and released by @MrLotU.

Remove percent encoding when logging url path (#2399)

The DefaultResponder now removes the percent encoding when logging the url request's path.

Previous log:

[ INFO ] GET /users/auth0%7C59abc/

After this change:

[ INFO ] GET /users/auth0|59abc/