Skip to content

Refactor APIGatewayXXX to eliminate duplicate code #89

@sebsto

Description

@sebsto

There is an opportunity to DRY by refactoring part of the APIGateway, APIGatewayV2, and APIGateway+WebSocket payload.

As per my assistant:


1. HTTP Headers and Body Handling

  • Properties like headers, multiValueHeaders (or just headers in V2), and body, as well as isBase64Encoded, appear in all major APIGateway request/response structs:
    • APIGatewayRequest
    • APIGatewayV2Request
    • APIGatewayWebSocketRequest
    • Their corresponding response types.

2. Context/Identity Structures

  • Each request type defines a nested Context struct (sometimes with further nesting like Identity or HTTP), which contains information about the caller, API, stage, request IDs, etc.
  • Many fields in these context structs overlap, such as apiId, stage, requestId, domainName, and sourceIp.

3. Codable/Sendable Conformance

  • All these types conform to Codable (and, where supported, Sendable).

4. CodingKeys Mapping

  • Several structs use custom CodingKeys enums to map from JSON input to struct properties, especially for context/requestContext fields.

5. Response Struct Pattern

  • The response structs (APIGatewayResponse, APIGatewayV2Response, and by alias, APIGatewayWebSocketResponse) all follow a similar pattern: statusCode, headers, body, and isBase64Encoded, with slight variations.

Candidates for Code Sharing/Abstraction

  • Protocols: Define a protocol for common properties (headers, body, isBase64Encoded) and have each struct conform to it.
    protocol APIGatewayRequestCommon: Codable {
        var headers: HTTPHeaders? { get }
        var body: String? { get }
        var isBase64Encoded: Bool? { get }
    }
  • Shared Context/Identity Structs: Refactor common context/identity fields into base structs or protocols, and compose them in each specific context struct as needed.
  • Initializers/Decoding Helpers: Shared extensions or helper initializers to reduce repeated decoding logic for commonly structured properties.

Summary Table of Common Properties:

Property APIGatewayRequest APIGatewayV2Request APIGatewayWebSocketRequest
headers
multiValueHeaders (V2 drops this)
body
isBase64Encoded
context/requestContext ✓ (as context)
stage ✓ (in context) ✓ (in context) ✓ (in context)
apiId ✓ (in context) ✓ (in context) ✓ (in context)
requestId ✓ (in context) ✓ (in context) ✓ (in context)
domainName ✓ (in context) ✓ (in context) ✓ (in context)
sourceIp ✓ (in context) ✓ (in context) ✓ (in context.identity)

Metadata

Metadata

Assignees

No one assigned

    Type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions