parser

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 13, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Overview

Package parser validates and transforms Lambda payloads with typed schemas.

Parse returns a validated value or ParseError. SafeParse retains the original input and structured Issue values when validation fails. WrapHandler and WrapSafeHandler adapt schemas to typed Lambda handlers.

Schema composition

Build schemas with Object, Array, primitive constructors, Transform and Refine. Typed maps validated JSON-shaped values into application types. The schemas subpackage supplies service event contracts; envelopes validates the outer event and extracts a payload for further parsing.

Parser has no JSON Schema engine dependency. Use the separate Validation module for JSON Schema documents. Review the guide's field, number and error boundaries before relying on compatibility with another Powertools implementation.

For usage and compatibility details, see the user guide.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Parse

func Parse[T any](ctx context.Context, input any, schema Schema[T]) (T, error)
Example
package main

import (
	"context"
	"fmt"

	"github.com/rambow-cloud/powertools-lambda-go/parser"
)

func main() {
	schema := parser.Object(parser.Field{Name: "orderId", Schema: parser.String()})
	value, err := parser.Parse(context.Background(), map[string]any{"orderId": "order-123"}, schema)
	if err != nil {
		panic(err)
	}
	fmt.Println(value.(map[string]any)["orderId"])
}
Output:
order-123

func WrapHandler

func WrapHandler[I, T, R any](schema Schema[T], handler func(context.Context, T) (R, error)) func(context.Context, I) (R, error)

WrapHandler parses before calling the business handler and preserves shared invocation identity. Context, operational errors and panics are not replaced.

func WrapSafeHandler

func WrapSafeHandler[I, T, R any](schema Schema[T], handler func(context.Context, Result[T]) (R, error)) func(context.Context, I) (R, error)

Types

type Field

type Field struct {
	Name     string
	Schema   Schema[any]
	Optional bool
	// contains filtered or unexported fields
}

Field retains declaration order, including validation issue order. Optional distinguishes absence from null. WithDefault applies only to absent values.

func (Field) WithDefault

func (f Field) WithDefault(value any) Field

type Issue

type Issue struct {
	Message  string    `json:"message"`
	Path     []any     `json:"path,omitempty"`
	Code     string    `json:"code,omitempty"`
	Expected string    `json:"expected,omitempty"`
	Errors   [][]Issue `json:"errors,omitempty"`
	// Continuable marks a check failure that preserves the parsed value's type.
	// It controls union/refinement evaluation and is not part of serialized errors.
	Continuable bool `json:"-"`
}

Issue maps Standard Schema's message/path contract. Code and Expected retain useful built-in diagnostics without requiring a specific validation engine.

func Prefix

func Prefix(issues []Issue, path ...any) []Issue

type ObjectSchema

type ObjectSchema struct {
	// contains filtered or unexported fields
}

func Object

func Object(fields ...Field) *ObjectSchema

func (*ObjectSchema) Extend

func (s *ObjectSchema) Extend(fields ...Field) *ObjectSchema

func (*ObjectSchema) Omit

func (s *ObjectSchema) Omit(names ...string) *ObjectSchema

Omit returns a schema without the named fields, retaining validation order.

func (*ObjectSchema) Validate

func (s *ObjectSchema) Validate(ctx context.Context, input any) (any, []Issue, error)

func (*ObjectSchema) ValidateSafe

func (s *ObjectSchema) ValidateSafe(ctx context.Context, input any) (any, []Issue, error)

func (*ObjectSchema) WithUnknownFields

func (s *ObjectSchema) WithUnknownFields(policy UnknownFields) *ObjectSchema

type ParseError

type ParseError struct {
	Message string
	Issues  []Issue
	Err     error
}

func (*ParseError) Error

func (e *ParseError) Error() string

func (*ParseError) Unwrap

func (e *ParseError) Unwrap() error

type Result

type Result[T any] struct {
	Success       bool
	Data          T
	Error         *ParseError
	OriginalEvent any
}

Result includes the original event only on validation failure. The event is retained by reference, as in the reference safeParse contract.

func SafeParse

func SafeParse[T any](ctx context.Context, input any, schema Schema[T]) (Result[T], error)

type SafeSchema

type SafeSchema[T any] interface {
	ValidateSafe(context.Context, any) (T, []Issue, error)
}

SafeSchema optionally aggregates additional envelope failures in safe mode.

type Schema

type Schema[T any] interface {
	Validate(context.Context, any) (T, []Issue, error)
}

Schema returns nil issues for success. A non-nil slice, including an empty slice, denotes validation failure. Unexpected errors propagate even in safe parsing, matching a thrown Standard Schema validator exception.

func Any

func Any[T any](schema Schema[T]) Schema[any]

func Array

func Array[T any](schema Schema[T], minimum ...int) Schema[[]T]

func Base64Encoded

func Base64Encoded[T any](schema Schema[T]) Schema[T]

Base64Encoded follows the reference's gzip-JSON, JSON, then UTF-8 text fallback. Malformed Base64 errors propagate rather than becoming schema issues.

func Boolean

func Boolean() Schema[any]

func Dictionary

func Dictionary(schema Schema[any]) Schema[any]

func DynamoDBMarshalled

func DynamoDBMarshalled[T any](schema Schema[T]) Schema[T]

DynamoDBMarshalled decodes raw AttributeValue objects before schema validation. Raw binary values and large integers retain the Commons conversion contract.

func Enum

func Enum(values ...string) Schema[any]

Enum validates a string against a fixed set of values.

func JSONStringified

func JSONStringified[T any](schema Schema[T]) Schema[T]

func Literal

func Literal(value any) Schema[any]

func Null

func Null() Schema[any]

Null accepts explicit null while rejecting an absent object field.

func Nullable

func Nullable[T any](schema Schema[T]) Schema[any]

func Number

func Number() Schema[any]

func Pipe

func Pipe[A, B any](first Schema[A], next Schema[B]) Schema[B]

Pipe validates transformed output and preserves safe-mode envelope aggregation.

func Refine

func Refine[T any](schema Schema[T], predicate func(T) bool, message string) Schema[T]

func String

func String() Schema[any]

func Transform

func Transform[A, B any](schema Schema[A], convert func(context.Context, A) (B, error)) Schema[B]

Transform preserves an envelope's safe-mode aggregation before converting output.

func Typed

func Typed[T any](schema Schema[any]) Schema[T]

Typed converts validated output using ordinary Go JSON tags and types. Schema transforms run before decoding; incompatible output types are operational errors.

func Union

func Union(schemas ...Schema[any]) Schema[any]

Union tries branches in order and preserves nested failures when none succeeds. A sole branch with only continuable check failures retains its own diagnostics.

func Unknown

func Unknown() Schema[any]

type SchemaFunc

type SchemaFunc[T any] func(context.Context, any) (T, []Issue, error)

func (SchemaFunc[T]) Validate

func (f SchemaFunc[T]) Validate(ctx context.Context, input any) (T, []Issue, error)

type UnknownFields

type UnknownFields uint8
const (
	StripUnknown UnknownFields = iota
	PreserveUnknown
	RejectUnknown
)

Directories

Path Synopsis
Package envelopes validates Lambda event envelopes and extracts typed payloads.
Package envelopes validates Lambda event envelopes and extracts typed payloads.
Package schemas supplies reusable AWS Lambda service event schemas.
Package schemas supplies reusable AWS Lambda service event schemas.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL