OrvalOrval

Effect

Generate Effect schemas from OpenAPI

Generate Effect Schema schemas from your OpenAPI specification for runtime validation.

client: 'effect' writes a schema for each operation, as described below. schemas.type: 'effect' writes one for each model, so a fetch-based client can validate its responses with them:

import { Schema as S } from 'effect';
import { Pet, type PetOutput } from './src/api/model/index.effect';

const pet: PetOutput = S.decodeUnknownSync(Pet)(data);

Configuration

Set the client option to effect:

orval.config.ts
import { defineConfig } from 'orval';

export default defineConfig({
  petstore: {
    output: {
      client: 'effect',
      mode: 'single',
      target: './src/api/schemas',
    },
    input: {
      target: './petstore.yaml',
    },
  },
});

Generated Output

Orval generates an Effect schema for each model in your OpenAPI specification:

import { Schema as S } from 'effect';

export const CreatePetsBody = S.Struct({
  id: S.Number,
  name: S.String,
  tag: S.optional(S.String),
});

Effect Version

Orval reads the effect version installed in your project and emits Effect 3 or Effect 4 Schema syntax to match. When no effect package is found, it emits Effect 4. Set override.effect.version to pin the target.

Options

Options live under override.effect:

  • strict - per location (param, query, header, body, response). It has no effect yet: Effect schemas drop extra fields instead of rejecting them. All false by default.
  • generate - per location, choose which schemas are generated. All true by default.
  • useBrandedTypes - append S.brand() to the generated schemas. false by default.
  • exactOptional - emit optional properties for projects with exactOptionalPropertyTypes. false by default. Can also be set per operation or tag.
  • version - pin the Effect major version (3, 4 or 'auto') instead of reading it from the installed package. Output-wide.
  • generateEachHttpStatus - emit a schema per response status code. false by default.
  • generateReusableSchemas - emit each component schema an operation reaches once and reference it, instead of inlining every $ref. false by default. See Reusable Schemas.

Reusable Schemas

By default every $ref is inlined, which makes the output large for a spec with many shared components. With generateReusableSchemas, each component schema an operation reaches becomes one exported constant:

orval.config.ts
export default defineConfig({
  petstore: {
    output: {
      client: 'effect',
      target: './src/api/schemas.ts',
      override: { effect: { generateReusableSchemas: true } },
    },
    input: { target: './petstore.yaml' },
  },
});
export type Pet = {
  readonly name: string;
  readonly friends?: ReadonlyArray<Pet> | undefined;
};

export type PetEncoded = {
  readonly name: string;
  readonly friends?: ReadonlyArray<PetEncoded> | undefined;
};

export const Pet = S.Struct({
  name: S.String,
  friends: S.optional(
    S.Array(S.suspend((): S.Codec<Pet, PetEncoded> => Pet)),
  ),
});

export const ListPetsResponseItem = Pet;
export const ListPetsResponse = S.Array(ListPetsResponseItem);

The constants go next to the operations: into the target in single mode, into a *.schemas.ts file in the other modes. A reference to a constant on a cycle reads through S.suspend, typed with S.Schema on Effect 3 and S.Codec on Effect 4.

Each constant on a cycle also gets two exported types: Pet for what it decodes to and PetEncoded for what it accepts. The S.suspend getter uses them, so the recursive field keeps its type. When another schema already has the name PetEncoded, the encoded type becomes PetEncoded2. A field converted by a formatType is typed from its effect.schema. An expression that is not a plain identifier is declared as a constant (such as petSlugFormat) for that.

Limitations

  • With client: 'effect', generateReusableSchemas and output.schemas can't be set together: generation fails with an error. To write the schemas to their own module, set schemas.type to effect with an HTTP client.
  • A $ref is still inlined where a constant would not behave the same, such as form bodies, parameters, allOf members, an array body or response (generated from its items, which stay references), schemas with a default, and members of a oneOf or anyOf with sibling keywords such as properties, type or required. Effect merges allOf members by their fields, so an allOf of references stays inlined.
  • When allOf members declare the same key with different definitions, only the last one is checked (on Effect 4, and on Effect 3 with schemas.type set to effect). Generation warns with the key and the schema or operation, once for each operation that inlines the schema. Identical definitions, and a non-nullable enum or literal of strings that replaces a plain, unconstrained string with the same optionality, do not warn.
  • A $ref to a schema that is readOnly or writeOnly is always inlined, and so is one that holds such a property when it is read in a request body.
  • A location with another exactOptional than the output inlines its schemas.
  • Only the components the generated operations use, and those they read in turn, are generated. A component only an error response reads is not, unless generateEachHttpStatus is on, and neither is one only an unsupported media type reads. One of them that can't be generated, such as an allOf of a schema with itself, stops generation with an error that names it.
  • A component named Date, RegExp, File, S, Effect or ReadonlyArray, or like a name a formatType effect.schema or schemaImport reads, gets a Schema suffix. Two components with the same name stop generation with an error, and so does a constant hoisted from a component or an operation (such as PetMin) that has the name of another component.
  • A constant of an operation (such as ListPetsResponse or CreatePetsBody) that has the name of a component gets a Schema suffix, even when no constant is written for that component. Code that imports the name it has without the option stops compiling.
  • A cycle closed by a $ref that can't stay a reference, such as one with readOnly or writeOnly next to it, is validated as unknown where it closes, with a warning, as it is without the option. A constant is expanded from itself, so a schema reached through an alias is validated one level less than it is without the option.
  • On Effect 4, TypeScript can report Type instantiation is excessively deep for a constant on a cycle that reads a chain of about 16 or more nested components outside any cycle. Leave the option off for such a spec.

Usage

Decoding Data

import { Schema as S } from 'effect';
import { CreatePetsBody } from './src/api/schemas';

const pet = { id: 1, name: 'Buddy', tag: 'dog' };
const parsedPet = S.decodeUnknownSync(CreatePetsBody)(pet);
// => { id: 1, name: "Buddy", tag: "dog" }

Type Inference

import { Schema as S } from 'effect';
import { CreatePetsBody } from './src/api/schemas';

type Pet = S.Schema.Type<typeof CreatePetsBody>;

const pet: Pet = { id: 1, name: 'Buddy', tag: 'dog' };

Safe Decoding

import { Exit, Schema as S } from 'effect';

const result = S.decodeUnknownExit(CreatePetsBody)(unknownData);

if (Exit.isSuccess(result)) {
  console.log(result.value);
} else {
  console.error(result.cause);
}

With Effect 3, use S.decodeUnknownEither and Either.isRight instead.

Validating HTTP Client Responses

Set schemas.type to effect and turn on the client's runtimeValidation. The generated client then validates responses with Effect schemas instead of Zod.

orval.config.ts
export default defineConfig({
  petstore: {
    output: {
      client: 'fetch',
      target: './src/api/endpoints.ts',
      schemas: { path: './src/api/model', type: 'effect' },
      override: {
        fetch: { runtimeValidation: true },
      },
    },
    input: { target: './petstore.yaml' },
  },
});

Every schema goes to one module, <schemas.path>/index.effect.ts, or schemas.path itself when it names a file. Each schema is wrapped as a Standard Schema (S.toStandardSchemaV1 on Effect 4, S.standardSchemaV1 on Effect 3.15 or newer, and generation stops on an older one), so it stays an Effect schema and also validates through schema['~standard'].validate(). It exports the types X (S.Codec.Encoded on Effect 4, S.Schema.Encoded on Effect 3) and XOutput (S.Schema.Type). A schema on a cycle declares both in full, because they cannot be inferred.

  • Validation runs through the runtimeValidation option of override.fetch for fetch and for react-query, vue-query, svelte-query, solid-query, swr, pinia-colada with httpClient: 'fetch', override.angular for angular, and override.query for angular-query. It is off by default.
  • standardSchema is always on. Validation errors are therefore StandardSchemaError, not ParseError (Effect 3) or SchemaError (Effect 4), and async schemas are not supported.
  • Axios clients do not validate.
  • Generated validation is skipped for custom mutators. With includeSchemaInArguments, the mutator of fetch or a fetch-backed client receives the schema as schema (example). Angular clients do not pass it.
  • useDates makes the schemas turn date strings into Date, so XOutput has Date where X has string. The conversion is lenient: it accepts strings such as "2024". useDatesTransform turns on useDates and nothing more: the client adds no date deserializer.
  • version, generate and exactOptional of override.effect apply. strict, useBrandedTypes and generateEachHttpStatus have no effect.

The following fail with a configuration error: schemas.mode: 'split', schemas.routes, schemas.splitByTags, mock generators, operationSchemas, factoryMethods, splitByContentType, standardSchema: false, override.formatType, override.useBigInt, override.namingConvention.properties, Angular runtimeValidation.requestBodies with useDates, and the clients zod, effect, valibot, hono and mcp.

Known limits:

  • Requests and responses share a component schema, so a required writeOnly property is optional in it.
  • format: binary maps to S.instanceOf(File) also in JSON, so a JSON response with such a property fails validation.
  • On Effect 3 the wrapped schema loses .fields and .make. Effect 4 keeps them.
  • Every component gets a constant. One that can't be generated is left out with a warning, unless an operation reaches it: that stops generation with an error. So does an operation schema (such as ListPetsParams) named like a component.
  • $ref inlining, cycles that can't stay a reference and allOf members merged as structs (on Effect 3 too) follow the limitations of Reusable Schemas.

Custom Mutator

The mutator receives the Effect schema itself, with ~standard added. The schema describes the success response only, but the mutator also sees error statuses, so check response.ok before validating. Return the same { data, status, headers } object as the fetch mutator.

src/custom-fetch.ts
import { Schema as S } from 'effect';

export const customFetch = async <T>(
  url: string,
  // On Effect 3, type `schema` as `S.Schema.AnyNoContext`.
  options: RequestInit & { schema?: S.Decoder<unknown> },
): Promise<T> => {
  const { schema, ...init } = options;
  const response = await fetch(url, init);
  const text = await response.text();
  const data: unknown = text ? JSON.parse(text) : undefined;

  return {
    data: schema && response.ok ? S.decodeUnknownSync(schema)(data) : data,
    status: response.status,
    headers: response.headers,
  } as T;
};

To validate through Standard Schema instead, type schema as StandardSchemaV1 (from effect/StandardSchema on Effect 4, or @standard-schema/spec on Effect 3) and call schema['~standard'].validate(data).

Combining with HTTP Clients

See the Client with Effect guide for using Effect schemas with React Query, SWR, or other HTTP clients.

On this page