components

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2026 License: MIT Imports: 8 Imported by: 0

Documentation

Overview

Package components — публичный фасад библиотеки для встраивания (docs/plan/01-architecture.md §2.4, docs/plan/04-module-functionality.md §1): тонкий реэкспорт внутреннего сервисного слоя, импортёра файлов наполнения и REST /api/v1 — вместе с типами domain и catalog из их сигнатур — без перестройки слоёв. Внешний модуль импортирует только этот пакет: пакеты internal/ за пределами модуля недоступны, алиасы открывают типы внутреннего API под публичными именами (это те же типы, не копии).

app, err := components.Open(ctx, components.Config{
	Dialect: "sqlite", DSN: "catalog.db", EnsureCreated: true,
})
if err != nil { … }
defer app.Close()

mux.Handle("/api/v1/", app.Handler())
page, err := app.Services.Devices.Search(ctx, components.SearchQuery{
	Kind: components.KindTransistor, Query: "КТ3",
})

Готовый пример встраивания — examples/embed: внешний модуль с replace на локальный путь, сборка и запуск — фаза consumer QA-прогонщика.

Index

Constants

View Source
const (
	ValueExact   = catalog.ValueExact
	ValueAtLeast = catalog.ValueAtLeast
	ValueAtMost  = catalog.ValueAtMost
	ValueRange   = catalog.ValueRange
	ValueLimits  = catalog.ValueLimits
	ValueText    = catalog.ValueText
	ValueEnum    = catalog.ValueEnum
)
View Source
const (
	AttrText     = catalog.AttrText
	AttrTextList = catalog.AttrTextList
	AttrBool     = catalog.AttrBool
	AttrInt      = catalog.AttrInt
	AttrNumber   = catalog.AttrNumber
	AttrEnum     = catalog.AttrEnum
)
View Source
const (
	ModeRequired = catalog.ModeRequired
	ModeOptional = catalog.ModeOptional
)
View Source
const (
	KindTransistor = domain.KindTransistor
	KindDiode      = domain.KindDiode
	KindResistor   = domain.KindResistor
	KindCapacitor  = domain.KindCapacitor
	KindRelay      = domain.KindRelay
)
View Source
const (
	SystemGost  = domain.SystemGost
	SystemOst   = domain.SystemOst
	SystemPro   = domain.SystemPro
	SystemJedec = domain.SystemJedec
	SystemJis   = domain.SystemJis
	SystemOther = domain.SystemOther
)
View Source
const (
	FormatJSONC  = importer.FormatJSONC
	FormatYAML   = importer.FormatYAML
	FormatNDJSON = importer.FormatNDJSON
)
View Source
const (
	OutcomeAdded           = service.OutcomeAdded
	OutcomeUpdatedExisting = service.OutcomeUpdatedExisting
	OutcomeSkipped         = service.OutcomeSkipped
)
View Source
const (
	OpEq  = service.OpEq
	OpGte = service.OpGte
	OpLte = service.OpLte
)
View Source
const (
	SearchDefaultLimit  = service.SearchDefaultLimit
	SearchLimitMax      = service.SearchLimitMax
	SearchIDsMax        = service.SearchIDsMax
	SearchValuesMax     = service.SearchValuesMax
	SuggestDefaultLimit = service.SuggestDefaultLimit
	SuggestLimitMax     = service.SuggestLimitMax
	ChangesDefaultLimit = service.ChangesDefaultLimit
	ChangesLimitMax     = service.ChangesLimitMax
)
View Source
const (
	ChangeOpCreated = service.ChangeOpCreated
	ChangeOpUpdated = service.ChangeOpUpdated
	ChangeOpDeleted = service.ChangeOpDeleted
)

Variables

This section is empty.

Functions

This section is empty.

Types

type AnalogInput

type AnalogInput = service.AnalogInput

type App

type App struct {
	Services Services
	Importer *Importer
	// contains filtered or unexported fields
}

