awseventgenerator

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: May 11, 2023 License: MIT Imports: 17 Imported by: 0

README

awseventgenerator

Generates Go (golang) Structs and Validation code from AWS EventBridge JSON schemas.

Requirements

  • Go 1.20.3+

Usage

Install

$ go get -u github.com/webdestroya/awseventgenerator

Example

This schema

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "AwsExampleEventBridgeEvent",
  "definitions": {
    "TrafficLightChange": {
      "properties": {
        "new-state": {
          "$ref": "#/definitions/TrafficLightState"
        },
        "previous-state": {
          "$ref": "#/definitions/TrafficLightState"
        },
        "id": {
          "type": "string"
        }
      },
      "required": ["id", "new-state", "previous-state"],
      "type": "object"
    },
    "TrafficLightState": {
      "properties": {
        "blinking": {
          "type": "boolean"
        },
        "color": {
          "enum": ["RED", "YELLOW", "GREEN"],
          "type": "string"
        }
      },
      "required": ["color"],
      "type": "object"
    }
  },
  "properties": {
    "account": {
      "type": "string"
    },
    "detail": {
      "$ref": "#/definitions/TrafficLightChange"
    },
    "detail-type": {
      "type": "string"
    },
    "id": {
      "type": "string"
    },
    "region": {
      "type": "string"
    },
    "resources": {
      "items": {
        "type": "string"
      },
      "type": "array"
    },
    "source": {
      "type": "string"
    },
    "time": {
      "format": "date-time",
      "type": "string"
    },
    "version": {
      "type": "string"
    }
  },
  "required": [
    "detail-type",
    "resources",
    "id",
    "source",
    "time",
    "detail",
    "region",
    "version",
    "account"
  ],
  "type": "object",
  "x-amazon-events-detail-type": "Example EventBridge Event",
  "x-amazon-events-source": "aws.example"
}

generates

package awsexample

import (
	"time"
)

const (
	AwsEventSource     = `aws.example`
	AwsEventDetailType = `Example EventBridge Event`
)

type ColorType string
const (
	ColorTypeRed    ColorType = "RED"
	ColorTypeYellow ColorType = "YELLOW"
	ColorTypeGreen  ColorType = "GREEN"
)
func (ColorType) Values() []ColorType {
	return []ColorType{
		"RED",
		"YELLOW",
		"GREEN",
	}
}

type AwsEvent struct {
	Account    string              `json:"account"`
	Detail     *TrafficLightChange `json:"detail"`
	DetailType string              `json:"detail-type"`
	Id         string              `json:"id"`
	Region     string              `json:"region"`
	Resources  []string            `json:"resources"`
	Source     string              `json:"source"`
	Time       time.Time           `json:"time"`
	Version    string              `json:"version"`
}

type TrafficLightChange struct {
	Id            string             `json:"id"`
	NewState      *TrafficLightState `json:"new-state"`
	PreviousState *TrafficLightState `json:"previous-state"`
}

type TrafficLightState struct {
	Blinking *bool     `json:"blinking,omitempty"`
	Color    ColorType `json:"color"`
}

To view more examples, run make generate and then look in the internal/testcode/ directory.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultPackageNameFunc

func DefaultPackageNameFunc(s *Schema) string

func Generate

func Generate(from any, config *Config) ([]byte, error)

