models

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2026 License: MIT Imports: 4 Imported by: 0

README

models

Go Reference

Knot's data model as an importable Go module: the domain types behind the product (Group, API, Parameter), the Knot JSON v1 wire-format types used by export/import, and the validation constants that define what a legal document is.

Installation

go get github.com/ProjAnvil/knot/models

The module is the models/ directory of the ProjAnvil/knot repository. It is versioned with models/vX.Y.Z git tags (e.g. models/v1.0.0), and go get resolves releases from those tags.

Versioning

The module follows semantic versioning via the repository's models/v* tags — the current release is v1.0.0. Breaking changes to any exported type or to the wire format bump the major version (per Go module conventions, a v2 would move the import path to github.com/ProjAnvil/knot/models/v2); backwards-compatible additions are minor releases; fixes are patches.

Packages

Package Import path Brings in
Root github.com/ProjAnvil/knot/models Standard library only
GORM bindings github.com/ProjAnvil/knot/models/gormbind GORM

The root package defines:

  • the domain types Group, API, and Parameter, plus ParamNode (the nested parameter tree projected from flat Parameter rows) and the import-preview types (ImportPlan, ImportGroup, ImportAPI);
  • the Knot JSON v1 wire-format types — KnotExportDocument with its KnotExportGroup / KnotExportAPI / KnotExportParams children, and the envelope constants WireFormat ("knot") and WireVersion (1);
  • the validation constants HTTPMethods, APITypes, ParamTypes, and ParamValueTypes, with their IsValidMethod / IsValidAPIType / IsValidParamType / IsValidParamValueType predicates.

The root package imports only the Go standard library.

gormbind maps those types onto database tables: pass your *gorm.DB to gormbind.AutoMigrate(db), or use gormbind.MigrateModels() with your own migration flow, to create/migrate the groups, apis, and parameters tables. Importing this subpackage pulls in GORM.

Example
import (
	"github.com/ProjAnvil/knot/models"
	"github.com/ProjAnvil/knot/models/gormbind"
)

g := models.Group{Name: "user-service"} // domain type
ok := models.IsValidMethod("GET")       // validation predicate

err := gormbind.AutoMigrate(db) // db *gorm.DB; migrates groups/apis/parameters

Wire-format artifacts

Two generated artifacts ship in the module so non-Go consumers can speak the same Knot JSON v1 interchange format:

Both files are generated — do not edit them by hand. They are derived from the Go types; regenerate them from the repository root with:

go run ./tools/cmd/gen-schema   # rewrites models/schema/knot-v1.schema.json
go run ./tools/cmd/gen-ts       # rewrites models/ts/index.d.ts

CI drift-locks them: the models job regenerates both files and fails the build if the committed copies differ, so a Go type change must always be committed together with its regenerated artifacts. How the generators work is documented in tools/README.md.

For maintainers: releasing

Tag the release and publish the GitHub release without taking the Latest badge:

git tag models/vX.Y.Z && git push origin models/vX.Y.Z
gh release create models/vX.Y.Z --latest=false

--latest=false matters: the repository's Latest badge must stay on the Knot product release, not on a library release.

License

MIT — same as the repository (LICENSE).

Documentation

Index

Constants

View Source
const WireFormat = "knot"

WireFormat is the format identifier written into every Knot JSON export document ("knot"). Consumers use it to recognize Knot files; the export builder and the format detector must agree on this value.

View Source
const WireVersion = 1

WireVersion is the version of the Knot JSON export envelope currently produced and accepted for import.

Variables

View Source
var APITypes = []string{"HTTP", "RPC"}

APITypes lists the supported API types.

View Source
var HTTPMethods = []string{"GET", "POST", "PUT", "DELETE", "PATCH"}

HTTPMethods lists the HTTP methods an API endpoint may declare.

View Source
var ParamTypes = []string{"request", "response"}

ParamTypes lists the parameter categories (request or response body).

View Source
var ParamValueTypes = []string{"string", "number", "boolean", "array", "object"}

ParamValueTypes lists the allowed parameter value types.

Functions

func CountNodes

