Giter VIP home page Giter VIP logo

vapor-routing's Introduction

Swift 5.7 CI @pointfreeco

This repo contains the full source code for the Point-Free website, a video series exploring advanced programming topics in Swift. The codebase is split into 3 pieces:

  • PointFree: This is the core application, and is responsible for routing requests, loading data and rendering HTML and CSS.
  • Styleguide: This library contains functions and data types for creating a consistent style across the entire website.
  • Server: This is the actual executable server. It uses NIO to handle the low-level server responsibilities, and hands everything else over to the PointFree package.

Point-Free Homepage

Getting Started

Interested in a video tour of the code base?

video poster image

The repo contains an extensive test suite and some playgrounds to explore. To get things running:

  • Open up a terminal window and grab the code:

    git clone https://github.com/pointfreeco/pointfreeco.git
    cd pointfreeco
  • Make sure cmark is installed. You can install it with Homebrew:

    brew install cmark # or your preferred installation method
  • Make sure Postgres is installed and running. It's our database of choice. You can install it with Homebrew:

    brew install postgres # or your preferred installation method
    brew services start postgresql # or your preferred launch method
    make db

    (If you use Postgres.app, EnterpriseDB, or another installation method, please follow some additional instructions in the CPostgreSQL README.)

With the project open in Xcode, you can:

  • Run the server locally
    • Select the Server target
    • Run: Command+R
    • Visit http://localhost:8080
  • Explore our playgrounds
    • Select the PointFree target
    • Build: Command+B
    • Open a playground!

Some fun things to explore

There're a lot of fun things to explore in this repo. For example:

  • We develop web pages in playgrounds for a continuous feedback loop. This is made possible by the fact that the entire server stack is composed of pure functions with side-effects pushed to the boundaries of the application. It allows us to load up any request in isolation, including POST requests, all without ever worrying about doing a side-effect. Server side Swift in a playground

  • We use snapshot testing to capture full data structures in order to verify their correctness. Not only do we do this in the traditional way of taking screenshots of web pages at various break points (e.g. on iPhone and desktop), but we can also snapshot any entire request-to-response lifecycle (e.g. the POST to a signup page does the correct redirect).

▿ Step
  ResponseEnded

▿ Request
  POST http://localhost:8080/launch-signup

  [email protected]

▿ Response
  Status 302 FOUND
  Location: /?success=true

Xcode Color Theme

Like the color theme we use in our episodes? Run make colortheme to install locally!

Related projects

Point-Free uses a bunch of interesting open-source software:

  • 🗺 swift-html: A Swift DSL for type-safe, extensible, and transformable HTML documents.
  • 🕸 swift-web: A collection of types and functions for dealing with common web server concerns, such as HTML render, CSS preprocessing, middleware and more.
  • 🎶 swift-prelude: Offers a standard library for experimental functional programming in Swift.
  • 🏷 swift-tagged: Helps us create strong contracts with our data boundaries, like JSON from GitHub and Stripe, and our PostgreSQL data.
  • 📸 swift-snapshot-testing: Powers our testing infrastructure by taking snapshots of various data structures to guarantee the correctness of their output. We use this on everything from middleware to ensure requests are correctly transformed into responses, and even entire web pages to make sure the site looks correct at a variety of sizes (e.g. on iPhone and desktop).

Explore more of our open-source on the Point-Free organization.

Learn More

Brandon gave a talk about most of the core ideas that went into this project at Swift Summit 2017.

The two sides of writing testable code

Find this interesting?

Then check out Point-Free!

License

The content of this project itself is licensed under the CC BY-NC-SA 4.0 license, and the underlying source code used to format and display that content is licensed under the MIT license.

vapor-routing's People

Contributors

finestructure avatar gohanlon avatar mbrandonw avatar stephencelis avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vapor-routing's Issues

Breaking change in release 0.1.3

Screenshot 2023-04-16 at 22 20 31

dependencies: [
        .package(url: "https://github.com/vapor/vapor.git", from: "4.0.0"),
        .package(url: "https://github.com/vapor/fluent.git", from: "4.0.0"),
        .package(url: "https://github.com/vapor/fluent-postgres-driver.git", from: "2.0.0"),
        .package(url: "https://github.com/vapor/leaf.git", from: "4.0.0"),
        .package(url: "https://github.com/pointfreeco/vapor-routing", from: "0.1.0")
    ],

Forcing previous release fixes my issue

 .package(url: "https://github.com/pointfreeco/vapor-routing", esact: "0.1.2")

Unable to run with Docker

Hi! I am getting an error after adding this library to generated by vapor new project with fluent+postgre.
This error does not appears with docker compose build but, after running docker compose up I got this:

$ docker compose up   
[+] Running 2/2
 ⠿ Container testpointfree-db-1   Created                                                                                                         0.0s
 ⠿ Container testpointfree-app-1  Recreated                                                                                                       0.1s
Attaching to testpointfree-app-1, testpointfree-db-1
testpointfree-db-1   | 
testpointfree-db-1   | PostgreSQL Database directory appears to contain a database; Skipping initialization
testpointfree-db-1   | 
testpointfree-db-1   | 2022-05-24 13:57:41.910 UTC [1] LOG:  starting PostgreSQL 14.3 on x86_64-pc-linux-musl, compiled by gcc (Alpine 10.3.1_git20211027) 10.3.1 20211027, 64-bit
testpointfree-db-1   | 2022-05-24 13:57:41.911 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
testpointfree-db-1   | 2022-05-24 13:57:41.911 UTC [1] LOG:  listening on IPv6 address "::", port 5432
testpointfree-db-1   | 2022-05-24 13:57:41.914 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
testpointfree-db-1   | 2022-05-24 13:57:41.920 UTC [22] LOG:  database system was shut down at 2022-05-24 13:51:55 UTC
testpointfree-db-1   | 2022-05-24 13:57:41.933 UTC [1] LOG:  database system is ready to accept connections
testpointfree-app-1  | ./Run: error while loading shared libraries: libcurl.so.4: cannot open shared object file: No such file or directory
testpointfree-app-1 exited with code 127

My Package.swift:

// swift-tools-version:5.6
import PackageDescription

let package = Package(
    name: "TestPointfree",
    platforms: [
       .macOS(.v12)
    ],
    dependencies: [
        // 💧 A server-side Swift web framework.
        .package(url: "https://github.com/vapor/vapor.git", from: "4.0.0"),
        .package(url: "https://github.com/vapor/fluent.git", from: "4.0.0"),
        .package(url: "https://github.com/vapor/fluent-postgres-driver.git", from: "2.0.0"),
        .package(url: "https://github.com/pointfreeco/vapor-routing", from: "0.1.0"),
    ],
    targets: [
        .target(
            name: "App",
            dependencies: [
                .product(name: "Fluent", package: "fluent"),
                .product(name: "FluentPostgresDriver", package: "fluent-postgres-driver"),
                .product(name: "Vapor", package: "vapor"),
                .product(name: "VaporRouting", package: "vapor-routing"),
            ],
            swiftSettings: [
                // Enable better optimizations when building in Release configuration. Despite the use of
                // the `.unsafeFlags` construct required by SwiftPM, this flag is recommended for Release
                // builds. See <https://github.com/swift-server/guides/blob/main/docs/building.md#building-for-production> for details.
                .unsafeFlags(["-cross-module-optimization"], .when(configuration: .release))
            ]
        ),
        .executableTarget(name: "Run", dependencies: [.target(name: "App")]),
        .testTarget(name: "AppTests", dependencies: [
            .target(name: "App"),
            .product(name: "XCTVapor", package: "vapor"),
        ])
    ]
)

Project without this library runs as expected.

Documentation links aren't working

Just wanted to point out that the documentation urls point to a blank page. the one for the swift-url-routing do seem to work for me!

ObjectId.parser() instand -> UUID.parser()

ObjectId is from mongo db

public let wordsRouter = OneOf {
    Route(.case(WordsRoute.words)) {
        Path { "words2" }
    }
    
    Route(.case(WordsRoute.word)) {
        Path { "words2" }
        Path { Parse(.string) } // this how do it parse this like UUID.parser() *
        wordRouter
    }
}

func wordHandher(
    request: Request,
    wordID: String,
    route: WordRoute
) async throws -> AsyncResponseEncodable {
    switch route {
    case .fetch:
        guard let id = ObjectId.init(wordID) // * so I can remove this line 
        else {
            struct BadObjectId: Error {}
            throw BadObjectId()
        }
        
        return WordResponse(_id: id, englishWord: "english Word", englishDefinition: "English Definition", isReadFromNotification: false, isReadFromView: false, level: .beginner, url: router.url(for: .words(.word(id.hexString, .fetch))))
}

Vapor Abort doesn't work as expected.

I've replaced a part of the routes in an existing project using VaporRouting. I Replaced a single Vapour Controller by removing it from the registration in routes() and mounted a siteHandler and swift-parsing router that only covers the routes from that controller.
Now within a site handler when throwing for example a .badRequest error for example by using:
throw Abort(.badRequest, reason: "...")
A response is returned with status .notFound, I'm expecting this to be the route not being found. However my router did reach the end it's just the siteHandler that failed somewhere down the chain. I would expect my response to return this .badRequest error

How do I run on IOS for SiteRouter -> this target supports 9.0

I have create new SPM for my models so I can add server + iOS now when I add it iOS project I am getting this issue

// swift-tools-version: 5.6
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: "WordNotificationSiteRouter",
    platforms: [.macOS(.v12)], -> I also try add `.iOS(.v14)`
    products: [
        // Products define the executables and libraries a package produces,
        // and make them visible to other packages.
        .library(name: "WordNotificationSiteRouter", targets: ["WordNotificationSiteRouter"]),
    ],
    dependencies: [
        .package(url: "https://github.com/pointfreeco/vapor-routing", from: "0.1.1"),
        .package(url: "https://github.com/pointfreeco/swift-parsing", from: "0.9.2"),
        .package(url: "https://github.com/vapor/fluent-mongo-driver.git", from: "1.1.2"),
    ],
    targets: [
        .target(
            name: "WordNotificationSiteRouter",
            dependencies: [
                .product(name: "VaporRouting", package: "vapor-routing"),
                .product(name: "_URLRouting", package: "swift-parsing"),
                .product(name: "FluentMongoDriver", package: "fluent-mongo-driver"),
            ]),
        .testTarget(
            name: "WordNotificationSiteRouterTests",
            dependencies: ["WordNotificationSiteRouter"]),
    ]
)

