### Install flyctl on Linux Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/fly.md Download and execute the official installation script to install `flyctl` on Linux. ```bash curl -L https://fly.io/install.sh | sh ``` -------------------------------- ### Build and Install Vapor Toolbox Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/digital-ocean.md Builds the Vapor Toolbox in release mode and installs the binary to the system's PATH. ```sh swift build -c release --disable-sandbox --enable-test-discovery sudo mv .build/release/vapor /usr/local/bin ``` -------------------------------- ### Example updated configure.swift method Source: https://github.com/vapor/docs/blob/main/docs/4.0/upgrading.md An example of an updated configure method for Vapor 4, showing database and migration configuration. ```swift import Fluent import FluentSQLiteDriver import Vapor // Called before your application initializes. public func configure(_ app: Application) throws { // Serves files from `Public/` directory // app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory)) // Configure SQLite database app.databases.use(.sqlite(.file("db.sqlite")), as: .sqlite) // Configure migrations app.migrations.add(CreateTodo()) try routes(app) } ``` -------------------------------- ### Starting a Vapor App with Supervisor Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/supervisor.md Commands to reload Supervisor configuration, add the application, and start it. ```sh supervisorctl reread supervisorctl add hello supervisorctl start hello ``` -------------------------------- ### Start Vapor Server with Default Command Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/server.md Use this command to start the Vapor server. It runs by default if no other commands are specified. ```swift swift run App serve ``` -------------------------------- ### Install Supervisor on Ubuntu Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/supervisor.md Installs Supervisor using apt-get on Ubuntu systems. ```sh sudo apt-get update sudo apt-get install supervisor ``` -------------------------------- ### Run Docker Compose Source: https://github.com/vapor/docs/blob/main/README.md Starts the Vapor project using Docker Compose. Ensure Docker and Docker Compose are installed. ```bash docker compose up ``` -------------------------------- ### Launch Fly Application Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/fly.md Run this command in your Vapor project's root directory to start the interactive setup for your Fly application. It helps configure settings like name, region, and database. ```bash fly launch ``` -------------------------------- ### Middleware Order Example Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/middleware.md Demonstrates the request and response flow through multiple middleware and a route handler. ```swift app.middleware.use(MiddlewareA()) app.middleware.use(MiddlewareB()) app.group(MiddlewareC()) { $0.get("hello") { req in "Hello, middleware." } } ``` -------------------------------- ### Install Latest Swift using Swiftly CLI Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/digital-ocean.md Installs the latest stable Swift release using the Swiftly CLI tool. Verify the installation by checking the Swift version. ```sh $ swiftly install latest Fetching the latest stable Swift release... Installing Swift 5.9.1 Downloaded 488.5 MiB of 488.5 MiB Extracting toolchain... Swift 5.9.1 installed successfully! $ swift --version Swift version 5.9.1 (swift-5.9.1-RELEASE) Target: x86_64-unknown-linux-gnu ``` -------------------------------- ### Example User Creation Request Source: https://github.com/vapor/docs/blob/main/docs/4.0/security/authentication.md An example HTTP request to create a new user via the POST /users endpoint. ```http POST /users HTTP/1.1 Content-Length: 97 Content-Type: application/json { "name": "Vapor", "email": "test@vapor.codes", "password": "secret42", "confirmPassword": "secret42" } ``` -------------------------------- ### Vapor Server Logs Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/digital-ocean.md Example of server logs indicating that the Vapor application has started and is listening for requests. ```sh [ NOTICE ] Server starting on http://0.0.0.0:8080 [ INFO ] GET / ``` -------------------------------- ### Run Migrations Command Line Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/overview.md Example of running Fluent migrations from the command line using the Vapor CLI. ```bash $ swift run App migrate Migrate Command: Prepare The following migration(s) will be prepared: + CreateGalaxy on default Would you like to continue? y/n> y Migration successful ``` -------------------------------- ### HTTP GET Request with Query String Source: https://github.com/vapor/docs/blob/main/docs/4.0/basics/content.md Example of an HTTP GET request including a query string. ```http GET /hello?name=Vapor HTTP/1.1 content-length: 0 ``` -------------------------------- ### Install Nginx on Fedora Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/nginx.md Use dnf to install Nginx on Fedora systems. ```sh sudo dnf install nginx ``` -------------------------------- ### Verify Swift Installation Source: https://github.com/vapor/docs/blob/main/docs/4.0/install/linux.md Checks the installed Swift version to confirm successful installation. ```sh $ swift --version Swift version 5.9.1 (swift-5.9.1-RELEASE) Target: x86_64-unknown-linux-gnu ``` -------------------------------- ### Install Nginx on Ubuntu Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/nginx.md Use apt-get to update package lists and install Nginx on Ubuntu systems. ```sh sudo apt-get update sudo apt-get install nginx ``` -------------------------------- ### Handle GET Request with User DTO for Response Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/model.md Example of handling a GET request to return users, transforming each user model into the GetUser DTO format for the response. ```swift app.get("users") { req async throws -> [GetUser] in // Fetch all users from the database. let users = try await User.query(on: req.db).all() return try users.map { // Convert each user to GET return type. try GetUser( id: user.requireID(), name: "\(user.firstName) \(user.lastName)" ) } } ``` -------------------------------- ### Install Vapor Toolbox with Homebrew Source: https://github.com/vapor/docs/blob/main/docs/4.0/install/macos.md Install the Vapor Toolbox CLI using Homebrew. This tool simplifies creating new Vapor projects. ```sh brew install vapor ``` -------------------------------- ### Run the Cowsay Command Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/commands.md Example of executing the custom Cowsay command with arguments and options. ```sh swift run App cowsay sup --eyes ^^ --tongue "U " ``` -------------------------------- ### Install Supervisor on Fedora Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/supervisor.md Installs Supervisor using dnf on Fedora systems. ```sh sudo dnf install supervisor ``` -------------------------------- ### Install flyctl on macOS Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/fly.md Use Homebrew to install the `flyctl` CLI on macOS. ```bash brew install flyctl ``` -------------------------------- ### Fetch All Planets using Content API Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/model.md Example of fetching an array of all planets using the Content API in a GET request handler. ```swift app.get("planets") { req async throws in // Return an array of all planets. try await Planet.query(on: req.db).all() } ``` -------------------------------- ### Start Vapor Server with Bind Flag Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/server.md This command starts the Vapor server and overrides the configured hostname and port using the bind flag. ```swift swift run App serve -b 0.0.0.0:80 ``` -------------------------------- ### Check Vapor Toolbox Installation Source: https://github.com/vapor/docs/blob/main/docs/4.0/install/macos.md Verify the Vapor Toolbox installation by displaying its help information. This confirms the CLI is accessible and functional. ```sh vapor --help ``` -------------------------------- ### Making a GET Request Source: https://github.com/vapor/docs/blob/main/docs/4.0/basics/client.md Use the `get` convenience method to make a GET request to a specified URL. The response contains the HTTP status, headers, and body. ```swift let response = try await req.client.get("https://httpbin.org/status/200") ``` -------------------------------- ### Build Vapor Toolbox from Source Source: https://github.com/vapor/docs/blob/main/docs/4.0/install/macos.md Build and install the Vapor Toolbox from its source code. This method is an alternative to using Homebrew and requires cloning the repository and using a Makefile. ```sh git clone https://github.com/vapor/toolbox.git cd toolbox git checkout make install ``` -------------------------------- ### Run Application and Dependencies Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/docker.md Starts the application and its dependent services (e.g., database) defined in the Docker Compose file. The app will be accessible on http://localhost:8080. ```shell docker compose up app ``` -------------------------------- ### Install Swift on Fedora Source: https://github.com/vapor/docs/blob/main/docs/4.0/install/linux.md Installs the Swift language package on Fedora systems using the DNF package manager. ```sh sudo dnf install swift-lang ``` -------------------------------- ### Install Heroku CLI using Homebrew Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/heroku.md Installs the Heroku command-line interface using Homebrew on macOS. ```bash brew tap heroku/brew && brew install heroku ``` -------------------------------- ### Supervisor Configuration for a Vapor App Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/supervisor.md Example Supervisor configuration file for a Vapor application named 'hello'. Ensure 'directory' points to your project's root. ```sh [program:hello] command=/home/vapor/hello/.build/release/App serve --env production directory=/home/vapor/hello/ user=vapor stdout_logfile=/var/log/supervisor/%(program_name)s-stdout.log stderr_logfile=/var/log/supervisor/%(program_name)s-stderr.log ``` -------------------------------- ### Leaf Folder Structure Example Source: https://github.com/vapor/docs/blob/main/docs/4.0/leaf/getting-started.md Illustrates the default folder structure for Leaf templates and other project assets. ```plaintext VaporApp ├── Package.swift ├── Resources │   ├── Views │   │   └── hello.leaf ├── Public │   ├── images (images resources) │   ├── styles (css resources) └── Sources    └── ... ``` -------------------------------- ### Manual Server Startup and Shutdown Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/server.md Manually start, shutdown, and wait for the server to complete its shutdown process. Ensure 'app' is configured before use. ```swift // Start Vapor's server. try app.server.start() // Request server shutdown. app.server.shutdown() // Wait for the server to shutdown. try app.server.onShutdown.wait() ``` -------------------------------- ### Configure Testing Method (In-Memory vs. Live Server) Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/testing.md Specify the testing method using `app.testing(method:)`. `.inMemory` is the default. `.running` starts a live HTTP server, optionally on a specific port. ```swift // Use programmatic testing. app.testing(method: .inMemory).test(...) // Run tests through a live HTTP server. app.testing(method: .running).test(...) // Run tests through a live HTTP server on a specific port. app.testing(method: .running(port: 8123)).test(...) ``` -------------------------------- ### Run Application with Trace Logging Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/docker.md Starts the application with trace-level logging enabled by setting the LOG_LEVEL environment variable. This provides the most granular logging output. ```shell LOG_LEVEL=trace docker-compose up app ``` -------------------------------- ### Create Procfile for Heroku Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/heroku.md Creates a 'Procfile' that tells Heroku how to run your Vapor application. This example configures it to serve in production mode, listening on all interfaces and the port provided by Heroku. ```bash echo "web: App serve --env production --hostname 0.0.0.0 --port \$PORT" > Procfile ``` -------------------------------- ### Run Multiple Services Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/docker.md Starts multiple specified services (e.g., app and db) along with their dependencies. This ensures all necessary services are running. ```shell docker-compose up app db ``` -------------------------------- ### Create a Cowsay Command with Arguments and Options Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/commands.md An example of a custom command that accepts a message argument and optional eyes/tongue options. ```swift import Vapor struct Cowsay: AsyncCommand { struct Signature: CommandSignature { @Argument(name: "message") var message: String @Option(name: "eyes", short: "e") var eyes: String? @Option(name: "tongue", short: "t") var tongue: String? } var help: String { "Generates ASCII picture of a cow with a message." } func run(using context: CommandContext, signature: Signature) async throws { let eyes = signature.eyes ?? "oo" let tongue = signature.tongue ?? " " let cow = #""" < $M > \ ^__^ \ ($E)\_______ (__)\ )\/\ $T ||----w | || || """#.replacingOccurrences(of: "$M", with: signature.message) .replacingOccurrences(of: "$E", with: eyes) .replacingOccurrences(of: "$T", with: tongue) context.console.print(cow) } } ``` -------------------------------- ### Display Help for Vapor Commands Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/commands.md Shows how to get help information for Vapor's default commands and specific commands. ```sh swift run App --help ``` ```sh swift run App serve --help ``` -------------------------------- ### Eager Loaded JSON Response Example Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/overview.md Example of the JSON response structure after successfully eager loading the stars relation for galaxies. ```json [ { "id": ..., "name": "Milky Way", "stars": [ { "id": ..., "name": "Sun", "galaxy": { "id": ... } } ] } ] ``` -------------------------------- ### Navigate to Project Directory Source: https://github.com/vapor/docs/blob/main/docs/4.0/getting-started/hello-world.md Change into the newly created project directory. ```sh cd hello ``` -------------------------------- ### Basic Authentication Request Example Source: https://github.com/vapor/docs/blob/main/docs/4.0/security/authentication.md Example of a POST request to the /login endpoint using Basic authentication with a username and password encoded in the Authorization header. ```http POST /login HTTP/1.1 Authorization: Basic dGVzdEB2YXBvci5jb2RlczpzZWNyZXQ0Mg== ``` -------------------------------- ### Start In-Process Queue Jobs Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/queues.md Enable queue jobs to run within the same process as your application. This is a convenience for development or simpler deployments. ```swift try app.queues.startInProcessJobs(on: .default) ``` -------------------------------- ### Perform Integration Test with Database Setup Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/testing.it.md Execute an integration test using the `withAppIncludingDB` helper to ensure a fresh database state for each test. ```swift @Test func mioTestDiIntegrazioneDB() async throws { try await withAppIncludingDB { app in try await app.testing().test(.GET, "hello") { res async in #expect(res.status == .ok) #expect(res.body.string == "Hello, world!") } } } ``` -------------------------------- ### Configure Leaf Views Source: https://github.com/vapor/docs/blob/main/docs/4.0/upgrading.md Leaf is now configured using the `app.views` property, simplifying view rendering setup. ```swift app.views.use(.leaf) ``` -------------------------------- ### HTTP GET Request without Query String Source: https://github.com/vapor/docs/blob/main/docs/4.0/basics/content.md Example of an HTTP GET request where the query string is omitted. ```http GET /hello HTTP/1.1 content-length: 0 ``` -------------------------------- ### Basic Authentication HTTP Request Example Source: https://github.com/vapor/docs/blob/main/docs/4.0/security/authentication.md Example of an HTTP GET request using Basic Authentication. The Authorization header contains a Base64 encoded username and password. ```http GET /me HTTP/1.1 Authorization: Basic dGVzdDpzZWNyZXQ= ``` -------------------------------- ### Implement BasicAuthenticator Source: https://github.com/vapor/docs/blob/main/docs/4.0/security/authentication.md Create a UserAuthenticator struct conforming to BasicAuthenticator. This example hard-codes credentials for verification. ```swift import Vapor struct UserAuthenticator: BasicAuthenticator { typealias User = App.User func authenticate( basic: BasicAuthorization, for request: Request ) -> EventLoopFuture { if basic.username == "test" && basic.password == "secret" { request.auth.login(User(name: "Vapor")) } return request.eventLoop.makeSucceededFuture(()) } } ``` -------------------------------- ### Configure Model Middleware Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/model.md Example of how to register a custom `ModelMiddleware` with the application's database configuration for a specific database driver. ```swift // Example of configuring model middleware. app.databases.middleware.use(PlanetMiddleware(), on: .psql) ``` -------------------------------- ### Example HTTP Request for JWT Verification Source: https://github.com/vapor/docs/blob/main/docs/4.0/security/jwt.md An example HTTP GET request including the Authorization header with a Bearer token. This is how a client would send a JWT to your application for verification. ```http GET /me HTTP/1.1 authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ2YXBvciIsImV4cCI6NjQwOTIyMTEyMDAsImFkbWluIjp0cnVlfQ.lS5lpwfRNSZDvpGQk6x5JI1g40gkYCOWqbc3J_ghowo ``` -------------------------------- ### Enable Auto-Migration on Serve Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/migration.md Automatically run migrations before the application starts by using the `--auto-migrate` flag with the `serve` command. ```sh swift run App serve --auto-migrate ``` -------------------------------- ### Basic Route Handler with Request Parameters Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/request.md Demonstrates accessing route parameters from the Request object in a simple GET route. ```swift app.get("hello", ":name") { req -> String in let name = req.parameters.get("name")! return "Hello, \(name)!" } ``` -------------------------------- ### Helper Function for Database Integration Tests Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/testing.it.md A helper function to manage application setup, database migrations, and teardown for integration tests. ```swift private func withAppIncludingDB(_ test: (Application) async throws -> ()) async throws { let app = try await Application.make(.testing) do { try await configure(app) try await app.autoMigrate() try await test(app) try await app.autoRevert() } catch { try? await app.autoRevert() try await app.asyncShutdown() throw error } try await app.asyncShutdown() } ``` -------------------------------- ### Create New Vapor Project Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/digital-ocean.md Creates a new Vapor project named 'HelloWorld' using a bare-bones template. ```sh vapor new HelloWorld -n ``` -------------------------------- ### Serve Local Documentation Source: https://github.com/vapor/docs/blob/main/README.md Serves the generated documentation site locally for preview. Use Python 3's http.server module. ```bash python3 -m http.server --directory site ``` -------------------------------- ### Model Lifecycle Middleware (Create Event - Async/Await) Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/model.md Example of an `AsyncModelMiddleware` that capitalizes a planet's name before creation and prints a message after creation. This uses the `async/await` pattern. ```swift struct PlanetMiddleware: AsyncModelMiddleware { func create(model: Planet, on db: Database, next: AnyAsyncModelResponder) async throws { // The model can be altered here before it is created. model.name = model.name.capitalized() try await next.create(model, on: db) // Once the planet has been created, the code // here will be executed. print ("Planet \(model.name) was created") } } ``` -------------------------------- ### Query All Planets Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/model.md Use the static `query(on:)` method to get a query builder and then call `all()` to retrieve all instances of a model. ```swift Planet.query(on: database).all() ``` -------------------------------- ### Create and Fetch Models with Filters and Joins Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/query.md An example of Fluent's query API demonstrating filtering by type, sorting by name, and eager loading a relationship. ```swift let planets = try await Planet.query(on: database) .filter(\.$\.type == .gasGiant) .sort(\.$\.name) .with(\.$\.star) .all() ``` -------------------------------- ### Detecting Environment and Bootstrapping Logging Source: https://github.com/vapor/docs/blob/main/docs/4.0/basics/environment.md The entrypoint typically uses Environment.detect() to determine the environment and then bootstraps the logging system. ```swift @main enum Entrypoint { static func main() async throws { var env = try Environment.detect() try LoggingSystem.bootstrap(from: &env) let app = Application(env) defer { app.shutdown() } try await configure(app) try await app.runFromAsyncMainEntrypoint() } } ``` -------------------------------- ### Create a Simple Table Schema Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/schema.md An example of creating a new table named 'planets' with an auto-incrementing ID and a required string field for 'name'. ```swift try await database.schema("planets") .id() .field("name", .string, .required) .create() ``` -------------------------------- ### Initialize Test Application with `withApp` Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/testing.it.md Use `withApp` to manage the lifecycle of your test application. Pass your application's `configure` method to ensure routes are registered. ```swift import XCTest import Vapor @Test func qualcheTest() async throws { try await withApp(configure: configure) { app in // il tuo test } } ``` -------------------------------- ### Configure Password Hasher Source: https://github.com/vapor/docs/blob/main/docs/4.0/security/passwords.md Use `app.passwords.use(...)` to configure the application's password hasher. This is typically done during application setup. ```swift import Vapor app.passwords.use(...) ``` -------------------------------- ### Initializing Environment with Custom Arguments Source: https://github.com/vapor/docs/blob/main/docs/4.0/basics/environment.md Manually initialize an Environment instance with a specific name and an array of arguments to simulate command-line input, useful for testing. ```swift let env = Environment(name: "testing", arguments: ["vapor"]) ``` -------------------------------- ### Install Nginx on CentOS/Amazon Linux Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/nginx.md Use yum to install Nginx on CentOS and Amazon Linux distributions. ```sh sudo yum install nginx ``` -------------------------------- ### Create User Schema Migration Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/schema.md An example of a basic schema migration to create a 'users' table with 'id' and 'name' fields. This migration is designed to be stringly typed for robustness. ```swift struct UserMigration: AsyncMigration { func prepare(on database: Database) async throws { try await database.schema("users") .field("id", .uuid, .identifier(auto: false)) .field("name", .string, .required) .create() } func revert(on database: Database) async throws { try await database.schema("users").delete() } } ``` -------------------------------- ### JSON Response for Created Star Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/overview.md Example JSON response after successfully creating a star, showing its unique ID, name, and the associated galaxy information. ```json { "id": ..., "name": "Sun", "galaxy": { "id": ... } } ``` -------------------------------- ### Vapor Project Package Manifest Source: https://github.com/vapor/docs/blob/main/docs/4.0/getting-started/spm.md This is an example of a Package.swift manifest file for a Vapor project. It defines the Swift tools version, platforms, dependencies (including Vapor itself), and targets for the application and its tests. ```swift // swift-tools-version:5.8 import PackageDescription let package = Package( name: "MyApp", platforms: [ .macOS(.v12) ], dependencies: [ .package(url: "https://github.com/vapor/vapor.git", from: "4.76.0"), ], targets: [ .executableTarget( name: "App", dependencies: [ .product(name: "Vapor", package: "vapor") ] ), .testTarget(name: "AppTests", dependencies: [ .target(name: "App"), .product(name: "XCTVapor", package: "vapor"), ]) ] ) ``` -------------------------------- ### Install Supervisor on CentOS/Amazon Linux Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/supervisor.md Installs Supervisor using yum on CentOS and Amazon Linux systems. ```sh sudo yum install supervisor ``` -------------------------------- ### Import Fluent Source: https://github.com/vapor/docs/blob/main/docs/4.0/upgrading.md Fluent is now database agnostic. Import `Fluent` instead of specific database drivers. ```diff - import FluentMySQL + import Fluent ``` -------------------------------- ### Model Lifecycle Middleware (Create Event - Future) Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/model.md Example of a `ModelMiddleware` that capitalizes a planet's name before creation and prints a message after creation. This uses the `EventLoopFuture` pattern. ```swift // Example middleware that capitalizes names. struct PlanetMiddleware: ModelMiddleware { func create(model: Planet, on db: Database, next: AnyModelResponder) -> EventLoopFuture { // The model can be altered here before it is created. model.name = model.name.capitalized() return next.create(model, on: db).map { // Once the planet has been created, the code // here will be executed. print ("Planet \(model.name) was created") } } } ``` -------------------------------- ### Configure PostgreSQL from URL Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/overview.md Configure PostgreSQL using a database connection string. ```swift try app.databases.use(.postgres(url: ""), as: .psql) ``` -------------------------------- ### GetUser DTO for GET Responses Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/model.md Defines the structure for GET /users responses, including a computed 'name' field. ```swift // Structure of GET /users response. struct GetUser: Content { var id: UUID var name: String } ``` -------------------------------- ### Open Project in Xcode Source: https://github.com/vapor/docs/blob/main/docs/4.0/getting-started/hello-world.md Open the project's Package.swift file in Xcode to begin dependency resolution and scheme selection. ```sh open Package.swift ``` -------------------------------- ### Define a GET Route Source: https://github.com/vapor/docs/blob/main/docs/4.0/basics/routing.md Register a handler for a specific GET request path. The path components are provided as string arguments. ```swift app.get("hello", "vapor") { req in return "Hello, vapor!" } ``` -------------------------------- ### Configure Redis Queue Driver Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/queues.md Configure the Queues system to use the Redis driver by providing the connection URL. This setup is typically done in your application's configure.swift file. ```swift import QueuesRedisDriver try app.queues.use(.redis(url: "redis://127.0.0.1:6379")) ``` -------------------------------- ### Example Bearer Authentication HTTP Request Source: https://github.com/vapor/docs/blob/main/docs/4.0/security/authentication.md This is an example of an HTTP request using Bearer authentication, sending a token in the Authorization header. ```http GET /me HTTP/1.1 Authorization: Bearer foo ``` -------------------------------- ### Enable TLS Server Configuration Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/server.md Enable TLS (SSL) on the server by providing certificate chain and private key. Requires importing `NIOSSL` and potentially adding it as a dependency. ```swift // Enable TLS. app.http.server.configuration.tlsConfiguration = .makeServerConfiguration( certificateChain: try NIOSSLCertificate.fromPEMFile("/path/to/cert.pem").map { .certificate($0) }, privateKey: .privateKey(try NIOSSLPrivateKey(file: "/path/to/key.pem", format: .pem)) ) ``` -------------------------------- ### Create a Postgres Database on Fly Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/fly.md Run `fly pg create` to set up a new PostgreSQL database application on Fly.io. This command provisions a Fly app capable of hosting databases. ```bash fly pg create ``` -------------------------------- ### Add New User Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/digital-ocean.md Create a new user and grant it sudo privileges. ```sh adduser vapor usermod -aG sudo vapor ``` -------------------------------- ### Use Writable Service on Application Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/services.md Shows how to set and retrieve a custom writable service configuration (`myConfiguration`) on the `Application` instance. This demonstrates the usage of the `Application` extension for managing stateful services. ```swift app.myConfiguration = .init(apiKey: ...) print(app.myConfiguration?.apiKey) ``` -------------------------------- ### Registering a GET Route Source: https://github.com/vapor/docs/blob/main/docs/4.0/basics/routing.md Registers a route that responds to a GET request for the specified URI path. The handler closure is executed when a matching request is received. ```swift app.get("foo", "bar", "baz") { req in ... } ``` -------------------------------- ### Start Scheduler Worker Command Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/queues.md Run this command in your terminal to start the scheduler worker process. Ensure this worker remains running in production environments. ```sh swift run App queues --scheduled ``` -------------------------------- ### Create a new Vapor project Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/fly.md Use the Vapor toolbox to create a new Vapor application, replacing `app-name` with your desired application name. ```bash vapor new app-name ``` -------------------------------- ### Initialize Testable Application Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/testing.md Initialize an Application instance with the .testing environment and ensure app.shutdown() is called using defer. ```swift let app = Application(.testing) defer { app.shutdown() } try configure(app) ``` -------------------------------- ### Example Signed JWT Response Source: https://github.com/vapor/docs/blob/main/docs/4.0/security/jwt.md An example of a JSON response containing a signed JWT. This token can be decoded and verified using tools like the jwt.io debugger. ```json { "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ2YXBvciIsImV4cCI6NjQwOTIyMTEyMDAsImFkbWluIjp0cnVlfQ.lS5lpwfRNSZDvpGQk6x5JI1g40gkYCOWqbc3J_ghowo" } ``` -------------------------------- ### Send GET Request and Assert Response Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/testing.it.md Send a GET request to a specific route and assert the response status and body using `app.testing().test()` within `withApp`. ```swift import XCTest import Vapor @Test("Test Hello World Route") func helloWorld() async throws { try await withApp(configure: configure) { app in try await app.testing().test(.GET, "hello") { res async in #expect(res.status == .ok) #expect(res.body.string == "Hello, world!") } } } ``` -------------------------------- ### Manage Nginx Service Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/nginx.md Commands to stop, start, or restart the Nginx service. ```sh sudo service nginx stop sudo service nginx start sudo service nginx restart ``` -------------------------------- ### Serve Assets from Public Directory Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/middleware.md Use FileMiddleware to serve static assets like stylesheets and images from your project's Public directory. Ensure the public directory is correctly configured. ```swift let file = FileMiddleware(publicDirectory: app.directory.publicDirectory) app.middleware.use(file) ``` -------------------------------- ### User Model Definition Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/model.md Abridged User model definition for reference in DTO examples. ```swift // Abridged user model for reference. final class User: Model { @ID(key: .id) var id: UUID? @Field(key: "first_name") var firstName: String @Field(key: "last_name") var lastName: String } ``` -------------------------------- ### Initialize Git Repository Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/heroku.md Initializes a new Git repository in your project directory if one does not already exist. ```bash git init ``` -------------------------------- ### Create New Vapor Project Source: https://github.com/vapor/docs/blob/main/docs/4.0/getting-started/hello-world.md Use the Vapor Toolbox to create a new project. The '-n' flag uses a bare-bones template. ```sh vapor new hello -n ``` -------------------------------- ### Implement Bearer Authenticator (Vapor) Source: https://github.com/vapor/docs/blob/main/docs/4.0/security/authentication.md Example of a Vapor authenticator conforming to BearerAuthenticator. It verifies a hard-coded token. ```swift import Vapor struct UserAuthenticator: BearerAuthenticator { typealias User = App.User func authenticate( bearer: BearerAuthorization, for request: Request ) -> EventLoopFuture { if bearer.token == "foo" { request.auth.login(User(name: "Vapor")) } return request.eventLoop.makeSucceededFuture(()) } } ``` -------------------------------- ### Run Migrations from Command Line Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/migration.md Execute the `migrate` command in your terminal to apply pending database migrations. Confirmation is required before execution. ```sh swift run App migrate ``` -------------------------------- ### Require Authenticated User Source: https://github.com/vapor/docs/blob/main/docs/4.0/security/authentication.md Use `req.auth.require(_:)` to get the currently authenticated user. This will throw an error if no user is authenticated. ```swift let user: User = try req.auth.require(User.self) print(user.name) // String ``` -------------------------------- ### Build and Run Vapor Project on Linux Source: https://github.com/vapor/docs/blob/main/docs/4.0/getting-started/hello-world.md Use the Swift Package Manager to build and run the Vapor project from the terminal on Linux or other OSes. ```sh swift run ``` -------------------------------- ### HTTP Response for Successful Decoding Source: https://github.com/vapor/docs/blob/main/docs/4.0/basics/content.md Example HTTP response after successfully decoding the query string and processing the route. ```http HTTP/1.1 200 OK content-length: 12 Hello, Vapor ``` -------------------------------- ### Check Swift Version Source: https://github.com/vapor/docs/blob/main/docs/4.0/install/macos.md Verify that Swift is installed and check its version. Vapor 4 requires Swift 5.9 or greater. ```sh swift --version ``` ```sh swift-driver version: 1.75.2 Apple Swift version 5.8 (swiftlang-5.8.0.124.2 clang-1403.0.22.11.100) Target: arm64-apple-macosx13.0 ``` -------------------------------- ### Configure SQLite for Testing Environment Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/testing.it.md Set up an in-memory SQLite database when the application environment is set to testing. ```swift public func configure(_ app: Application) async throws { // Altre configurazioni... if app.environment == .testing { app.databases.use(.sqlite(.memory), as: .sqlite) } else { app.databases.use(.sqlite(.file("db.sqlite")), as: .sqlite) } } ``` -------------------------------- ### Count Database Records Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/query.md Use the `count` method to get the total number of records in a table. This method returns an integer. ```swift Planet.query(on: database).count() ``` -------------------------------- ### Serve Assets from Bundle (iOS/macOS) Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/middleware.md For applications packaged within an Xcode project (e.g., iOS apps), use this initializer for FileMiddleware. It requires using Folder References in Xcode to maintain the resource folder structure. ```swift let file = try FileMiddleware(bundle: .main, publicDirectory: "Public") ``` -------------------------------- ### Use Custom Server with Leading-Dot Syntax Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/server.md Registers a custom server provider using leading-dot syntax for cleaner configuration. ```swift extension Application.Servers.Provider { static var myServer: Self { .init { $0.servers.use { app in MyServer() } } } } app.servers.use(.myServer) ``` -------------------------------- ### Prompt User for Input in a Command Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/commands.md Demonstrates how to use the console to ask for user input within a command's execution. ```swift let name = context.console.ask("What is your \"name\", color: .blue)?") context.console.print("Hello, \(name) 👋") ``` -------------------------------- ### Create Promise from Application Source: https://github.com/vapor/docs/blob/main/docs/4.0/basics/async.md Illustrates how to obtain an event loop from the application and use it to create a promise. This is typically done outside of route closures. ```swift app.eventLoopGroup.next().makePromise(of: ...) ``` -------------------------------- ### Validate Nginx Installation Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/nginx.md Access your server's IP address or domain name in a web browser to verify Nginx is running. ```text http://server_domain_name_or_IP ``` -------------------------------- ### Send a Simple Test Request Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/testing.md Use the test method to send a GET request to your application and assert the response status and body. ```swift try app.test(.GET, "hello") { res in XCTAssertEqual(res.status, .ok) XCTAssertEqual(res.body.string, "Hello, world!") } ``` -------------------------------- ### Create a Query Builder for a Model Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/query.md Demonstrates two ways to create a query builder for the Planet model: using the static `query` method or the database's `query` method. ```swift // An example of Fluent's query API. let planets = try await Planet.query(on: database) .filter(\.$\.type == .gasGiant) .sort(\.$\.name) .with(\.$\.star) .all() ``` ```swift // Also creates a query builder. database.query(Planet.self) ``` -------------------------------- ### Run Application Detached Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/docker.md Starts the application and its dependencies in detached mode (background). This allows you to continue using your terminal while the services run. ```shell docker compose up --detach app ``` -------------------------------- ### Start In-Process Scheduled Jobs Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/queues.md Enable scheduled jobs to run within the same process as your application. This complements the in-process job execution. ```swift try app.queues.startScheduledJobs() ``` -------------------------------- ### Update Middleware Configuration Source: https://github.com/vapor/docs/blob/main/docs/4.0/upgrading.md Middleware is now added using `app.middleware.use()`. Initialize middleware before registering. ```diff let corsMiddleware = CORSMiddleware(configuration: ...) - var middleware = MiddlewareConfig() - middleware.use(corsMiddleware) + app.middleware.use(corsMiddleware) - services.register(middlewares) ``` ```diff - middleware.use(ErrorMiddleware.self) + app.middleware.use(ErrorMiddleware.default(environment: app.environment)) ``` -------------------------------- ### HTTP Request for Authenticated User Source: https://github.com/vapor/docs/blob/main/docs/4.0/security/authentication.md Example HTTP request to the /me endpoint, demonstrating how to include the authorization token in the Bearer header. ```http GET /me HTTP/1.1 Authorization: Bearer ``` -------------------------------- ### Configure MySQL Database with Connection String Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/overview.md Configure the MySQL database connection by parsing credentials from a connection string. ```swift try app.databases.use(.mysql(url: ""), as: .mysql) ``` -------------------------------- ### Implement Async Bearer Authenticator (Vapor) Source: https://github.com/vapor/docs/blob/main/docs/4.0/security/authentication.md Example of a Vapor authenticator conforming to AsyncBearerAuthenticator using async/await. It verifies a hard-coded token. ```swift import Vapor struct UserAuthenticator: AsyncBearerAuthenticator { typealias User = App.User func authenticate( bearer: BearerAuthorization, for request: Request ) async throws { if bearer.token == "foo" { request.auth.login(User(name: "Vapor")) } } } ``` -------------------------------- ### Configure PostgreSQL Database Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/overview.md Configure PostgreSQL credentials with Fluent using app.databases.use in configure.swift. ```swift import Fluent import FluentPostgresDriver app.databases.use( .postgres( configuration: .init( hostname: "localhost", username: "vapor", password: "vapor", database: "vapor", tls: .disable ) ), as: .psql ) ``` -------------------------------- ### Echo Received Text Messages Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/websockets.md An example of echoing received text messages back to the sender using the provided WebSocket instance. ```swift ws.onText { ws, text in ws.send(text) } ``` -------------------------------- ### Connect to App Instances via SSH Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/fly.md Use this command to establish an SSH connection to your application's instances for debugging or management purposes. ```bash fly ssh console -s ``` -------------------------------- ### Define a Basic Migration Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/migration.md Implement the `Migration` protocol for standard asynchronous operations. The `prepare` method defines changes, and `revert` undoes them. ```swift struct MyMigration: Migration { func prepare(on database: any Database) -> EventLoopFuture { // Make a change to the database. } func revert(on database: any Database) -> EventLoopFuture { // Undo the change made in `prepare`, if possible. } } ``` -------------------------------- ### Stop Detached Containers Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/docker.md Stops all containers defined in the Docker Compose file that were started in detached mode. This is the recommended way to shut down services. ```shell docker-compose down ``` -------------------------------- ### Basic Vapor App Test Structure Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/testing.md Import VaporTesting and Testing, and define a test suite with @Suite and @Test annotations. ```swift @testable import App import VaporTesting import Testing @Suite("App Tests") struct AppTests { @Test("Test Stub") func stub() async throws { // Test here. } } ``` -------------------------------- ### Initialize Session with Data Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/sessions.md Use this HTTP request to initialize a session by adding data to it. ```http GET /set/vapor HTTP/1.1 content-length: 0 ``` -------------------------------- ### List Docker Images Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/docker.md Lists all Docker images on your system, including the newly built application image. This helps verify that the build process was successful. ```shell docker image ls ``` -------------------------------- ### Use a Custom Tag in Leaf Source: https://github.com/vapor/docs/blob/main/docs/4.0/leaf/custom-tags.md Once registered, custom tags can be used directly within your Leaf templates. This example shows how to use the #now() tag. ```leaf The time is #now() ``` -------------------------------- ### Create and Complete a Promise Source: https://github.com/vapor/docs/blob/main/docs/4.0/basics/async.md Demonstrates how to create a promise for a String and then complete it successfully or with an error. Promises require an EventLoop to be initialized and ensure completion actions are returned to the event loop. ```swift let eventLoop: EventLoop // Create a new promise for some string. let promiseString = eventLoop.makePromise(of: String.self) print(promiseString) // EventLoopPromise print(promiseString.futureResult) // EventLoopFuture // Completes the associated future. promiseString.succeed("Hello") // Fails the associated future. promiseString.fail(...) ``` -------------------------------- ### Configure MySQL Database with Credentials Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/overview.md Configure the MySQL database connection using hostname, username, password, and database name. ```swift import Fluent import FluentMySQLDriver app.databases.use(.mysql(hostname: "localhost", username: "vapor", password: "vapor", database: "vapor"), as: .mysql) ``` -------------------------------- ### Test Vapor Application with Curl Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/digital-ocean.md Tests if the Vapor application is running by sending an HTTP GET request to the server's IP address and port. ```sh $ curl http://134.122.126.139:8080 It works! ``` -------------------------------- ### Create .swift-version file Source: https://github.com/vapor/docs/blob/main/docs/4.0/deploy/heroku.md Creates a '.swift-version' file in your project's root directory, specifying the Swift version Heroku should use for building your application. Replace '5.8.1' with your project's required Swift version. ```bash echo "5.8.1" > .swift-version ``` -------------------------------- ### Run Queue Worker as a Process Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/queues.md Start a dedicated queue worker process from the command line. You can specify a particular queue to process, like 'emails'. ```bash swift run App queues swift run App queues --queue emails ``` -------------------------------- ### Decoded and Verified JWT Payload Example Source: https://github.com/vapor/docs/blob/main/docs/4.0/security/jwt.md The structure of the payload after a JWT has been successfully decoded and verified by the Vapor application. This shows the original data that was signed. ```swift TestPayload( subject: "vapor", expiration: 4001-01-01 00:00:00 +0000, isAdmin: true ) ``` -------------------------------- ### Render a Leaf View (Async/Await) Source: https://github.com/vapor/docs/blob/main/docs/4.0/leaf/getting-started.md Render a Leaf template using the async/await syntax. Ensure the template file exists in the `Resources/Views` directory. ```swift app.get("hello") { req async throws -> View in return try await req.view.render("hello", ["name": "Leaf"]) } ``` -------------------------------- ### Handle PATCH Request with User DTO Source: https://github.com/vapor/docs/blob/main/docs/4.0/fluent/model.md Example of handling a PATCH request to update a user, using the PatchUser DTO for decoding and updating the model. ```swift app.patch("users", ":id") { req async throws -> User in // Decode the request data. let patch = try req.content.decode(PatchUser.self) // Fetch the desired user from the database. guard let user = try await User.find(req.parameters.get("id"), on: req.db) else { throw Abort(.notFound) } // If first name was supplied, update it. if let firstName = patch.firstName { user.firstName = firstName } // If new last name was supplied, update it. if let lastName = patch.lastName { user.lastName = lastName } // Save the user and return it. try await user.save(on: req.db) return user } ``` -------------------------------- ### Define a Basic Custom AsyncCommand Source: https://github.com/vapor/docs/blob/main/docs/4.0/advanced/commands.md Illustrates the basic structure for creating a custom command conforming to AsyncCommand. ```swift import Vapor struct HelloCommand: AsyncCommand { struct Signature: CommandSignature { } var help: String { "Says hello" } func run(using context: CommandContext, signature: Signature) async throws { context.console.print("Hello, world!") } } ``` -------------------------------- ### Blocking Sleep on Event Loop Source: https://github.com/vapor/docs/blob/main/docs/4.0/basics/async.md This example shows a direct call to `sleep` on an event loop thread, which will block all incoming requests handled by that loop. ```swift app.get("hello") { req in /// Puts the event loop's thread to sleep. sleep(5) /// Returns a simple string once the thread re-awakens. return "Hello, world!" } ```