Runtime Helpers
Helper functions and utilities for working with CallApi
CallApi provides utility functions for schemas, plugins, error handling, and data processing.
Schema & Plugin Utilities
defineSchema
Creates type-safe schema configurations:
import { fallBackRouteSchemaKey } from "@zayne-labs/callapi/constants";
import { defineSchema } from "@zayne-labs/callapi/utils";
import { z } from "zod";
export const apiSchema = defineSchema({
[fallBackRouteSchemaKey]: {
headers: z.object({
"x-api-key": z.string(),
}),
},
"/users/:id": {
data: z.object({
id: z.number(),
name: z.string(),
email: z.string().email(),
}),
params: z.object({
id: z.number(),
}),
},
});definePluginWithContext
Use this when the plugin's hooks or setup need extra fields. For plugins that only add request options or metadata, definePlugin is enough.
import type { GetCallApiContext } from "@zayne-labs/callapi";
import { definePluginWithContext } from "@zayne-labs/callapi/utils";
type AuthOptions = { apiKey: string; refreshToken?: string };
type AuthContext = GetCallApiContext<{ InferredExtraOptions: AuthOptions }>;
export const authPlugin = definePluginWithContext<AuthContext>()({
id: "auth-plugin",
name: "Authentication Plugin",
setup: ({ options, request }) => ({
request: {
...request,
headers: {
...request.headers,
Authorization: `Bearer ${options.apiKey}`,
},
},
}),
});Data Processing Utilities
toFormData
Converts objects to FormData with intelligent type handling:
import { toFormData } from "@zayne-labs/callapi/utils";
const formData = toFormData({
name: "John",
age: 30,
tags: ["javascript", "typescript"], // Arrays become multiple entries
avatar: fileBlob, // Files and blobs handled correctly
settings: { theme: "dark" }, // Objects are JSON stringified
});toQueryString
Converts objects to URL query strings:
import { toQueryString } from "@zayne-labs/callapi/utils";
const query = toQueryString({
page: 1,
tags: ["js", "ts"], // Arrays become multiple params
search: "javascript",
active: null, // Null/undefined values are skipped
});
// Result: "page=1&tags=js&tags=ts&search=javascript"Error Handling Utilities
Error Type Guards
Check error types in result objects:
import { isHTTPError, isJavascriptError, isValidationError } from "@zayne-labs/callapi/utils";
function handleError(error: unknown) {
if (isHTTPError(error)) {
return `HTTP ${error.originalError.response.status}: ${error.message}`;
}
if (isValidationError(error)) {
return `Validation failed: ${error.message}`;
}
// Any error that basically isn't the above two
if (isJavascriptError(error)) {
return `JavaScript error: ${error.message}`;
}
}Error Instance Guards
Check CallApi-specific error instances when using throwOnError: true:
import { isHTTPErrorInstance, isValidationErrorInstance } from "@zayne-labs/callapi/utils";
try {
const { data } = await apiClient("/users", { throwOnError: true });
} catch (error) {
if (isHTTPErrorInstance(error)) {
console.error(`HTTP ${error.response.status}: ${error.message}`);
}
if (isValidationErrorInstance(error)) {
console.error(`Validation failed: ${error.message}`);
}
}Constants
fallBackRouteSchemaKey
Constant for defining fallback schemas:
import { fallBackRouteSchemaKey } from "@zayne-labs/callapi/constants";
import { defineSchema } from "@zayne-labs/callapi/utils";
import { z } from "zod";
const schema = defineSchema({
[fallBackRouteSchemaKey]: {
headers: z.object({
"x-api-key": z.string(),
}),
},
});Last updated on