Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,13 @@ let package = Package(
.product(name: "SwiftParser", package: "swift-syntax"),
]
),
.testTarget(
name: "RoutingTests",
dependencies: [
"Routing",
.product(name: "AWSLambdaEvents", package: "swift-aws-lambda-events"),
]
),
.testTarget(
name: "DynamoQueriesMacrosTests",
dependencies: [
Expand Down
18 changes: 18 additions & 0 deletions Sources/Routing/Errors/HeaderError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//
// HeaderError.swift
//
// Copyright © 2026 SongShift, LLC. All rights reserved.
//

/// Thrown by `Headers.require` when a header is absent.
/// `Router.handle` maps it to `400 Bad Request`.
public enum HeaderError: Error {
case missing(String)

public var message: String {
switch self {
case let .missing(name):
"Missing required header: \(name)"
}
}
}
21 changes: 21 additions & 0 deletions Sources/Routing/Errors/PathParameterError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//
// PathParameterError.swift
//
// Copyright © 2026 SongShift, LLC. All rights reserved.
//

/// Thrown by `PathParameters.require` when a parameter is absent or not convertible.
/// `Router.handle` maps it to `400 Bad Request`.
public enum PathParameterError: Error {
case missing(String)
case invalidType(name: String, value: String, expectedType: String)

public var message: String {
switch self {
case let .missing(name):
"Missing required path parameter: \(name)"
case let .invalidType(name, value, expectedType):
"Path parameter '\(name)' value '\(value)' is not a valid \(expectedType)"
}
}
}
21 changes: 21 additions & 0 deletions Sources/Routing/Errors/QueryParameterError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
//
// QueryParameterError.swift
//
// Copyright © 2026 SongShift, LLC. All rights reserved.
//

/// Thrown by `QueryParameters.require` when a parameter is absent or not convertible.
/// `Router.handle` maps it to `400 Bad Request`.
public enum QueryParameterError: Error {
case missing(String)
case invalidType(name: String, value: String, expectedType: String)

public var message: String {
switch self {
case let .missing(name):
"Missing required query parameter: \(name)"
case let .invalidType(name, value, expectedType):
"Query parameter '\(name)' value '\(value)' is not a valid \(expectedType)"
}
}
}
18 changes: 18 additions & 0 deletions Sources/Routing/Errors/RequestBodyError.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//
// RequestBodyError.swift
//
// Copyright © 2026 SongShift, LLC. All rights reserved.
//

/// Thrown when a request body cannot be decoded into a handler's `Body` type.
/// `Router.handle` maps it to `400 Bad Request`.
public enum RequestBodyError: Error {
case decodingFailed(any Error)

public var message: String {
switch self {
case let .decodingFailed(error):
"The request body could not be decoded."
}
}
}
11 changes: 0 additions & 11 deletions Sources/Routing/Headers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,3 @@ public struct Headers: Sendable {
Set(self.values.keys)
}
}

public enum HeaderError: Error {
case missing(String)

public var message: String {
switch self {
case let .missing(name):
"Missing required header: \(name)"
}
}
}
14 changes: 0 additions & 14 deletions Sources/Routing/PathParameters.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,17 +51,3 @@ public struct PathParameters: Sendable {
self.values[name] = value
}
}

public enum PathParameterError: Error {
case missing(String)
case invalidType(name: String, value: String, expectedType: String)

public var message: String {
switch self {
case let .missing(name):
"Missing required path parameter: \(name)"
case let .invalidType(name, value, expectedType):
"Path parameter '\(name)' value '\(value)' is not a valid \(expectedType)"
}
}
}
14 changes: 0 additions & 14 deletions Sources/Routing/QueryParameters.swift
Original file line number Diff line number Diff line change
Expand Up @@ -116,17 +116,3 @@ public struct QueryParameters: Sendable {
Set(self.values.keys)
}
}

public enum QueryParameterError: Error {
case missing(String)
case invalidType(name: String, value: String, expectedType: String)

public var message: String {
switch self {
case let .missing(name):
"Missing required query parameter: \(name)"
case let .invalidType(name, value, expectedType):
"Query parameter '\(name)' value '\(value)' is not a valid \(expectedType)"
}
}
}
33 changes: 28 additions & 5 deletions Sources/Routing/Router.swift
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,21 @@ public final class RouterBuilder<R: Routable, Engine: RoutingKit.RouterBuilder>
}
}

/// Register a handler at a routing key, JSON-decoding the request body into
/// `Body` before invoking the handler.
///
/// Available for any `Routable` whose `body: Data` carries JSON. The HTTP and
/// WebSocket adapters both qualify.
public func on<Body: Decodable & Sendable>(
_ key: [String],
body: Body.Type,
use handler: @Sendable @escaping (R, Body, Logger) async throws -> RouteResponse
) {
self.on(key) { request, logger in
try await handler(request, Self.decodeBody(Body.self, from: request), logger)
}
}

// MARK: - Routes through middleware

/// Register a handler at a routing key, running it through middleware first.
Expand All @@ -76,9 +91,6 @@ public final class RouterBuilder<R: Routable, Engine: RoutingKit.RouterBuilder>

/// Register a handler at a routing key, running middleware and then JSON-decoding
/// the request body into `Body` before invoking the handler.
///
/// Available for any `Routable` whose `body: Data` carries JSON. The HTTP and
/// WebSocket adapters both qualify.
public func on<M: MiddlewareProtocol, Body: Decodable & Sendable>(
_ key: [String],
through middleware: M,
Expand All @@ -87,12 +99,21 @@ public final class RouterBuilder<R: Routable, Engine: RoutingKit.RouterBuilder>
) where M.Input == R {
self.on(key) { request, logger in
try await middleware.handle(request, next: { output, logger in
let decoded = try JSONDecoder().decode(Body.self, from: request.body)
return try await handler(output, decoded, logger)
try await handler(output, Self.decodeBody(Body.self, from: request), logger)
}, logger: logger)
}
}

/// Decode a JSON request body, wrapping failures in `RequestBodyError` so
/// `Router.handle` can map them to `400 Bad Request`.
private static func decodeBody<Body: Decodable>(_ type: Body.Type, from request: R) throws -> Body {
do {
return try JSONDecoder().decode(Body.self, from: request.body)
} catch {
throw RequestBodyError.decodingFailed(error)
}
}

// MARK: - Groups

/// Begin a route group whose registrations all run through the supplied middleware.
Expand Down Expand Up @@ -159,6 +180,8 @@ public final class Router<R: Routable>: Sendable {
return .error(statusCode: .badRequest, message: error.message)
} catch let error as HeaderError {
return .error(statusCode: .badRequest, message: error.message)
} catch let error as RequestBodyError {
return .error(statusCode: .badRequest, message: error.message)
} catch {
return .error(statusCode: .internalServerError, message: "Internal server error")
}
Expand Down
38 changes: 38 additions & 0 deletions Sources/Routing/Transports/HTTP/HTTPRouter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,44 @@ public extension RouterBuilder where R == HTTPRequest,
) {
self.on(HTTPRequest.options(path), use: handler)
}

/// Register a `POST` handler at the given path.
func post(
_ path: String,
use handler: @Sendable @escaping (HTTPRequest, Logger) async throws -> RouteResponse
) {
self.on(HTTPRequest.post(path), use: handler)
}

/// Register a `POST` handler at the given path, JSON-decoding the request body
/// into `Body` before invoking the handler.
func post<Body: Decodable & Sendable>(
_ path: String,
body: Body.Type,
use handler: @Sendable @escaping (HTTPRequest, Body, Logger) async throws -> RouteResponse
) {
self.on(HTTPRequest.post(path), body: body, use: handler)
}

/// Register a `PUT` handler at the given path, JSON-decoding the request body
/// into `Body` before invoking the handler.
func put<Body: Decodable & Sendable>(
_ path: String,
body: Body.Type,
use handler: @Sendable @escaping (HTTPRequest, Body, Logger) async throws -> RouteResponse
) {
self.on(HTTPRequest.put(path), body: body, use: handler)
}

