schema

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2025 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Definitions of JSON-level data structures.

Any data structure that the API expects or provides, regardless of whether it's through body, path, query, headers, is defined as a `schema.Schema`.

Index

Examples

Constants

View Source
const (
	TypeString = Type("string")
	TypeObject = Type("object")
	TypeArray  = Type("array")
	TypeNumber = Type("number")
	TypeBool   = Type("boolean")
)
View Source
const (
	FormatDateTime    = Format("date-time")
	FormatDate        = Format("date")
	FormatTime        = Format("time")
	FormatDuration    = Format("duration")
	FormatEmail       = Format("email")
	FormatIdnEmail    = Format("idn-email")
	FormatHostname    = Format("hostname")
	FormatIdnHostname = Format("idn-hostname")
	FormatUri         = Format("uri")
	FormatRegex       = Format("regex")
	FormatBinary      = Format("binary")
	FormatInt32       = Format("int32")
	FormatInt64       = Format("int64")
	FormatFloat       = Format("float")
	FormatDouble      = Format("double")
	FormatByte        = Format("byte")
	FormatPassword    = Format("password")
)

Well-known formats.

Note that this list doesn't attempt to be exhaustive.

Variables

This section is empty.

Functions

func RegisterOneOf

func RegisterOneOf[T IsOneOf](value T) structs.Nothing

Register a OneOf type.

Note: In other languages, this would be a static method of IsOneOf, but there are no such things in Go.

Types

type AllOf

type AllOf struct {
	AllOf []Schema `json:"allOf"`
}

"All of" combinator, e.g. an intersection type.

type Array

type Array struct {
	Shared `flatten:""`
	// The type of items.
	Items Schema `json:"items"`
	// Optionally, definitions used within `Items`.
	Defs *map[string]Schema `json:"$defs,omitempty"`
}

Array combinator.

type Format

type Format string

A well-known format.

type HasFormat

type HasFormat interface {
	// The format restriction.
	Format() Format
}

Implement this on a string or number to specify that it should match a given format.

type HasMax

type HasMax interface {
	Max() float64
}

Implement this to mark a maximal value for a number.

type HasMaxArrayLength

type HasMaxArrayLength interface {
	MaxArrayLength() int64
}

Implement this to mark a maximal length for an array.

type HasMaxMapLength

type HasMaxMapLength interface {
	MaxMapLength() int64
}

Implement this to mark a maximal length for an array.

type HasMaxStringLength

type HasMaxStringLength interface {
	MaxStringLength() int64
}

Implement this to mark a maximal length for a string.

type HasMin

type HasMin interface {
	Min() float64
}

Implement this to mark a minimal value for a number.

type HasMinArrayLength

type HasMinArrayLength interface {
	MinArrayLength() int64
}

Implement this to mark a minimal length for an array.

type HasMinMapLength

type HasMinMapLength interface {
	MinMapLength() int64
}

Implement this to mark a minimal length for an array.

type HasMinStringLength

type HasMinStringLength interface {
	MinStringLength() int64
}

Implement this to mark a minimal length for a string.

type HasSchema

type HasSchema interface {
	Schema() Schema
}

Use this interface to customize the schema returned by your type.

type Implementation

type Implementation struct {
	Type             reflect.Type
	PublicNameKey    string
	Title            *string
	MultipleOf       *float64
	Maximum          *float64
	ExclusiveMaximum *float64
	Minimum          *float64
	ExclusiveMinimum *float64
	MaxLength        *int64
	MinLength        *int64
	Pattern          *string
	MaxItems         *int64
	MinItems         *int64
	MaxProperties    *int64
	MinProperties    *int64
	Enum             *[]any
	Format           *string
	Example          *string
}

func ImplementationFromStructField

func ImplementationFromStructField(field reflect.StructField, publicNameKey string) (Implementation, error)

type IsEnum

type IsEnum interface {
	// The list of possibilities for this enum.
	Enum() []shared.Json
}

Implement this on a type to specify that it should be marked as an enum.

For more sophisticated cases, see `IsOneOf`.