data = string = file (unless it starts with {) []byte = interpreted as raw schema *Schema io.Reader

func GenerateAndExport

func GenerateAndExport(data any, destinationFile string, config *Config) error

func GenerateFromSchema

func GenerateFromSchema(schema *Schema, config *Config) ([]byte, error)

func GenerateFromSchemaFile

func GenerateFromSchemaFile(filename string, config *Config) ([]byte, error)

func GenerateFromSchemaString

func GenerateFromSchemaString(data string, config *Config) ([]byte, error)

func Output

func Output(w io.Writer, g *Generator) error

Output generates code and writes to w.

Types

type AdditionalProperties

type AdditionalProperties Schema

AdditionalProperties handles additional properties present in the JSON schema.

func (*AdditionalProperties) UnmarshalJSON

func (ap *AdditionalProperties) UnmarshalJSON(data []byte) error

UnmarshalJSON handles unmarshalling AdditionalProperties from JSON.

type Config

type Config struct {
	// A string for the package name
	// or a function that is passed the schema
	PackageName any

	// whether enum types should be actual enums
	// adds a helper .Values() method that lists all possible values
	GenerateEnums bool

	// All values, regardless of requiredness should be pointers
	AlwaysPointerize bool

	// whether to skip pretty format the code
	NoFormatCode bool

	// Set the root element name. default is AwsEvent
	RootElement string

	// do not emit the Source/DetailType constants
	SkipEventConstants bool

	// makes very violent marshallers, that will fail if a required field is missing
	EnforceRequiredInMarshallers bool
}

func (*Config) InitDefaults

func (c *Config) InitDefaults()

type Field

type Field struct {
	// The golang name, e.g. "Address1"
	Name string
	// The JSON name, e.g. "address1"
	JSONName string
	// The golang type of the field, e.g. a built-in type like "string" or the name of a struct generated
	// from the JSON schema.
	Type string
	// Required is set to true when the field is required.
	Required    bool
	Description string
	EnumValues  []string
	Format      string

	// the actual go type to write to the file
	FinalType string
	// contains filtered or unexported fields
}

Field defines the data required to generate a field in Go.

type Generator

type Generator struct {
	Structs map[string]Struct
	Aliases map[string]Field

	Constants map[string]any
	// contains filtered or unexported fields
}

Generator will produce structs from the JSON schema.

func New

func New(config *Config, schema *Schema) *Generator

func NewMulti

func NewMulti(config *Config, schemas ...*Schema) *Generator

New creates an instance of a generator which will produce structs.

func (*Generator) Generate

func (g *Generator) Generate() (err error)

Generate creates types from the JSON schemas, keyed by the golang name.

type PackageNameFunc

type PackageNameFunc = func(*Schema) string

type RefResolver

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

RefResolver allows references to be resolved.

func NewRefResolver

func NewRefResolver(schemas []*Schema) *RefResolver

NewRefResolver creates a reference resolver.

func (*RefResolver) GetPath

func (r *RefResolver) GetPath(schema *Schema) string

GetPath generates a path to given schema.

func (*RefResolver) GetSchemaByReference

func (r *RefResolver) GetSchemaByReference(schema *Schema) (*Schema, error)

GetSchemaByReference returns the schema.

func (*RefResolver) Init

func (r *RefResolver) Init() error

Init the resolver.

func (*RefResolver) InsertURI

func (r *RefResolver) InsertURI(uri string, schema *Schema) error

InsertURI to the references.

type Schema

type Schema struct {
	// SchemaType identifies the schema version.
	// http://json-schema.org/draft-07/json-schema-core.html#rfc.section.7
	SchemaType string `json:"$schema"`

	// ID{04,06} is the schema URI identifier.
	// http://json-schema.org/draft-07/json-schema-core.html#rfc.section.8.2
	ID04 string `json:"id"`  // up to draft-04
	ID06 string `json:"$id"` // from draft-06 onwards

	// Title and Description state the intent of the schema.
	Title       string
	Description string

	// TypeValue is the schema instance type.
	// http://json-schema.org/draft-07/json-schema-validation.html#rfc.section.6.1.1
	TypeValue interface{} `json:"type"`

	Format        string   `json:"format"`
	AwsDetailType string   `json:"x-amazon-events-detail-type"`
	AwsSource     string   `json:"x-amazon-events-source"`
	EnumValues    []string `json:"enum"`

	// Definitions are inline re-usable schemas.
	// http://json-schema.org/draft-07/json-schema-validation.html#rfc.section.9
	Definitions map[string]*Schema

	// Properties, Required and AdditionalProperties describe an object's child instances.
	// http://json-schema.org/draft-07/json-schema-validation.html#rfc.section.6.5
	Properties map[string]*Schema
	Required   []string

	// "additionalProperties": {...}
	AdditionalProperties *AdditionalProperties

	// "additionalProperties": false
	AdditionalPropertiesBool *bool `json:"-"`

	AnyOf []*Schema
	AllOf []*Schema
	OneOf []*Schema

	// Default can be used to supply a default JSON value associated with a particular schema.
	// http://json-schema.org/draft-07/json-schema-validation.html#rfc.section.10.2
	Default interface{}

	// Examples ...
	// http://json-schema.org/draft-07/json-schema-validation.html#rfc.section.10.4
	Examples []interface{}

	// Reference is a URI reference to a schema.
	// http://json-schema.org/draft-07/json-schema-core.html#rfc.section.8
	Reference string `json:"$ref"`

	// Items represents the types that are permitted in the array.
	// http://json-schema.org/draft-07/json-schema-validation.html#rfc.section.6.4
	Items *Schema

	// NameCount is the number of times the instance name was encountered across the schema.
	NameCount int `json:"-" `

	// Parent schema
	Parent *Schema `json:"-" `

	// Key of this schema i.e. { "JSONKey": { "type": "object", ....
	JSONKey string `json:"-" `

	// path element - for creating a path by traversing back to the root element
	PathElement string `json:"-"`

	// calculated struct name of this object, cached here
	GeneratedType string `json:"-"`
}

Schema represents JSON schema.

func Parse

func Parse(schema string, uri *url.URL) (*Schema, error)

Parse parses a JSON schema from a string.

func (*Schema) AllowsNull

func (schema *Schema) AllowsNull() bool

Aws does a really annoying thing where they say an item is required, but then make the type of the property be [string, null] which is actually _NOT_ required so this works around that

func (*Schema) FixMissingTypeValue

func (schema *Schema) FixMissingTypeValue()

FixMissingTypeValue is backwards compatible, guessing the users intention when they didn't specify a type.

func (*Schema) GetRoot

func (schema *Schema) GetRoot() *Schema

GetRoot returns the root schema.

func (*Schema) ID

func (schema *Schema) ID() string

ID returns the schema URI id.

func (*Schema) Init

func (schema *Schema) Init()

Init schema.

func (*Schema) IsRoot

func (schema *Schema) IsRoot() bool

IsRoot returns true when the schema is the root.

func (*Schema) MultiType

func (schema *Schema) MultiType(conf *Config) ([]string, bool)

MultiType returns "type" as an array

func (*Schema) Type

func (schema *Schema) Type() (firstOrDefault string, multiple bool)

Type returns the type which is permitted or an empty string if the type field is missing. The 'type' field in JSON schema also allows for a single string value or an array of strings. Examples:

"a" => "a", false
[] => "", false
["a"] => "a", false
["a", "b"] => "a", true

type Struct

type Struct struct {
	// The ID within the JSON schema, e.g. #/definitions/address
	ID string
	// The golang name, e.g. "Address"
	Name string
	// Description of the struct
	Description string
	Fields      map[string]Field

	GenerateCode   bool
	AdditionalType string

	EnumValues []string
	IsEnum     bool

	// If this should just be a straight alias (type ThisThing = XXXX)
	AliasType string
	// contains filtered or unexported fields
}

Struct defines the data required to generate a struct in Go.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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