fhirpath

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Sep 26, 2026 License: Apache-2.0 Imports: 18 Imported by: 0

README

haistack-fhirpath (pkg/fhirpath)

In-memory FHIRPath evaluation for a single FHIR resource at a time.

What it does

FHIRPath is a small query language for FHIR — like XPath for XML. You write expressions such as:

  • Patient.name.given — given names
  • Patient.telecom.where(system = 'phone').value — phone numbers
  • Observation.value.ofType(Quantity).value — a numeric observation value

This package runs those expressions against a Patient, Observation, or other resource you already have in memory. It does not search a database or fetch resources by itself; it only reads fields from a resource you pass in.

The implementation wraps github.com/verily-src/fhirpath-go behind a stable haistack API (Engine, CompiledExpression, Value).

Does not: import store, sqlite, or postgres; evaluate across resource graphs without an optional Resolve backend; accept raw JSON maps as roots (use ResourceEnvelope or R4 proto).

How it fits in the ecosystem

FHIRPath answers “what is inside this resource?” Search answers “which resources match?” ViewDefinitions project many resources into rows.

                    ┌─────────────────────────────────────┐
                    │  FHIR Search (pkg/search)           │
                    │  Registry SearchParameter.expression│
                    └──────────────┬──────────────────────┘
                                   │ index write path
                                   ▼
              RegistryIndexer ──► fhirpath.Eval ──► normalized index tokens
                                   │
     ViewDefinition where/select ──┼──► fhirpath (parse + execute)
                                   │
     SDC calculatedExpression ─────┼──► fhirpath (+ SDC custom fns)
                                   │
     Subscription FilterFHIRPath ──┘
Consumer Role of fhirpath
pkg/search RegistryIndexer evaluates SearchParameter expressions
pkg/view ViewDefinition filters and column paths at parse and scan time
pkg/sdc Questionnaire text/fhirpath items; NewSDCFHIRPathEngine adds weight()
pkg/subscriptions Matcher.FilterFHIRPath on change events
pkg/structuremap Shared engine for map-dependent logic
cmd/haistack haistack fhirpath eval for local debugging

When to use it

  • Extracting fields from a resource already loaded in memory (UI, validation, indexing)
  • Compiling hot-path expressions once (Compile) and reusing across many resources
  • Wiring search indexing when registry SearchParameters use FHIRPath expressions
  • Parsing ViewDefinitions or SDC questionnaires that reference FHIRPath
  • Optional: enabling resolve() or terminology functions when you configure resolvers

Prefer pkg/search for “find all Patients named Smith”, not FHIRPath over the whole database.

Usage modes

Mode: Direct evaluation (CLI or application)

One-shot or compiled evaluation against an envelope or R4 proto:

eng, err := fhirpath.NewEngine(fhirpath.Config{})
ctx := context.Background()

values, err := eng.Eval(ctx, "Patient.name.given", envelope)
name, err := eng.EvalString(ctx, "Patient.name.given.first()", envelope)

compiled, _ := eng.Compile("Patient.telecom.where(system = 'phone').value")
phones, _ := compiled.Eval(ctx, envelope)

CLI: haistack fhirpath eval patient.json 'Patient.name.family'.

Mode: Search indexing
indexer, err := search.NewRegistryIndexer(search.RegistryIndexerConfig{
    Registry: search.NewSnapshotRegistry(snapshot),
    Engine:   fhirpathEngine,
})

Param matching: search.MatchResourceParameter(ctx, reg, engine, "Observation", envelope, "code", wantTokens).

Mode: ViewDefinition execution
parser, _ := view.NewDefinitionParser(engine)
spec, _ := parser.Parse(viewDefinitionJSON)
reg := view.NewRegistry()
_, _ = reg.Register(spec, engine)
exec, _ := view.NewExecutor(view.Config{Resources: resourceStore, Engine: engine, Registry: reg})
result, _ := exec.Execute(ctx, view.ExecuteRequest{ViewName: spec.Name})
Mode: SDC questionnaires
engine, err := sdc.NewSDCFHIRPathEngine(fhirpath.Config{})

Use with sdc.ComposeExpressions for calculated, initial, and constraint fields.

Mode: Subscriptions and filters
trigger := subscriptions.Trigger{
    ResourceType: "Observation", Event: subscriptions.TriggerEventCreate,
    FilterFHIRPath: "code.coding.code = '8867-4'",
}
matcher := &subscriptions.Matcher{Engine: engine, Registry: searchRegistry}

Examples

Envelope vs proto roots — prefer *types.ResourceEnvelope; proto path used when envelope.Proto is set or when passing *patient_go_proto.Patient directly. Raw []byte and map[string]any return ErrInvalidInput.

Custom functions at engine creation:

eng, _ := fhirpath.NewEngine(fhirpath.Config{
    Functions: map[string]fhirpath.Function{ /* see README tests */ },
    FunctionArity: map[string]int{"echoPrefix": 1},
})

Optional resolve() and terminology:

eng, _ := fhirpath.NewEngine(fhirpath.Config{
    Resolve:     fhirpath.ResourceStoreResolver(resources.Read),
    Terminology: fhirpath.TerminologyServiceAdapter(myValidateCode),
})

See pkg/fhirpath/fhirpath_env_test.go and engine_test.go for navigation, aggregates, and error cases.

Configuration / key types

Type / field Role
Engine Eval, Compile, EvalString, EvalBool, EvalWithEnv
Config.CacheSize Default 256 compiled-expression cache entries
Config.MaxExpressionLen Default 4096
Config.MaxResultItems Default 1024
Config.ProtoCodec Default proto.NewGoogleR4Codec() for JSON envelopes
Config.Resolve / Terminology Opt-in backends for advanced functions
Value Result item with Type(), String(), Bool(), Raw()

Stable errors: ErrInvalidInput, ErrExpressionTooLong, ErrTooManyResults, ErrEmptyResult, ErrNotSingleton, ErrTypeMismatch, ErrNotSupported, ErrShadowsBuiltin.

Where it fits

Layer Role
types ResourceEnvelope input
proto R4 proto codec and envelope proto field
fhirpath Expression engine (this package)
search / view / sdc Primary consumers

Limits

  • One resource root per evaluation (no graph queries without Resolve)
  • Google FHIR R4 proto only for typed roots
  • Full normative FHIRPath compliance not guaranteed beyond tested subset
  • resolve() / memberOf() require explicit configuration
  • Does not persist or mutate resources

Documentation

Overview

Package fhirpath implements haistack-fhirpath, an in-memory FHIRPath expression engine for the haistack runtime.

haistack-fhirpath wraps github.com/verily-src/fhirpath-go behind a stable haistack-facing API. Callers compile and evaluate FHIRPath expressions against a single FHIR resource at a time without importing the upstream library or Google FHIR protobuf paths directly.

Role in the stack

FHIRPath reads fields inside already-selected resources. FHIR Search finds resources. ViewDefinitions build reusable projections. This package is the expression layer only:

  • It does not query databases or search indexes.
  • It does not parse FHIR search query strings.
  • It does not resolve references across a server (resolve() is rejected).
  • It does not call terminology services (memberOf() is rejected).

Typical consumers are pkg/search (index field extraction), pkg/view (ViewDefinition projections), pkg/ai (typed tool preconditions), and future conflict or subscription packages that need path-based field access on envelopes already loaded from storage.

Design principles

Single-resource, in-memory evaluation:

  • Every evaluation path accepts exactly one root resource.
  • The resource becomes the sole item in the FHIRPath input collection.
  • Multi-resource collections, database handles, and search queries are rejected.

JSON-first runtime, proto-aware evaluation:

  • types.ResourceEnvelope.JSON remains the canonical stored form across haistack.
  • When envelope.Proto is populated (via pkg/proto), evaluation uses the typed proto directly without re-parsing JSON.
  • When envelope.Proto is nil, the engine lazily parses envelope.JSON through Config.ProtoCodec (default: proto.NewGoogleR4Codec()) before evaluation.

Stable public surface:

  • Exported types use haistack names (Engine, Value, Collection).
  • Upstream Verily and Google FHIR types stay behind Value.Raw() and the internal/verily adapter subpackage.
  • Compile and CompiledExpression values are safe for concurrent use.

Bounded execution:

  • Expression length and result collection size are capped by configuration.
  • Context deadlines are honored on every evaluation path.
  • DefaultTimeout applies only when the caller context has no earlier deadline.
  • Timeout enforcement is soft (see Timeouts below).

Immutable custom-function registry:

  • Custom functions are bound at engine construction and cannot be changed later.
  • Custom function names must not shadow built-in FHIRPath functions.
  • Cache keys are expression strings only because the function table is fixed for the lifetime of the engine.

Backend

The sole MVP backend is github.com/verily-src/fhirpath-go, which evaluates expressions against Google FHIR R4 protobuf messages. The concrete adapter lives in pkg/fhirpath/internal/verily and is not importable outside this module tree.

Broader upstream FHIRPath support may exist but is not part of the haistack MVP contract unless covered by tests in this package. Full normative compliance, advanced type checking, terminology-backed functions, expression tracing, optimizer work, and hard process isolation are deferred.

Engine interface

Compile(expr string) (CompiledExpression, error)
Eval(ctx context.Context, expr string, resource any) ([]Value, error)
EvalBool(ctx context.Context, expr string, resource any) (bool, error)
EvalString(ctx context.Context, expr string, resource any) (string, error)

Compile parses and compiles a FHIRPath expression. Repeated calls with the same source string return a cached CompiledExpression. Compile is safe to call concurrently on the same Engine.

Eval compiles (or reuses a cached compile) and evaluates the expression, returning the full result collection as []Value.

EvalBool and EvalString apply strict singleton coercion (see Coercion rules).

Construct an engine with NewEngine:

eng, err := fhirpath.NewEngine(fhirpath.Config{})
if err != nil {
    return err
}

CompiledExpression interface

Expr() string
Eval(ctx context.Context, resource any) ([]Value, error)
EvalBool(ctx context.Context, resource any) (bool, error)
EvalString(ctx context.Context, resource any) (string, error)

A CompiledExpression holds a parsed expression bound to the custom-function table configured on the Engine that created it. It is safe to evaluate concurrently from multiple goroutines.

Prefer Compile when the same expression is evaluated many times against different resources:

compiled, err := eng.Compile("Patient.telecom.where(system = 'phone').value")
if err != nil {
    return err
}
for _, env := range envelopes {
    values, err := compiled.Eval(ctx, env)
    // ...
}

Evaluation inputs

Accepted root inputs:

  • *types.ResourceEnvelope — preferred runtime container from pkg/core and stores.
  • Google FHIR R4 protobuf resources recognized by pkg/proto.IsProtoResource, including individual resource messages (for example *patient_go_proto.Patient) and *ContainedResource values with a populated oneof branch.

Rejected root inputs (return ErrInvalidInput):

  • Raw JSON []byte
  • map[string]any or other decoded JSON structures
  • Arbitrary Go structs
  • nil envelopes without JSON or proto payload
  • Unsupported or non-R4 proto values

Resource adaptation for envelopes:

  • When envelope.Proto is non-nil and supported, it is unwrapped (ContainedResource values yield the inner resource message) and passed to the backend.
  • When envelope.Proto is nil, envelope.JSON is parsed through ProtoCodec.
  • envelope.ResourceType is forwarded to ParseJSONToProto for optional type checks.

Value and Collection

Evaluation returns a Collection ([]Value). Each Value wraps one FHIRPath result item from the backend.

Value helpers:

  • Type() string — stable type name (Boolean, String, Patient, HumanName, …)
  • Raw() any — backend-native item; use only when integrating with proto-aware code
  • Bool() (bool, error)
  • String() (string, error)
  • Float64() (float64, error)

Helper methods return ErrTypeMismatch when the wrapped item is not coercible to the requested type. Prefer EvalBool and EvalString on Engine or CompiledExpression when a singleton boolean or string is required.

Coercion rules

EvalBool and EvalString enforce stricter rules than the upstream evaluator:

  • Empty collection → ErrEmptyResult
  • More than one item → ErrNotSingleton
  • One item, wrong type → ErrTypeMismatch

Eval returns the full collection without coercion. An empty collection is represented as nil []Value.

Config

Config fields and defaults (zero values replaced at NewEngine):

  • ProtoCodec — default proto.NewGoogleR4Codec()
  • Functions — custom FHIRPath functions; default empty map
  • FunctionArity — FHIRPath argument count per custom function name; default 0
  • CacheSize — default 256 (DefaultCacheSize)
  • DefaultTimeout — default 0 (no implicit deadline beyond caller context)
  • MaxExpressionLen — default 4096 (DefaultMaxExpressionLen)
  • MaxResultItems — default 1024 (DefaultMaxResultItems)

MaxCustomFunctionArity (8) is the maximum supported FunctionArity value.

Custom functions

Register application-specific FHIRPath functions through Config.Functions. Each entry maps a FHIRPath function name to a Go callback:

type Function func(input Collection, args ...Collection) (Collection, error)

The input collection is the current FHIRPath focus collection. Each entry in args is the evaluated result of one FHIRPath argument expression, wrapped as a haistack Collection (one collection per argument).

Set Config.FunctionArity[name] to the number of FHIRPath arguments the function accepts. Omitted names default to arity 0 (niladic calls such as customFn()). Each FHIRPath argument must evaluate to a singleton upstream; the adapter wraps that singleton as a one-item Collection before invoking the callback.

Example — niladic custom function:

eng, err := fhirpath.NewEngine(fhirpath.Config{
    Functions: map[string]fhirpath.Function{
        "alwaysTrue": func(_ fhirpath.Collection, _ ...fhirpath.Collection) (fhirpath.Collection, error) {
            return fhirpath.Collection{fhirpath.NewValue(system.Boolean(true))}, nil
        },
    },
})

Example — unary custom function:

eng, err := fhirpath.NewEngine(fhirpath.Config{
    Functions: map[string]fhirpath.Function{
        "echoPrefix": func(_ fhirpath.Collection, args ...fhirpath.Collection) (fhirpath.Collection, error) {
            s, err := args[0][0].String()
            if err != nil {
                return nil, err
            }
            return fhirpath.Collection{fhirpath.NewValue(system.String("prefix-" + s))}, nil
        },
    },
    FunctionArity: map[string]int{"echoPrefix": 1},
})
// Expression: echoPrefix('hello')  →  "prefix-hello"

Custom function names that conflict with built-in FHIRPath functions cause NewEngine to return ErrShadowsBuiltin.

Timeouts

Evaluation honors context cancellation and deadlines on every path. When Config.DefaultTimeout is greater than zero and the caller context has no existing deadline, NewEngine-derived evaluation wraps the call in a timeout context of that duration.

Because the upstream evaluator has no native cancellation hook, timeout enforcement is soft: the wrapper returns context.DeadlineExceeded when the deadline is reached but does not force-stop upstream computation already running in a background goroutine.

Errors

Stable sentinel errors:

  • ErrInvalidInput — unsupported evaluation root type
  • ErrExpressionTooLong — expression exceeds MaxExpressionLen
  • ErrTooManyResults — result collection exceeds MaxResultItems
  • ErrEmptyResult — EvalBool/EvalString on empty collection
  • ErrNotSingleton — EvalBool/EvalString on multi-item collection
  • ErrTypeMismatch — EvalBool/EvalString or Value helper coercion failure
  • ErrShadowsBuiltin — custom function name conflicts with a built-in
  • ErrNotSupported — expression requires resolve(), terminology, or other capabilities excluded from the MVP contract

Compile and evaluation may also return upstream parse or evaluation errors, context.Canceled, and context.DeadlineExceeded.

MVP expression subset

Tests in this package guarantee support for common navigation and collection operations, including:

  • Field navigation (Patient.name.given)
  • Filtering (Patient.telecom.where(system = 'phone').value)
  • Type filtering (Observation.value.ofType(Quantity).value)
  • Existence, subsetting, and aggregates (exists(), where(), first(), count())
  • Comparisons and boolean operators

Expressions that call resolve() or experimental terminology functions such as memberOf() return ErrNotSupported.

Integration with other packages

pkg/types — ResourceEnvelope is the primary evaluation input; JSON is canonical. pkg/proto — GoogleR4Codec parses envelope JSON when Proto is nil; IsProtoResource gates direct proto inputs. pkg/search — future Indexer implementations may use fhirpath to extract index fields. pkg/view — future ViewDefinition execution may project envelope fields via FHIRPath. pkg/ai — future typed tools may evaluate preconditions on loaded resources. pkg/core — does not depend on fhirpath directly; resources reach fhirpath after load.

pkg/fhirpath must not import pkg/store, pkg/sqlite, pkg/postgres, or other query backends.

Typical flows

Evaluate a path on a stored envelope:

eng, _ := fhirpath.NewEngine(fhirpath.Config{})
given, err := eng.EvalString(ctx, "Patient.name.given", envelope)

Extract multiple values for indexing:

values, err := eng.Eval(ctx, "Patient.telecom.where(system = 'phone').value", envelope)
for _, v := range values {
    phone, _ := v.String()
    // index phone
}

Reuse a compiled expression in a hot loop:

compiled, _ := eng.Compile("Observation.value.ofType(Quantity).value")
for _, obs := range observations {
    values, err := compiled.Eval(ctx, obs)
    // ...
}

File layout

  • doc.go — package documentation (this file)
  • api.go — Engine, CompiledExpression, Config, Function, Collection
  • errors.go — stable sentinel errors
  • value.go — Value type and coercion helpers
  • engine.go — NewEngine and evaluation orchestration
  • adapt.go — custom-function adapter and error mapping
  • cache.go — thread-safe compile cache
  • fhirpath_test.go — MVP contract tests
  • internal/verily/ — Verily backend adapter (compile, evaluate, resource input)

Out of scope (MVP)

FHIR search execution, database querying, multi-resource root collections, raw JSON evaluation inputs, external constant variables (%name), terminology service integration, reference resolution (resolve()), expression tracing, R5 proto providers, hard process isolation, and CLI commands (future cmd/haistack fhirpath eval). Full FHIRPath normative compliance beyond the tested subset is not guaranteed.

Index

Constants

View Source
const DefaultCacheSize = 256

DefaultCacheSize is the default compile-cache capacity.

View Source
const DefaultMaxExpressionLen = 4096

DefaultMaxExpressionLen is the default maximum FHIRPath source length.

View Source
const DefaultMaxResultItems = 1024

DefaultMaxResultItems is the default maximum number of items in a result collection.

View Source
const MaxCustomFunctionArity = 8

MaxCustomFunctionArity is the maximum number of FHIRPath arguments a custom function may declare.

Variables

View Source
var (
	// ErrInvalidInput is returned when the evaluation root is not a supported type.
	ErrInvalidInput = errors.New("fhirpath: invalid evaluation input")

	// ErrExpressionTooLong is returned when an expression exceeds MaxExpressionLen.
	ErrExpressionTooLong = errors.New("fhirpath: expression exceeds maximum length")

	// ErrTooManyResults is returned when evaluation exceeds MaxResultItems.
	ErrTooManyResults = errors.New("fhirpath: result collection exceeds maximum size")

	// ErrNotSingleton is returned when EvalBool or EvalString requires exactly one value.
	ErrNotSingleton = errors.New("fhirpath: result is not a singleton collection")

	// ErrEmptyResult is returned when EvalBool or EvalString requires a non-empty result.
	ErrEmptyResult = errors.New("fhirpath: result collection is empty")

	// ErrTypeMismatch is returned when a singleton result is not coercible to the target type.
	ErrTypeMismatch = errors.New("fhirpath: result type does not match requested coercion")

	// ErrShadowsBuiltin is returned when a custom function name conflicts with a built-in.
	ErrShadowsBuiltin = errors.New("fhirpath: custom function shadows a built-in name")

	// ErrNotSupported is returned for expressions requiring terminology, resolve(), or
	// other capabilities excluded from the MVP contract.
	ErrNotSupported = errors.New("fhirpath: expression requires unsupported capability")
)
View Source
var DefaultLogicalIDResourceTypes = []string{
	"Patient", "Practitioner", "RelatedPerson", "Organization", "Location",
	"Encounter", "Appointment", "Observation", "Condition", "Procedure",
	"Device", "Medication", "MedicationRequest", "DiagnosticReport",
}

