services

package
v0.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: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoAPIIDs is returned when an export request carries no API IDs.
	ErrNoAPIIDs = errors.New("no API IDs provided")
	// ErrUnsupportedExportFormat is returned for an unknown export format
	// identifier; "" and "html" are the HTML default.
	ErrUnsupportedExportFormat = errors.New("unsupported export format")
)

Export input-validation sentinels. They let the HTTP handler and the embeddable engine facade (package knot) map the same failures to their respective error surfaces without either side string-matching messages.

Functions

func BuildExportDocument

func BuildExportDocument(db *gorm.DB, apiIDs []uint, format, locale string, now time.Time) ([]byte, string, string, error)

BuildExportDocument fetches the selected APIs with their groups and parameters, renders them in the requested format, and returns the payload together with the download filename and Content-Type. It is the single source of export truth shared by the HTTP handler (handlers/export.go) and the embeddable engine facade (backend/knot.go); both surfaces therefore produce byte-identical output for the same inputs and instant.

format follows the handler contract: "" and "html" render the standalone HTML document; "json", "openapi" and "postman" render the respective JSON documents. locale selects the HTML template language and defaults to "zh" when empty. now stamps time-derived fields (exportedAt, descriptions) and the JSON filenames, all with second granularity.

func BuildKnotDocument

func BuildKnotDocument(apis []APIWithParams, now time.Time) *models.KnotExportDocument

BuildKnotDocument assembles the Knot JSON v1 export document from APIs with their parameters. APIs are grouped by API.GroupID in first-appearance order (tracked with a seen-map over the input slice, never map iteration, so group order is deterministic); each group carries the GroupOrder of its APIs. Parameter rows are converted to nested models.ParamNode trees via models.TreeFromParams.

func BuildParameterTree

func BuildParameterTree(params []models.Parameter) []models.Parameter

BuildParameterTree builds a hierarchical tree structure from flat parameter list

func DetectImportFormat

func DetectImportFormat(data []byte) (models.ImportFormat, error)

DetectImportFormat inspects raw file bytes and decides which importer should handle them, per spec §8.2. A UTF-8 BOM is stripped before probing, then the document is unmarshalled into a raw root object and matched against the (disjoint) format signatures in order:

  1. root "format" == "knot" → knot-json
  2. root "info.schema" contains schema.getpostman.com → postman (v2.0 and v2.1)
  3. root "openapi" with major version "3" → openapi
  4. root "swagger" present → error naming OpenAPI 3

Non-JSON, empty, or unrecognized input is an error. All returned errors carry user-facing messages suitable for a 415-style response.

func GenerateExampleJSON

func GenerateExampleJSON(params []models.Parameter) map[string]interface{}

GenerateExampleJSON generates example JSON from parameters

func GenerateHTML

func GenerateHTML(apis []APIWithParams, locale string) string

GenerateHTML generates a complete HTML document from APIs

func GenerateParameterHTML

func GenerateParameterHTML(params []models.Parameter, depth int) string

GenerateParameterHTML generates HTML table for parameters

func JSONSchemaToNodes

func JSONSchemaToNodes(schema map[string]interface{}, root map[string]interface{}, visited map[string]bool, depth int) []models.ParamNode

JSONSchemaToNodes is the inverse of NodesToJSONSchema: it converts a JSON Schema (an object schema whose properties are the nodes, or a $ref to one) back into the models.ParamNode forest it describes. Property names are sorted for deterministic node order and Order values, the schema's "required" array marks required nodes, nested object schemas nest as children, array "items" become the array node's children, leaf types map directly and "description" is carried on every node that has one. $ref values are resolved against root with the passed visited set as cycle guard; subtrees behind cyclic, external, unresolvable or too-deeply nested references are skipped (the warning-recording variant used by ParseOpenAPIDocument reports them; this entry point drops them).

func NodesToJSONSchema

func NodesToJSONSchema(nodes []models.ParamNode, objectRequired bool) map[string]interface{}

NodesToJSONSchema converts a models.ParamNode forest into the JSON Schema of the value the forest describes: an implicit object whose properties are the nodes, mirroring GenerateExampleJSON, where each root node becomes one key of the request/response body. objectRequired reports whether that object requires its members (the requestBody-level required): when true and at least one node is required, the schema carries a "required" array listing their names; otherwise the key is omitted.

Nested nodes map per the export spec: object -> {type, properties, required: [names of required children]}; array -> {type, items}; leaf types (string|number|boolean) map directly; description is carried on every node that has one.

func ParseKnotJSON

func ParseKnotJSON(data []byte) (*models.ImportPlan, error)

ParseKnotJSON parses a Knot JSON v1 export (as produced by BuildKnotDocument) into a models.ImportPlan. It is the direct inverse of the export builder per spec §8.3: unknown fields are ignored, methods are upper-cased, and type defaults to "HTTP" when absent. An unknown type value is normalized to "HTTP" with a recorded warning rather than failing. A UTF-8 BOM is tolerated so any file accepted by DetectImportFormat parses.

func ParseOpenAPIDocument

func ParseOpenAPIDocument(data []byte) (*models.ImportPlan, error)

ParseOpenAPIDocument parses an OpenAPI 3.x document into a models.ImportPlan per spec §8.3. Path items are walked in sorted path order and each operation key (get/post/put/delete/patch/head/options/trace) in the fixed method order; other path-item keys (parameters, summary, ...) and root-level servers are ignored, as are schemas not reachable from any path. The operation name falls back summary → operationId → "METHOD /path"; the group is the first tag, else "Imported". Request and response ParamNodes come from the application/json schema of requestBody and of the first informative response ("200", then an any-case "2XX", then "default"), inverting NodesToJSONSchema. An operation marked "x-knot-type": "rpc" imports as Type "RPC" with an empty method, round-tripping the OpenAPI exporter. $ref values are resolved against the document with a visited-set cycle guard and a depth cap; offending subtrees are skipped with recorded warnings. A UTF-8 BOM is tolerated so any file accepted by DetectImportFormat parses.

func ParsePostmanCollection

func ParsePostmanCollection(data []byte) (*models.ImportPlan, error)

ParsePostmanCollection parses a Postman Collection v2.0/v2.1 document into a models.ImportPlan per spec §8.3. item[] is walked recursively: an item with a nested item array is a folder whose group name flattens the nesting with "/" separators (top-level folders use their own name), while a lone top-level request lands in a group named after info.name. request.url and request.description each accept both the v2.1 object form and the plain-string (v2.0) form. An item carrying the custom property "x-knot-type": "rpc" imports as Type "RPC" with an empty method, mirroring the Postman exporter. A raw request body that parses as a JSON object is converted to request ParamNodes; unconvertible bodies record a warning instead of failing. A UTF-8 BOM is tolerated so any file accepted by DetectImportFormat parses.

Types

type APIWithParams

type APIWithParams struct {
	API                models.API
	GroupName          string
	GroupOrder         int
	RequestParameters  []models.Parameter
	ResponseParameters []models.Parameter
}

APIWithParams represents an API with its parameters separated by type

type ImportResult

type ImportResult = models.ImportResult

ImportResult is relocated to the models module (models v1.1); this alias keeps every services/handler reference and test compiling unchanged while the canonical definition ships with the shared data model.

func ApplyImport

func ApplyImport(db *gorm.DB, format models.ImportFormat, plan *models.ImportPlan, dryRun bool) (*ImportResult, error)

ApplyImport persists a models.ImportPlan into the database with merge semantics, per spec §8.4. The whole import runs inside one transaction: any failure rolls back every row written so far (all-or-nothing). For each plan group, a same-name group is merged into (APIs appended after that group's current max API order, the group's own order untouched); a missing group is created with an order continuing after the current max group order. Parameter trees are flattened to rows with ParentID links and a per-API, per-side sequential order starting at 0. There is no API-level deduplication: importing the same file twice duplicates APIs inside merged groups.

With dryRun=true the exact same resolution logic runs but no row is written, and the returned counts are the ones a real run would produce. Plan warnings are surfaced in Result.Warnings in both modes.

type OpenAPIContent

type OpenAPIContent struct {
	Schema map[string]interface{} `json:"schema"`
}

OpenAPIContent wraps one JSON Schema under a media type key.

type OpenAPIDocument

type OpenAPIDocument struct {
	OpenAPI string                      `json:"openapi"`
	Info    OpenAPIInfo                 `json:"info"`
	Tags    []OpenAPITag                `json:"tags,omitempty"`
	Paths   map[string]*OpenAPIPathItem `json:"paths"`
}

OpenAPIDocument is the root object of an OpenAPI 3.1 document built by Knot. Paths is a map because path keys are arbitrary endpoint strings.

func BuildOpenAPIDocument

func BuildOpenAPIDocument(apis []APIWithParams) *OpenAPIDocument

BuildOpenAPIDocument assembles an OpenAPI 3.1 document from APIs with their parameters. Tags are declared per group in first-appearance order (tracked with a seen-map over the input slice, never map iteration, so tag order is deterministic). Operations are keyed by endpoint path and lower-cased HTTP method; when the same endpoint+method is selected twice the operations merge: the first occurrence wins for summary/operationId and subsequent notes are appended to the description joined by a thematic break, in input order.

type OpenAPIInfo

type OpenAPIInfo struct {
	Title   string `json:"title"`
	Version string `json:"version"`
}

OpenAPIInfo identifies the exporting tool and the document version.

type OpenAPIOperation

type OpenAPIOperation struct {
	Summary     string                      `json:"summary"`
	Description string                      `json:"description,omitempty"`
	OperationID string                      `json:"operationId"`
	Tags        []string                    `json:"tags,omitempty"`
	XKnotType   string                      `json:"x-knot-type,omitempty"`
	RequestBody *OpenAPIRequestBody         `json:"requestBody,omitempty"`
	Responses   map[string]*OpenAPIResponse `json:"responses,omitempty"`
}

OpenAPIOperation describes one endpoint+method pair.

type OpenAPIPathItem

type OpenAPIPathItem struct {
	Get    *OpenAPIOperation `json:"get,omitempty"`
	Post   *OpenAPIOperation `json:"post,omitempty"`
	Put    *OpenAPIOperation `json:"put,omitempty"`
	Delete *OpenAPIOperation `json:"delete,omitempty"`
	Patch  *OpenAPIOperation `json:"patch,omitempty"`
}

OpenAPIPathItem holds the operations of one endpoint. Each field serializes as its lower-cased HTTP method key.

type OpenAPIRequestBody

type OpenAPIRequestBody struct {
	Required bool                       `json:"required"`
	Content  map[string]*OpenAPIContent `json:"content"`
}

OpenAPIRequestBody carries the request body schema and whether a body must be sent.

type OpenAPIResponse

type OpenAPIResponse struct {
	Description string                     `json:"description"`
	Content     map[string]*OpenAPIContent `json:"content,omitempty"`
}

OpenAPIResponse describes one HTTP response.

type OpenAPITag

type OpenAPITag struct {
	Name string `json:"name"`
}

OpenAPITag declares one API group as an OpenAPI tag.

type ParameterService

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

ParameterService handles parameter-related operations

func NewParameterService

func NewParameterService(db *gorm.DB) *ParameterService

NewParameterService creates a new ParameterService

func (*ParameterService) UpdateParameters

func (s *ParameterService) UpdateParameters(apiID uint, paramType string, parameters json.RawMessage) (int, error)

UpdateParameters updates parameters from structure for a specific API

func (*ParameterService) UpdateParametersFromJSON

func (s *ParameterService) UpdateParametersFromJSON(apiID uint, paramType string, jsonData map[string]interface{}) (int, error)

UpdateParametersFromJSON updates parameters from JSON example for a specific API

type PostmanBody

type PostmanBody struct {
	Mode    string             `json:"mode"`
	Raw     string             `json:"raw"`
	Options PostmanBodyOptions `json:"options"`
}

PostmanBody carries a raw request body plus its language hint.

type PostmanBodyOptions

type PostmanBodyOptions struct {
	Raw PostmanRawOptions `json:"raw"`
}

PostmanBodyOptions hints at the raw body language.

type PostmanCollection

type PostmanCollection struct {
	Info PostmanInfo   `json:"info"`
	Item []PostmanItem `json:"item"`
}

PostmanCollection is the root object of a Postman Collection v2.1 document built by Knot.

func BuildPostmanCollection

func BuildPostmanCollection(apis []APIWithParams, now time.Time) *PostmanCollection

BuildPostmanCollection assembles a Postman Collection v2.1 document from APIs with their parameters. Each API group becomes one folder item, created on the group's first appearance (tracked with a seen-map over the input slice, never map iteration, so folder order is deterministic); groups with zero selected APIs never appear because folders are only created for selected APIs. Request and response example bodies reuse the GenerateExampleJSON tree walker and are omitted when the API has no parameters on that side. RPC-like APIs are exported as POST requests carrying the x-knot-type marker so Knot's importer can restore their classification.

type PostmanHeader

type PostmanHeader struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

PostmanHeader is one header entry; exported collections carry none.

type PostmanInfo

type PostmanInfo struct {
	Name        string `json:"name"`
	PostmanID   string `json:"_postman_id"`
	Description string `json:"description,omitempty"`
	Schema      string `json:"schema"`
}

PostmanInfo identifies the collection and the schema it follows.

type PostmanItem

type PostmanItem struct {
	Name      string            `json:"name"`
	XKnotType string            `json:"x-knot-type,omitempty"`
	Item      []PostmanItem     `json:"item,omitempty"`
	Request   *PostmanRequest   `json:"request,omitempty"`
	Response  []PostmanResponse `json:"response,omitempty"`
}

PostmanItem is either a folder (one API group, only Name and Item set) or a request leaf (Name, Request and, when the API has response parameters, saved example responses).

type PostmanRawOptions

type PostmanRawOptions struct {
	Language string `json:"language"`
}

PostmanRawOptions names the language of a raw body.

type PostmanRequest

type PostmanRequest struct {
	Method      string          `json:"method"`
	Header      []PostmanHeader `json:"header"`
	URL         PostmanURL      `json:"url"`
	Description string          `json:"description,omitempty"`
	Body        *PostmanBody    `json:"body,omitempty"`
}

PostmanRequest describes how to send one request. Header is always an empty array: Knot documents bodies, not headers.

type PostmanResponse

type PostmanResponse struct {
	Name string `json:"name"`
	Body string `json:"body"`
}

PostmanResponse is one saved example response on a request item.

type PostmanURL

type PostmanURL struct {
	Raw string `json:"raw"`
}

PostmanURL holds the raw request URL.

Jump to

Keyboard shortcuts

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