func CountNodes(nodes []ParamNode) int

CountNodes returns the total number of nodes in a ParamNode tree, including all descendants. Used for ImportResult.ParametersImported.

func IsValidAPIType

func IsValidAPIType(t string) bool

IsValidAPIType reports whether t is one of the supported API types. Membership is case-sensitive.

func IsValidMethod

func IsValidMethod(m string) bool

IsValidMethod reports whether m is one of the supported HTTP methods. Membership is case-sensitive.

func IsValidParamType

func IsValidParamType(t string) bool

IsValidParamType reports whether t is a valid parameter category. Membership is case-sensitive.

func IsValidParamValueType

func IsValidParamValueType(t string) bool

IsValidParamValueType reports whether t is a valid parameter value type. Membership is case-sensitive.

Types

type API

type API struct {
	ID         uint        `gorm:"primaryKey;autoIncrement" json:"id"`
	GroupID    uint        `gorm:"not null;index:idx_group_id" json:"groupId"`
	Group      *Group      `gorm:"foreignKey:GroupID" json:"group,omitempty"`
	Name       string      `gorm:"not null" json:"name"`
	Endpoint   string      `gorm:"not null" json:"endpoint"`
	Method     string      `gorm:"type:varchar(10)" json:"method"` // GET, POST, PUT, DELETE, PATCH
	Type       string      `gorm:"not null" json:"type"`           // HTTP or RPC
	Order      int         `gorm:"default:0" json:"order"`
	Note       *string     `gorm:"type:text" json:"note"`
	Parameters []Parameter `gorm:"foreignKey:APIID;constraint:OnDelete:CASCADE" json:"parameters,omitempty"`
	CreatedAt  int64       `gorm:"autoCreateTime" json:"-"`
	UpdatedAt  int64       `gorm:"autoUpdateTime" json:"-"`
}

API represents an API endpoint

func (API) MarshalJSON

func (a API) MarshalJSON() ([]byte, error)

MarshalJSON customizes JSON serialization to convert timestamps to ISO 8601 strings

func (API) TableName

func (API) TableName() string

TableName specifies the table name for API

type Group

type Group struct {
	ID        uint   `gorm:"primaryKey;autoIncrement" json:"id"`
	Name      string `gorm:"unique;not null" json:"name"`
	Order     int    `gorm:"default:0" json:"order"`
	APIs      []API  `gorm:"foreignKey:GroupID;constraint:OnDelete:CASCADE" json:"apis,omitempty"`
	CreatedAt int64  `gorm:"autoCreateTime" json:"-"`
	UpdatedAt int64  `gorm:"autoUpdateTime" json:"-"`
}

Group represents an API group/collection

func (Group) MarshalJSON

func (g Group) MarshalJSON() ([]byte, error)

MarshalJSON customizes JSON serialization to convert timestamps to ISO 8601 strings

func (Group) TableName

func (Group) TableName() string

TableName specifies the table name for Group

type ImportAPI

type ImportAPI struct {
	Name     string
	Endpoint string
	Method   string
	Type     string
	Note     *string
	Request  []ParamNode
	Response []ParamNode
}

ImportAPI is one API entry within an import plan group. Note is a pointer so a missing note stays distinguishable from an empty one.

type ImportFormat

type ImportFormat string

ImportFormat identifies the exchange format of an uploaded import file. The string values are stable identifiers used by the import handler.

const (
	ImportFormatKnot    ImportFormat = "knot-json"
	ImportFormatPostman ImportFormat = "postman"
	ImportFormatOpenAPI ImportFormat = "openapi"
)

type ImportGroup

type ImportGroup struct {
	Name string
	APIs []ImportAPI
}

ImportGroup is one API group within an import plan.

type ImportPlan

type ImportPlan struct {
	Groups   []ImportGroup
	Warnings []string
}

ImportPlan is the shared intermediate representation that every importer (Knot JSON, Postman, OpenAPI) produces from an uploaded file. The import apply step consumes it; Warnings collects non-fatal issues encountered while parsing so they can be surfaced to the user after import.

type KnotExportAPI

