← Library Select Deterministic

SwitchStringOp

Maps a key string to a value using a configured case table, returning a default on miss.

Inputs

FieldTypeDescription
Key*stringKey to switch on

Outputs

FieldTypeDescription
ResultstringMatched value, or default if key not found

Params

KeyTypeDefaultDescription
casesstring'{}'JSON key→value map of cases
defaultstring''Value returned when key not in cases

Typical Use Cases

  • Enum-to-label translation
  • Routing key to handler name
  • Code to human-readable name conversion

Default on miss. If the key is not found in the cases map, the default param value is returned. Use IfEmptyStringOp downstream to detect a missed match if the default is empty string.

Complete Runnable Example

Translates a department code like "billing" into a human-readable label for display in the UI.

main.go
package main

import (
	"context"
	"encoding/json"
	"log"
	"os"
	"time"

	"github.com/akennis/sparsi-go/library"
	_ "github.com/akennis/dagor/operator/builtin"

	"github.com/panjf2000/ants/v2"
	"github.com/akennis/dagor"
	"github.com/akennis/dagor/graph"
)

func main() {
	dept := "billing"
	library.RegisterConst("dept_code", dept)

	g, err := graph.NewBuilder("switch_demo").
		Vertex("src").Op("dept_code").Output("Result", "wire_key").
		Vertex("sw").Op("SwitchStringOp").
		Params(map[string]string{
			"cases":   `{"billing":"Billing & Payments","tech":"Technical Support","sales":"Sales"}`,
			"default": "General Support",
		}).
		Input("Key", "wire_key").
		Output("Result", "dept_label").
		Build()
	if err != nil {
		log.Fatalf("build: %v", err)
	}

	pool, err := ants.NewPool(4)
	if err != nil {
		log.Fatalf("pool: %v", err)
	}
	defer pool.Release()

	eng, err := dagor.NewEngine(g, pool)
	if err != nil {
		log.Fatalf("engine: %v", err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
	defer cancel()

	if err := eng.Run(ctx); err != nil {
		log.Fatalf("run: %v", err)
	}

	out := map[string]any{"department_code": dept}
	if raw, ok := eng.GetOutput("dept_label"); ok {
		out["department_label"] = *raw.(*string)
	}
	enc := json.NewEncoder(os.Stdout)
	enc.SetIndent("", "  ")
	enc.Encode(out)
}