Hyperlinkv0.8.0-beta.28

Config

Config.schemafunctioneffect/Config.ts:642
<T>(
  codec: Schema.ConstraintCodec<T, unknown>,
  path?: string | ConfigProvider.Path
): Config<T>

Creates a Config<T> from a Schema.Codec.

When to use

Use when you need to read structured or schema-validated configuration.

Details

The optional path sets the local path segment(s) for the config lookup. It is appended to the logical path prefix accumulated from outer nested calls. Pass a single string for a flat key or an array for nested paths.

Convenience constructors such as string, number, and boolean delegate to this API.

The codec is used to decode the raw StringTree produced by the provider into T. Schema validation errors are wrapped in ConfigError.

Example (Reading a structured config)

import { Config, ConfigProvider, Effect, Schema } from "effect"

const DbConfig = Config.schema(
  Schema.Struct({
    host: Schema.String,
    port: Schema.Int
  }),
  "db"
)

const provider = ConfigProvider.fromUnknown({
  db: { host: "localhost", port: 5432 }
})

// Effect.runSync(DbConfig.parse(provider))
// { host: "localhost", port: 5432 }
Source effect/Config.ts:64219 lines
export function schema<T>(codec: Schema.ConstraintCodec<T, unknown>, path?: string | ConfigProvider.Path): Config<T> {
  const codecStringTree = Schema.toCodecStringTree(codec)
  const decodeUnknownEffect = SchemaParser.decodeUnknownEffect(codecStringTree)
  const codecStringTreeEncoded = SchemaAST.toEncoded(codecStringTree.ast)
  const localPath = typeof path === "string" ? [path] : path ?? []
  return make((provider, pathPrefix) => {
    const fullPath = [...pathPrefix, ...localPath]
    return recur(codecStringTreeEncoded, provider, fullPath).pipe(
      Effect.flatMapEager((tree) =>
        decodeUnknownEffect(tree).pipe(
          Effect.mapErrorEager((issue) =>
            new Schema.SchemaError(fullPath.length > 0 ? new SchemaIssue.Pointer(fullPath, issue) : issue)
          )
        )
      ),
      Effect.mapErrorEager((cause) => new ConfigError(cause))
    )
  })
}
Referenced by 14 symbols