Skip to content

Improve error message layering in ensdb-sdk Zod schemas #1916

@sevenzing

Description

@sevenzing

Currently, the Zod schemas in ensdb-sdk (e.g. EnsDbUrlSchema, EnsIndexerSchemaNameSchema) dont show specific ENV names like ENSDB_URL or ENSINDEXER_SCHEMA_NAME in their error messages:

error: "ENSIndexer Schema Name is required.",
})
.trim()
.nonempty({
error: "ENSIndexer Schema Name cannot be an empty string.",

I tried to add it during #1872 (comment) but I think we need more correct approach without boilerplating names like that because this couples package-level validation logic to app-level concerns. The schemas themselves should describe what's wrong with the value, not where it came from. A separate utility function should wrap a base schema and inject the env var name into error messages.

I see it like

// ensdb-dk. define how to parse and handle errors
export function validateEnsDbConfigFromEnv(
  env: Record<string, string | undefined>,
  envMapping: { [K in keyof EnsDbConfig]: string }
): EnsDbConfig {
  const unvalidated = Object.fromEntries(
    Object.entries(envMapping).map(([key, envVar]) => [key, env[envVar]])
  );

  const result = EnsDbConfigSchema.safeParse(unvalidated);
  if (result.success) return result.data;

  const messages = result.error.issues.map((issue) => {
    const field = issue.path[0] as keyof EnsDbConfig | undefined;
    const envVar = field ? envMapping[field] : undefined;
    return envVar ? `${envVar}: ${issue.message}` : issue.message;
  });

  throw new Error(messages.join("\n"));
}

and in app:

// ensapi. define mapping of ENV -> Config variable
export function buildEnsDbConfigFromEnvironment(env: NodeJS.ProcessEnv): EnsDbConfig {
  validateEnsDbConfigFromEnv(process.env, {
    ensDbUrl: ENSDB_URL,
    ensIndexerSchemaName: ENSINDEXER_SCHEMA_NAME,
  });
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Status

    No status

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions