models

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 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.2.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.

v1.2.0 is an additive wire change: the Group domain type's JSON now emits order (its MarshalJSON previously omitted the field). Consumers see one new field wherever a Group is marshaled; nothing is renamed or removed.

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, ImportResult);
  • the Knot JSON v1 wire-format types — KnotExportDocument with its KnotExportGroup / KnotExportAPI / KnotExportParams children, and the envelope constants WireFormat ("knot") and WireVersion (1). WireFormat is the value written into a Knot JSON document's envelope format field to identify the v1 wire format — it is not the backend export request's format parameter (whose values are "", html, json, openapi and postman);
  • 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.

Table name prefix (v1.1)

Embedders that share one database with other software can namespace Knot's tables with models.SetTablePrefix (default "", i.e. the v1.0 bare names):

models.SetTablePrefix("knot_")   // before the first DB use: knot_groups, knot_apis, knot_parameters
err := gormbind.AutoMigrate(db)

The prefix is process-global: set it once before the first database use and run a single engine instance per process. GORM resolves table names when a model schema is first parsed and caches them per *gorm.DB, so changing the prefix afterwards has no effect on an open database, and existing tables are never renamed.

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

Changes in v1.1

Backwards-compatible additions over v1.0 (see Versioning):

  • SetTablePrefix / TablePrefix: prefix all model tables (knot_groups/knot_apis/knot_parameters style) so the models can be embedded in a shared database. The default empty prefix preserves the v1.0 physical schema.
  • ImportResult relocated verbatim from the Knot backend's services package (same fields, same JSON tags: format/groupsCreated/groupsMerged/ apisImported/parametersImported/warnings) so import tooling can consume the preview/confirm payload without importing the backend.
  • The embeddable engine module (backend) consumes both additions through this module: knot.Config.TablePrefix installs the prefix via SetTablePrefix, and knot.Knot.Import returns *models.ImportResult (the backend's internal services package aliases it as type ImportResult = models.ImportResult) — so engine hosts get these types through the backend import alone.

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.

View Source
var TablePrefix string

TablePrefix is prepended to every model table name (see Group.TableName, API.TableName and Parameter.TableName). The default empty string keeps the v1.0 physical schema unchanged: groups, apis, parameters.

TablePrefix is process-global state. Embedders that share one database with other software set it (e.g. "knot_") so Knot's tables are namespaced; everything else leaves it empty. Use SetTablePrefix to assign it — never write the variable from multiple goroutines.

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.

func SetTablePrefix added in v1.1.0

func SetTablePrefix(p string)

SetTablePrefix sets the process-wide prefix for all model table names.

Contract: call it exactly once, before the first database use (before opening a connection or running any migration/query), and run a single engine instance per process. GORM resolves each model's table name when its schema is first parsed and caches the result per *gorm.DB, so a running database never observes later prefix changes — changing the prefix after tables exist will not rename them and will strand existing data under the old names.

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: TablePrefix + "apis". The default empty prefix keeps the v1.0 table name "apis".

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: TablePrefix + "groups". The default empty prefix keeps the v1.0 table name "groups".

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 ImportResult added in v1.1.0

type ImportResult struct {
	Format             string   `json:"format"`
	GroupsCreated      int      `json:"groupsCreated"`
	GroupsMerged       int      `json:"groupsMerged"`
	APIsImported       int      `json:"apisImported"`
	ParametersImported int      `json:"parametersImported"`
	Warnings           []string `json:"warnings"`
}

ImportResult reports what an applied import plan did (or, for a dry run, what it would do). It is the payload of the import preview/confirm flow.

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: TablePrefix + "parameters". The default empty prefix keeps the v1.0 table name "parameters".

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