Runtime Schema Validation

Validate response data at runtime with a supported schema or validation function.


Standard Schema v1 Support

The client accepts Standard Schema v1 (~standard), Zod-like parse() or safeParse() methods, and validation functions. Install any schema library you choose as a dependency of your application:

validation.ts
typescript
import { z } from 'zod';
import { createClient, isValidationError } from 'react-native-fetch-client';

const api = createClient({ baseURL: 'https://api.example.com' });

// 1. Define schema
const UserSchema = z.object({
  id: z.number(),
  name: z.string(),
  email: z.string().email(),
  role: z.enum(['admin', 'member', 'guest']),
});

type User = z.infer<typeof UserSchema>;

try {
  // 2. Pass schema in request options
  // The generic types response.data; the schema validates it at runtime.
  const response = await api.get<User>('/user/me', {
    schema: UserSchema,
  });

  console.log('Validated user role:', response.data.role);
} catch (err) {
  if (isValidationError(err)) {
    console.error('Validation failed on endpoint:', err.config.url);
    console.error('Schema issues:', err.issues);
  }
}

Pure Functional Validators

If you want runtime checks without installing any schema library, pass a plain validation function:

typescript
// You can also use lightweight inline validators without Zod:
const res = await api.get('/settings', {
  schema: (data: unknown) => {
    if (
      typeof data !== 'object' ||
      data === null ||
      !('theme' in data) ||
      (data.theme !== 'light' && data.theme !== 'dark')
    ) {
      throw new Error('Expected a light or dark theme');
    }
    return data as { theme: 'light' | 'dark' };
  },
});
Type annotations
Pass the expected response type as a method generic, such as api.get<User>(). The validator checks the parsed value at runtime; the request method's type parameter describes the value returned to TypeScript.