Skip to content

Latest commit

 

History

History
83 lines (64 loc) · 2.19 KB

File metadata and controls

83 lines (64 loc) · 2.19 KB

Browser Method Middleware Provider for Vapor

Swift Vapor CircleCI

Vapor's ResourceRepresentable likes to use a wide range of HTTP verbs, but browsers like to use only GET and POST.

A common solution is to allow a POST request containing a special key _method which tells the server what HTTP method was actually intended.

This provider allows Vapor to do the same thing.

Setup

Add the dependency to Package.swift:

.Package(url: "https://github.com/bygri/vapor-browser-method-middleware-provider.git", majorVersion: 1)

Register the provider with the configuration system:

import BrowserMethodMiddlewareProvider

extension Config {
    /// Configure providers
    private func setupProviders() throws {
        ...
        try addProvider(BrowserMethodMiddlewareProvider.Provider.self)
    }
}

And finally, add the browser-method middleware key to the Droplet by editing droplet.json:

{
    "middleware": [
        ...
        "browser-method"
    ],
}

Usage

TL;DR:

<input type='hidden' name='_method' value='patch'>

Longer example:

ResourceRepresentable only routes to update() if the request uses the PATCH method, but most browsers will only send a form using POST. So, if you are creating a widget edit form, you can make Vapor think you sent a PATCH request by adding a hidden input named _method with value patch to your form.

<form method='post' action='/widget/#(widget.id)'>
    <input type='hidden' name='_method' value='patch'>
    <p>
        Name
        <input type='text' name='name' value='#(widget.name)'>
    </p>
    <p>
        Description
        <input type='text' name='description' value='#(widget.description)'>
    </p>
    <button type='submit'>Update</button>
</form>

Package name

Can you think of a better one?