/// Register a `PATCH` handler at the given path, JSON-decoding the request body
/// into `Body` before invoking the handler.
func patch<Body: Decodable & Sendable>(
_ path: String,
body: Body.Type,
use handler: @Sendable @escaping (HTTPRequest, Body, Logger) async throws -> RouteResponse
) {
self.on(HTTPRequest.patch(path), body: body, use: handler)
}
}

// MARK: - RouteGroup HTTP sugar
Expand Down
54 changes: 54 additions & 0 deletions Tests/RoutingTests/Helpers/HTTPRequestFixtures.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
//
// HTTPRequestFixtures.swift
//
// Copyright © 2026 SongShift, LLC. All rights reserved.
//

import AWSLambdaEvents
import Foundation
import Routing

enum HTTPRequestFixtures {
/// Builds a request through JSON because `APIGatewayV2Request` has no public initializer.
/// Shaped like a `/{proxy+}` HTTP API (payload 2.0) event.
static func makeRequest(
method: String = "POST",
path: String,
headers: [String: String] = [:],
body: String? = nil
) throws -> HTTPRequest {
var payload: [String: Any] = [
"version": "2.0",
"routeKey": "ANY /{proxy+}",
"rawPath": path,
"rawQueryString": "",
"headers": headers,
"pathParameters": ["proxy": path.hasPrefix("/") ? String(path.dropFirst()) : path],
"requestContext": [
"accountId": "123456789012",
"apiId": "api-id",
"domainName": "example.com",
"domainPrefix": "example",
"http": [
"method": method,
"path": path,
"protocol": "HTTP/1.1",
"sourceIp": "127.0.0.1",
"userAgent": "test",
],
"requestId": "request-id",
"routeKey": "ANY /{proxy+}",
"stage": "$default",
"time": "12/Mar/2026:19:03:58 +0000",
"timeEpoch": 1_583_348_638_390,
],
"isBase64Encoded": false,
]
if let body {
payload["body"] = body
}
let data = try JSONSerialization.data(withJSONObject: payload)
let event = try JSONDecoder().decode(APIGatewayV2Request.self, from: data)
return HTTPRequest(event: event)
}
}
15 changes: 15 additions & 0 deletions Tests/RoutingTests/Helpers/Logger+Testing.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
//
// Logger+Testing.swift
//
// Copyright © 2026 SongShift, LLC. All rights reserved.
//

import Logging

extension Logger {
/// Silent logger for router dispatch in tests.
static let testing = Logger(
label: "RoutingTests",
factory: { _ in SwiftLogNoOpLogHandler() }
)
}
49 changes: 49 additions & 0 deletions Tests/RoutingTests/RouterBodyDecodingTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
//
// RouterBodyDecodingTests.swift
//
// Copyright © 2026 SongShift, LLC. All rights reserved.
//

import Logging
import Routing
import Testing

@Suite("Router+BodyDecodingTests")
struct RouterBodyDecodingTests {
struct Input: Decodable, Sendable {
let id: String
}

let router: HTTPRouter

init() {
let builder = HTTPRouterBuilder()
builder.post("/echo", body: Input.self) { _, input, _ in
.string(input.id, statusCode: .ok)
}
self.router = builder.build()
}

@Test("Valid body is decoded and passed to the handler")
func validBody() async throws {
let response = await router.handle(
try HTTPRequestFixtures.makeRequest(path: "/echo", body: #"{"id":"abc"}"#),
logger: .testing
)
#expect(response.statusCode == .ok)
#expect(response.body == "abc")
}

@Test(
"Undecodable body returns 400",
arguments: [nil, "", "not json", #"{"wrong":1}"#, #"{"id":1}"#] as [String?]
)
func undecodableBody(body: String?) async throws {
let response = await router.handle(
try HTTPRequestFixtures.makeRequest(path: "/echo", body: body),
logger: .testing
)
#expect(response.statusCode == .badRequest)
#expect(response.body?.contains("The request body could not be decoded.") == true)
}
}
Loading