DefaultLogicalIDResourceTypes lists common FHIR resource types for urn:uuid lookup.

Functions

func EvaluationResource

func EvaluationResource(ctx context.Context) any

EvaluationResource returns the resource attached by WithEvaluationResource.

func LookupLogicalIDAcrossTypes

func LookupLogicalIDAcrossTypes(
	read func(ctx context.Context, resourceType, id string) (any, error),
	resourceTypes []string,
) func(ctx context.Context, logicalID string) (resourceType, id string, ok bool)

LookupLogicalIDAcrossTypes tries Read for each resource type until one succeeds.

func ParseReferenceForRead

func ParseReferenceForRead(raw, baseURL string) (resourceType, id string, ok bool)

ParseReferenceForRead extracts a resource type and id suitable for store.Read. It accepts typed relative references, absolute FHIR REST URLs, and urn:uuid references when the UUID is used directly as the logical id.

func ReferenceStringFromProto

func ReferenceStringFromProto(ref *dtpb.Reference) (string, bool)

ReferenceStringFromProto extracts a reference string from a Google FHIR Reference proto.

func ResolveContainedReference

func ResolveContainedReference(parent any, fragment string) (any, bool)

ResolveContainedReference resolves a #fragment against a containing resource map or envelope.

func ResolveContainedReferenceAsEnvelope

func ResolveContainedReferenceAsEnvelope(parent any, fragment string) (*types.ResourceEnvelope, bool)

ResolveContainedReferenceAsEnvelope resolves a contained reference to a ResourceEnvelope.

func WithEvaluationResource

func WithEvaluationResource(ctx context.Context, resource any) context.Context

WithEvaluationResource attaches the resource currently under evaluation to ctx. resolve() uses it to resolve contained #fragment references.

Types

type Collection

type Collection []Value

Collection is the FHIRPath result type: an ordered list of values.

type CompiledExpression

type CompiledExpression interface {
	Expr() string
	Eval(ctx context.Context, resource any) ([]Value, error)
	EvalWithEnv(ctx context.Context, resource any, env map[string]any) ([]Value, error)
	EvalBool(ctx context.Context, resource any) (bool, error)
	EvalString(ctx context.Context, resource any) (string, error)
}

CompiledExpression is a compiled FHIRPath expression safe for concurrent evaluation.

type Config

type Config struct {
	ProtoCodec       proto.ProtoCodec
	Functions        map[string]Function
	FunctionArity    map[string]int
	CacheSize        int
	DefaultTimeout   time.Duration
	MaxExpressionLen int
	MaxResultItems   int
	// Resolve enables resolve() by looking up reference strings at evaluation time.
	Resolve ResolveFunc
	// Terminology enables memberOf() via the experimental FHIRPath function table.
	Terminology TerminologyValidator
}

Config configures a FHIRPath engine.

type Engine

type Engine interface {
	Compile(expr string) (CompiledExpression, error)
	Eval(ctx context.Context, expr string, resource any) ([]Value, error)
	EvalWithEnv(ctx context.Context, expr string, resource any, env map[string]any) ([]Value, error)
	EvalBool(ctx context.Context, expr string, resource any) (bool, error)
	EvalString(ctx context.Context, expr string, resource any) (string, error)
}