App — открытое приложение фасада: сервисный слой (Services), импортёр файлов наполнения (Importer) и REST-обработчик (Handler). Безопасно для одновременного использования несколькими горутинами; Close — обязанность владельца (сайт создаёт App при старте и закрывает при завершении).

func Open

func Open(ctx context.Context, cfg Config) (*App, error)

Open открывает приложение по конфигурации (план 01 §2.4): сервисный слой поверх хранилища (при EnsureCreated — DDL и сиды каталога на пустую базу, docs/plan/02-database.md §5.3) и REST-транспорт /api/v1 над ним.

func (*App) Close

func (a *App) Close() error

Close закрывает приложение (пулы соединений).

func (*App) Handler

func (a *App) Handler() http.Handler

Handler возвращает http.Handler REST /api/v1 для монтирования в роутер сайта (http.ServeMux: mux.Handle("/api/v1/", app.Handler())).

func (*App) Revisions

func (a *App) Revisions(ctx context.Context) (catalogRev, dataRev int64, err error)

Revisions возвращает текущие счётчики catalog_revision и data_revision (ETag REST — docs/plan/02-database.md §5.5).

func (*App) Snapshot

func (a *App) Snapshot(ctx context.Context) (*Snapshot, error)

Snapshot возвращает актуальный снимок каталога (кэш с проверкой catalog_revision на каждом обращении).

func (*App) Stats

func (a *App) Stats(ctx context.Context) (Stats, error)

Stats собирает агрегаты приложения: количества записей по классам, версия схемы модуля и счётчики ревизий.

type AttrType

type AttrType = catalog.AttrType

type AttributeDef

type AttributeDef = catalog.AttributeDef

type AttributeFilter

type AttributeFilter = service.AttributeFilter

type AttributeValue

type AttributeValue = catalog.AttributeValue

type Card

type Card = service.Card

type CardAttribute

type CardAttribute = service.CardAttribute

type CardGroup

type CardGroup = service.CardGroup
type CardLink = service.CardLink

type CardSource added in v0.3.0

type CardSource = service.CardSource

type CardSynonym added in v0.0.8

type CardSynonym = service.CardSynonym

type CardTypeDiff

type CardTypeDiff = service.CardTypeDiff

type CardTypeGroup

type CardTypeGroup = service.CardTypeGroup

type CardTypeSibling

type CardTypeSibling = service.CardTypeSibling

type CardTypeValue

type CardTypeValue = service.CardTypeValue

type CardValue

type CardValue = service.CardValue

type CardVariant

type CardVariant = service.CardVariant

type CatalogInput

type CatalogInput = catalog.Input

type CatalogService

type CatalogService = service.CatalogService

type CategoryDef

type CategoryDef = catalog.CategoryDef

type ChangeEvent

type ChangeEvent = service.ChangeEvent

type ChangeOp

type ChangeOp = service.ChangeOp

type ChangesPage

type ChangesPage = service.ChangesPage

type Code

type Code = domain.Code

type ConditionDef

type ConditionDef = catalog.ConditionDef

type ConditionMode

type ConditionMode = catalog.ConditionMode

type ConditionSet

type ConditionSet = catalog.ConditionSet

type ConditionSetItem

type ConditionSetItem = catalog.ConditionSetItem

type ConditionValue

type ConditionValue = catalog.ConditionValue

type Config

type Config struct {
	Dialect        string // "sqlite" | "postgres"
	DSN            string // путь файла sqlite / DSN postgres
	Pool           PoolConfig
	Log            *slog.Logger
	EnsureCreated  bool
	DisableSuggest bool
	Metrics        Metrics
}

Config — конфигурация открытия приложения (план 04 §1): хранилище (Dialect/DSN/Pool), журнал, EnsureCreated (DDL и сиды каталога на пустую базу) и опции REST-транспорта Handler(): DisableSuggest (не монтировать GET /suggest) и Metrics (хук счётчиков сайта).

type DesignationService

type DesignationService = service.DesignationService

type DeviceInput

type DeviceInput = service.DeviceInput

type DeviceService

type DeviceService = service.DeviceService

type Error

type Error = domain.Error

func AsError

func AsError(err error) (*Error, bool)

AsError извлекает *Error из цепочки ошибок.

type Field

type Field = domain.Field

type FieldFilter

type FieldFilter = service.FieldFilter

type FilterOp

type FilterOp = service.FilterOp

type FindResult

type FindResult = service.FindResult

type Format

type Format = importer.Format

type GroupDef

type GroupDef = catalog.GroupDef

type ImportIssue

type ImportIssue = importer.Issue

type ImportOption

type ImportOption = importer.ImportOption

ImportOption — опция прогона Importer.Import.

func WithProgress

func WithProgress(fn func(Progress)) ImportOption

WithProgress — колбэк прогресса прогона импорта: вызывается после каждой прочитанной записи потока NDJSON (форматы-документы отмечают чтение одним вызовом) и по итоговому исходу применения каждой записи.

type ImportReport

type ImportReport = importer.Report

type Importer

type Importer = importer.Importer

type Kind

type Kind = domain.Kind

type KindDef

type KindDef = catalog.KindDef

type KindRuleRef

type KindRuleRef = catalog.KindRuleRef

type Metrics

type Metrics = httpapi.Metrics

Metrics — хук метрик REST (docs/plan/04-module-functionality.md §5): счётчики и длительности вызовов по операциям; реализация — на стороне сайта, модуль свой экспорт метрик не заводит. errCode — код ошибки домена ("" — успешный запрос).

type MsgID

type MsgID = domain.MsgID

type Outcome

type Outcome = service.Outcome

type ParameterDef

type ParameterDef = catalog.ParameterDef

type ParameterFilter

type ParameterFilter = service.ParameterFilter

type ParameterStat

type ParameterStat = service.ParameterStat

type ParameterStats

type ParameterStats = service.ParameterStats

type ParameterValue

type ParameterValue = catalog.ParameterValue

type ParameterValueFreq

type ParameterValueFreq = service.ParameterValueFreq

type ParsedDesignation

type ParsedDesignation = domain.ParsedDesignation

type PendingDesignations

type PendingDesignations = service.PendingDesignations

type PoolConfig

type PoolConfig = service.PoolConfig

type Progress

type Progress = importer.Progress

Progress — снимок прогресса прогона: нарастающие счётчики чтения файла и применения записей.

type RuleDef

type RuleDef = catalog.RuleDef

type SearchItem

type SearchItem = service.SearchItem

type SearchPage

type SearchPage = service.SearchPage

type SearchQuery

type SearchQuery = service.SearchQuery

type SearchValue added in v0.0.7

type SearchValue = service.SearchValue

type SectionInput

type SectionInput = service.SectionInput

type Services

type Services = service.Services

type Snapshot

type Snapshot = catalog.Snapshot

type SortField

type SortField = service.SortField

type SourceInput added in v0.3.0

type SourceInput = service.SourceInput

type SourceRefInput added in v0.3.0

type SourceRefInput = service.SourceRefInput

type SourceService added in v0.3.0

type SourceService = service.SourceService

type Stats

type Stats = service.Stats

type Suggestion

type Suggestion = service.Suggestion

type SynonymInput added in v0.0.8

type SynonymInput = service.SynonymInput

type System

type System = domain.System

type SystemDef

type SystemDef = catalog.SystemDef

type SystemKindRef

type SystemKindRef = catalog.SystemKindRef

type UnitDef

type UnitDef = catalog.UnitDef

type ValueColumn added in v0.0.7

type ValueColumn = service.ValueColumn

type ValueType

type ValueType = catalog.ValueType

type VariantInput

type VariantInput = service.VariantInput

Jump to

Keyboard shortcuts

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