Showing Recent Messages
The package product 'FluentKit' requires minimum platform version 13.0 for the iOS platform, but this target supports 9.0
The package product 'MongoKitten' requires minimum platform version 12.0 for the iOS platform, but this target supports 9.0
The package product 'Vapor' requires minimum platform version 13.0 for the iOS platform, but this target supports 9.0

Longer POST/PUT body fails inconsistently (tests attached)

I've created a test package with nearly the same SiteRoute used in vapor-routing's tests.

I demonstrate several things in these tests that I've observed in real-world use.

  1. Posting a short comment like the one in your test works fine every time
  2. Posting a medium-length comment usually works, but it will fail a few times out of 100 repetitions
  3. Posting a long comment almost always fails in the first twenty or so repetitions, and then it will succeed.
  4. The issue can be demonstrated on a route that parses the Comment, but also on a route that just accepts raw data. So the issue isn't related to JSONDecoder.
  5. Vapor's built-in router doesn't have this issue
  6. XCTVapor can't be used to demonstrate this issue, so I test by running my example server and making URLRequests against the running example server.

✅ vapor-routing-test.zip

I've tried many things, but I've had no luck fixing this issue myself. I thought it might have been related to this open issue: vapor/vapor#2682 but that issue appears to be caused by the use of data.getString(at: 0, length: data.capacity) in the example project attached to that issue.

There are a few important things you should know about running these tests

  • You need to run the server in Xcode before you run the tests
  • When you run the tests while the server is running, it will ask you if you want to replace the server. Click "Add" instead of replacing it.
  • The issue can be demonstrated just by running the tests once, but it is even more interesting when you run the tests repeatedly. If you haven't done this before, see this screenshot for instructions:

Screenshot 2023-02-03 at 5 43 26 PM

I like to pick Maximum Repetitions: 100, but 1,000 or even 10,000 will finish in a reasonable timeframe too.

More detailed JSON Decoding error message

The feedback for corrupt or unexpected data is lacking.

struct EditPoll: Codable, Equatable {
    let name: String
    let description: String
    let duration: Int
    let roomId: UUID
}

Route(.case(PollsRoute.create)) {
    Method.post
    Body(.json(EditPoll.self))
}

error: The data couldn’t be read because it isn’t in the correct format.

I think the following would print more specific information.

print(String(describing: jsonDecodingError))
``

How can I specify HTTP Method in my routes

Hi y'all!

I saw the fantastic video on the PointFree website demonstrating the ability of this library and I wanted to play around with it.
I've got myself a simple little Vapor app with a House entity and Room entity in order to have a one-to-many relation.

I'm setting up my router like this:

func setupRouter(app: Application) throws {
    let houseRouter = OneOf {
        Route(.case(HouseRoute.house)) {
            Path { "houses"; UUID.parser() }
        }
        Route(.case(HouseRoute.create)) {
            Path { "houses"; }
        }
    }
    app.mount(houseRouter, use: houseHandler)
}

And then I have my handler function looks like this:

func houseHandler(request: Request,
                  route: HouseRoute) async throws -> any AsyncResponseEncodable {
    switch route {
    case let .house(houseId: houseId):
        guard let house: House = try await House.query(on: request.db)
            .filter(\House.$id == houseId)
            .first() else {
            throw Abort(.notFound)
        }
        return HouseResponse(house: house)
    case .create:
        let house: House = try request.content.decode(House.self)
        try await house.create(on: request.db)
        return HouseResponse(house: house)
    }
}

When running the request with a POST HTTP method it fails with the following error:
image

However if I run the request with a GET HTTP method it succeeds even though a GET request shouldn't have a HTTP body according to the spec:
image

Now my question is how do I specify in the setupRouter method that the HouseRoute.create enum case maps to a POST HTTP method?

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.