type KnotExportAPI struct {
	Name       string           `json:"name"`
	Endpoint   string           `json:"endpoint"`
	Method     string           `json:"method"`
	Type       string           `json:"type"`
	Order      int              `json:"order"`
	Note       *string          `json:"note"`
	Parameters KnotExportParams `json:"parameters"`
}

KnotExportAPI is one API entry within a group.

type KnotExportDocument

type KnotExportDocument struct {
	Format     string            `json:"format"`
	Version    int               `json:"version"`
	ExportedAt string            `json:"exportedAt"`
	Groups     []KnotExportGroup `json:"groups"`
}

KnotExportDocument is the top-level structure of a Knot JSON v1 export file.

type KnotExportGroup

type KnotExportGroup struct {
	Name  string          `json:"name"`
	Order int             `json:"order"`
	APIs  []KnotExportAPI `json:"apis"`
}

KnotExportGroup is one API group within a Knot export document.

type KnotExportParams

type KnotExportParams struct {
	Request  []ParamNode `json:"request"`
	Response []ParamNode `json:"response"`
}

KnotExportParams holds the request and response parameter trees of one API.

type ParamNode

type ParamNode struct {
	Name        string      `json:"name"`
	Type        string      `json:"type"` // string|number|boolean|array|object
	Required    bool        `json:"required"`
	Description *string     `json:"description"`
	Order       int         `json:"order"`
	Children    []ParamNode `json:"children"`
}

ParamNode is a portable representation of a parameter tree node used by multi-format export/import. It mirrors Parameter without persistence or ORM concerns so it can be serialized to any exchange format.

func ParamNodesFromJSONValue

func ParamNodesFromJSONValue(v interface{}) []ParamNode

ParamNodesFromJSONValue converts a decoded JSON value (as produced by json.Unmarshal into interface{}) into ParamNodes on a best-effort basis: string→string, float64→number, bool→boolean, []interface{}→array, map[string]interface{}→object. Map keys are sorted for deterministic order. A non-object top-level value yields no nodes. Used by the Postman importer for raw JSON bodies.

func TreeFromParams

func TreeFromParams(params []Parameter) []ParamNode

TreeFromParams converts flat ordered parameter rows (as fetched for one API and paramType) into a nested tree of ParamNode. Input row order is preserved for both roots and siblings. Rows whose ParentID references an unknown parameter are dropped, mirroring BuildParameterTree.

type Parameter

type Parameter struct {
	ID          uint        `gorm:"primaryKey;autoIncrement" json:"id"`
	APIID       uint        `gorm:"not null;index:idx_api_param" json:"apiId"`
	API         *API        `gorm:"foreignKey:APIID" json:"-"`
	ParentID    *uint       `gorm:"index:idx_parent" json:"parentId"`
	Parent      *Parameter  `gorm:"foreignKey:ParentID" json:"-"`
	Children    []Parameter `gorm:"foreignKey:ParentID" json:"children,omitempty"`
	Name        string      `gorm:"not null" json:"name"`
	Type        string      `gorm:"not null" json:"type"` // string, number, boolean, array, object
	Description *string     `gorm:"type:text" json:"description"`
	Required    bool        `gorm:"default:false" json:"required"`
	ParamType   string      `gorm:"not null;index:idx_api_param" json:"paramType"` // request or response
	Order       int         `gorm:"not null;index:idx_api_param" json:"order"`
	CreatedAt   int64       `gorm:"autoCreateTime" json:"-"`
	UpdatedAt   int64       `gorm:"autoUpdateTime" json:"-"`
}

Parameter represents request/response parameters with support for nested structures

func (Parameter) MarshalJSON

func (p Parameter) MarshalJSON() ([]byte, error)

MarshalJSON customizes JSON serialization to convert timestamps to ISO 8601 strings

func (Parameter) TableName

func (Parameter) TableName() string

TableName specifies the table name for Parameter

Directories

Path Synopsis
Package gormbind binds the persistence-free domain models of the models module to GORM.
Package gormbind binds the persistence-free domain models of the models module to GORM.

Jump to

Keyboard shortcuts

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