# Extract into a struct: choose one of three

Read a configuration subtree into your own struct. All three paths keep strict types; they differ in control, dependencies and the amount of type rework.
For the interface and trade-offs, see [extract.md](../design/extract.md).

## When to use it

- Configuration keys and field names differ, or you need defaults or nested fields: use `FromConfig`
- The type already implements serde's `Deserialize` and you do not want to write it again for configuration: use `serde_bridge`
- The struct is a simple JSON shape and field names equal configuration keys: use `derive(FromJson)`

## Prerequisites

- `FromConfig`: the default extraction path, depending only on `core`; `from_config` receives a `Getter` and reads fields by
  tag
- serde (`moonbit-community/serde.mbt`): the type has `Deserialize` (hand-written or
  `#serde.derive(Deserialize)`) and depends on `serde_bridge`; it connects `Value` to the serde backend
- `derive(FromJson)`: the implementation is generated by `moonbitlang/core/json`; add
  `#derive(@json.FromJson)` to the type, plus one line `pub extend T with @json.FromJson::{from_json}`;
  depends on `json_format`
- 64-bit integers: `FromConfig` and `serde_bridge` read `Value` directly and use `Int64`;
  `derive(FromJson)` goes through Json and uses `Int64Text` (a wrapper type in `json_format`,
  retrieve it with `to_int64()`)
- Validation: the type implements `Validate` (the validation trait run after extraction); extraction goes through the entry point that takes `validated`

## Completion criteria

- The struct compiles, and nested fields can also be read
- A missing key reports `MissingKey`, a type mismatch reports `TypeMismatch`, and the message carries the full key path
- `*_or` uses the default only when the key is missing; a key that exists but has the wrong type still reports an error
- Changing the source (file / environment variables / command line) does not require changing the extraction code

## Steps

1. Use `FromConfig` by default: `from_config` receives a `Getter`, one line per field; tag, default and nesting
   are all written in one place; tags resolve relative to the `get_struct` subtree.

```moonbit nocheck
impl @config.FromConfig for Server with fn from_config(get : @config.Getter) -> Server raise @config.ConfigError {
  {
    host: get.string("db-host"),      // config key db-host, field name host
    port: get.int("port"),            // native Int64
    retry: get.int32_or("retry", 3),  // use 3 only when missing
    pool: get.nested("pool"),         // recurses into Pool's from_config
  }
}
let srv : Server = cfg.get_struct("server")
```

2. When the type already has a serde description, switch to `serde_bridge`: it treats `Value` as the serde backend, and the type side
   needs no change for configuration.

```moonbit nocheck
let app : AppCfg = @serde_bridge.extract_serde_from(cfg, "app")
```

3. When the struct is simple and field names equal configuration keys, use `derive(FromJson)`; `extract_from` first takes the subtree by key
   and then decodes it.

```moonbit nocheck
#derive(@json.FromJson)
struct Port { port : Int32 }

pub extend Port with @json.FromJson::{from_json}
let port : Port = @jsonfmt.extract_from(cfg, "db")
```

Nesting can be mixed: inside a `FromConfig` field, delegate in one line with `@jsonfmt.json_field(get, "db")`, or
`@serde_bridge.serde_field(get, "db")`; there is no need to change the whole tree.

## Common pitfalls and next steps

- `derive(FromJson)` ignores fields that are not in the struct; to check for unknown keys you can only use `FromConfig` + `Validate`.
- The getter `int` accepts only integer sources; the string `"5432"` is not converted automatically.
- The error messages of the three paths follow the same convention as `get_*`; do not wrap another layer at the call site.
- For validation, see [validate.md](../design/validate.md).
- Next step: for the complete code, see [from_config](../../examples/from_config/README.md),
  [serde_extract](../../examples/serde_extract/README.md),
  [strict_types](../../examples/strict_types/README.md).