type IsOneOf

type IsOneOf interface {
	// The main interface (for instance, for a MySum = MyString | MyInt, this should be MySum).
	Type() reflect.Type

	// Each of the possible variants (for instance, for a MySum = MyString | MyInt, this should be MyString and MySum).
	Variants() []reflect.Type
}

Implement this to represent a value that can come from several well-known types.

If you implement this interface, you MUST call RegisterOneOf.

See [sumtypes_test.go] for a complete example.

Example
package main

import (
	"encoding/json"
	"fmt"
	"reflect"

	"github.com/pasqal-io/gousset/openapi/schema"
)

// MyResult represents a sum between types Ok and Err.
type MyResult interface {
	sealed()

	schema.IsOneOf
}

func main() {
	spec, err := schema.FromImplementation(schema.Implementation{
		Type:          reflect.TypeFor[MyResult](),
		PublicNameKey: "json",
	})
	if err != nil {
		panic(err)
	}
	marshaled, err := json.MarshalIndent(spec, "", "\t")
	if err != nil {
		panic(err)
	}
	fmt.Print(string(marshaled))
}
Output:

{
	"oneOf": [
		{
			"type": "object",
			"required": [
				"result"
			],
			"properties": {
				"result": {
					"type": ""
				}
			}
		},
		{
			"type": "object",
			"required": [
				"error"
			],
			"properties": {
				"error": {
					"type": ""
				}
			}
		}
	]
}

type Object

type Object struct {
	Shared `flatten:""`

	// A list of required fields
	Required []string `json:"required,omitempty"`

	// A list of permitted fields, with their associated type. Use
	// this if your object is used as an object, with a well-known
	// list of properties.
	Properties map[string]Schema `json:"properties,omitempty"`

	// The types of values used in this object. Use this if your object
	// is used as a map, with an unknown list of properties, all of them
	// with the same type.
	AdditionalProperties *Schema `json:"additionalProperties,omitempty"`
}

type OneOf

type OneOf struct {
	OneOf []Schema `json:"oneOf"`
}

"One of" combinator, e.g. a sum type.

type Primitive

type Primitive struct {
	Shared `flatten:""`
}

type Schema

type Schema interface {
	// contains filtered or unexported methods
}

A JSON schema.

func FromImplementation

func FromImplementation(impl Implementation) (Schema, error)

Create a schema from a type.

As of this writing, we make no attempt to optimize schemas if e.g. some data structures are repeated.

Arguments:

  • typ The type to extract. See HasSchema, HasExternalDocs, HasExample for means to configure it.
  • publicNameKey The tag used to represent the public name of this field, e.g. `json`, `query`, `path`.

type Shared

type Shared struct {
	// Optional external documentation.
	ExternalDocs *doc.External `json:"externalDocs,omitempty"`

	// An optional example.
	Example *shared.Json `json:"example,omitempty"`

	// The JavaScript type for this schema.
	Type Type `json:"type"`

	// A well-known format, e.g. "email".
	Format *string `json:"format,omitempty"`

	Title            *string  `json:"title,omitempty"`
	MultipleOf       *float64 `json:"multipleOf,omitempty"`
	Maximum          *float64 `json:"maximum,omitempty"`
	ExclusiveMaximum *float64 `json:"exclusiveMaximum,omitempty"`
	Minimum          *float64 `json:"minimum,omitempty"`
	ExclusiveMinimum *float64 `json:"exclusiveMinimum,omitempty"`
	MaxLength        *int64   `json:"maxLength,omitempty"`
	MinLength        *int64   `json:"minLength,omitempty"`
	Pattern          *string  `json:"pattern,omitempty"`
	MaxItems         *int64   `json:"maxItems,omitempty"`
	MinItems         *int64   `json:"minItems,omitempty"`
	MaxProperties    *int64   `json:"maxProperties,omitempty"`
	MinProperties    *int64   `json:"minProperties,omitempty"`
	Enum             *[]any   `json:"enum,omitempty"`
}

Data shared between schemas.

type Type

type Type string

Jump to

Keyboard shortcuts

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