Engine evaluates FHIRPath expressions against a single in-memory resource.

func NewEngine

func NewEngine(cfg Config) (Engine, error)

NewEngine constructs a FHIRPath engine backed by github.com/verily-src/fhirpath-go.

Soft timeout behavior: when DefaultTimeout is set and the caller context has no earlier deadline, evaluation runs under a derived timeout context. Because the upstream evaluator has no cancellation hook, timeout enforcement is best-effort: the wrapper returns context.DeadlineExceeded when the deadline is reached but does not force-stop upstream computation already in flight.

type Function

type Function func(input Collection, args ...Collection) (Collection, error)

Function is a custom FHIRPath function registered at engine construction time. The first argument is the input collection; remaining arguments are evaluated expression results passed as collections (one collection per FHIRPath argument).

Set Config.FunctionArity[name] to the number of FHIRPath arguments the function accepts (0 for niladic calls). Each FHIRPath argument must evaluate to a singleton upstream; the adapter wraps that value as a one-item Collection.

type ResolveFunc

type ResolveFunc func(ctx context.Context, ref string) (any, error)

ResolveFunc resolves one FHIR reference string to a resource envelope or proto.

func EnhancedResourceStoreResolver

func EnhancedResourceStoreResolver(cfg ResourceResolverConfig) ResolveFunc

EnhancedResourceStoreResolver resolves references using ResourceResolverConfig.

func ResourceStoreResolver

func ResourceStoreResolver(read func(ctx context.Context, resourceType, id string) (any, error)) ResolveFunc

ResourceStoreResolver returns a ResolveFunc backed by store.ResourceStore.Read. It resolves typed relative references, absolute REST URLs, and urn:uuid ids.

func WrapResolveWithEvaluationResource

func WrapResolveWithEvaluationResource(fn ResolveFunc) ResolveFunc

WrapResolveWithEvaluationResource enables resolve() for contained #fragment references.

type ResourceResolverConfig

type ResourceResolverConfig struct {
	Read             func(ctx context.Context, resourceType, id string) (any, error)
	BaseURL          string
	ResolveLogicalID func(ctx context.Context, logicalID string) (resourceType, id string, ok bool)
}

ResourceResolverConfig configures reference resolution for resolve() and joins.

type SubsumptionValidator

type SubsumptionValidator interface {
	Subsumes(ctx context.Context, system, broadCode, narrowCode string) (bool, error)
}

SubsumptionValidator checks whether broadCode subsumes narrowCode in a code system.

type TerminologyValidator

type TerminologyValidator interface {
	MemberOf(ctx context.Context, valueSetURL, system, code string) (bool, error)
}

TerminologyValidator validates whether a code is a member of a value set.

func TerminologyServiceAdapter

func TerminologyServiceAdapter(validate func(ctx context.Context, valueSetURL, system, code string) (bool, error)) TerminologyValidator

TerminologyServiceAdapter adapts a validate-code callback to TerminologyValidator.

func TerminologyValidatorsAdapter

func TerminologyValidatorsAdapter(
	memberOf func(ctx context.Context, valueSetURL, system, code string) (bool, error),
	subsumes func(ctx context.Context, system, broadCode, narrowCode string) (bool, error),
) TerminologyValidator

TerminologyValidatorsAdapter wires ValueSet membership and optional code-system subsumption.

type Value

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

Value wraps one FHIRPath result item. Backend-native system types remain accessible through Raw() but are not part of the public type surface.

func NewValue

func NewValue(raw any) Value

NewValue wraps a backend result item for the public API.

func (Value) Bool

func (v Value) Bool() (bool, error)

Bool coerces a singleton boolean result.

func (Value) Float64

func (v Value) Float64() (float64, error)

Float64 coerces a singleton numeric result.

func (Value) Raw

func (v Value) Raw() any

Raw returns the backend-native value.

func (Value) String

func (v Value) String() (string, error)

String coerces a singleton string result.

func (Value) Type

func (v Value) Type() string

Type returns a stable type name for the wrapped value.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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