### Docusaurus Project Setup and Commands Source: https://github.com/ecyrbe/zodios/blob/main/website/README.md Provides essential commands for managing a Docusaurus 2 project, including installation, starting a development server, building for production, and deployment. ```bash yarn ``` ```bash yarn start ``` ```bash yarn build ``` ```bash USE_SSH=true yarn deploy ``` ```bash GIT_USER= yarn deploy ``` -------------------------------- ### Core Frontend Installation Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/installation.md Installs the core Zodios library along with Axios and Zod for frontend applications. This is the base installation for most frontend projects. ```bash npm install @zodios/core axios zod ``` -------------------------------- ### Solid Frontend Installation with Hooks Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/installation.md Installs Zodios core, Solid query, and Solid-specific packages for frontend applications utilizing Solid hooks. Requires @tanstack/solid-query for state management. ```bash npm install @tanstack/solid-query @zodios/core @zodios/solid axios solid-js zod ``` -------------------------------- ### Express Backend Installation Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/installation.md Installs the core Zodios library, Express integration, Zod, and Axios for backend applications using the Express framework. ```bash npm install @zodios/core @zodios/express express zod axios ``` -------------------------------- ### React Frontend Installation with Hooks Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/installation.md Installs Zodios core, React query, and React-specific packages for frontend applications utilizing React hooks. Requires @tanstack/react-query for state management. ```bash npm install @tanstack/react-query @zodios/core @zodios/react axios react react-dom zod ``` -------------------------------- ### NextJS Backend Installation Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/installation.md Installs Zodios core, Express integration, NextJS, React, React DOM, Zod, and Axios for backend applications using the NextJS framework. ```bash npm install @zodios/core @zodios/express next zod axios react react-dom ``` -------------------------------- ### OpenAPI Generation Packages Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/installation.md Installs optional packages for generating OpenAPI specifications and serving Swagger UI within an Express application. ```bash npm install @zodios/openapi swagger-ui-express ``` -------------------------------- ### Backend Type Definitions Installation Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/installation.md Installs TypeScript type definitions for Express, and optionally for React and React DOM if using NextJS, recommended for backend development. ```bash // if you use express npm install --dev @types/express // or with nextjs npm install --dev @types/express @types/react @types/react-dom ``` -------------------------------- ### Frontend Type Definitions Installation Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/installation.md Installs TypeScript type definitions for React and React DOM, recommended even for JavaScript projects to improve development experience and catch potential type errors. ```bash // if you use react npm install --dev @types/react @types/react-dom ``` -------------------------------- ### ApiBuilder Usage Example Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/api/helpers.md Demonstrates how to use ApiBuilder to construct an API definition with multiple endpoints, starting with an initial endpoint and adding subsequent ones. ```ts import { apiBuilder } from "@zodios/core"; import { z } from "zod"; // Assuming 'user' is a defined Zod schema // const user = z.object({ id: z.number(), name: z.string() }); const api = apiBuilder({ method: "get", path: "/users", response: z.array(user), alias: "getUsers", description: "Get users", }) .addEndpoint({ method: "get", path: "/users/:id", response: user, alias: "getUser", description: "Get a specific user by ID", }) .build(); // The 'api' variable now holds an array containing two endpoint descriptions. ``` -------------------------------- ### Express Application Example Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/server/express-app.md Illustrates creating a standard Zodios Express application using `zodiosApp`. This example shows how to initialize the app with API definitions and define a route that leverages type-safe request parameters. ```typescript import { zodiosApp } from "@zodios/express"; import { userApi } from "../../common/api"; // just an express adapter that is aware of your api, app is just an express app with type annotations and validation middlewares const app = zodiosApp(userApi); // auto-complete path fully typed and validated input params (body, query, path, header) // ▼ ▼ ▼ app.get("/users/:id", (req, res) => { // res.json is typed thanks to zod res.json({ // auto-complete req.params.id // ▼ id: req.params.id, name: "John Doe", }); }) app.listen(3000); ``` -------------------------------- ### Express Router from Context Example Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/server/express-router.md Demonstrates how to create a context-aware express router using zodiosContext and apply middleware. This example sets up user context and applies a user middleware. ```typescript import { zodiosContext } from "@zodios/express"; import z from "zod"; import { userApi } from "../../common/api"; import { userMiddleware } from "./userMiddleware"; const ctx = zodiosContext(z.object({ user: z.object({ id: z.number(), name: z.string(), isAdmin: z.boolean(), }), })); const router = ctx.router(); // middleware that adds the user to the context router.use(userMiddleware); ``` -------------------------------- ### Install Zodios Core Source: https://github.com/ecyrbe/zodios/blob/main/README.md Installs the core Zodios package for client-side API definitions and usage. ```bash > npm install @zodios/core or > yarn add @zodios/core ``` -------------------------------- ### Zodios React Hooks Example Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/react.md Demonstrates how to use ZodiosHooks to fetch a list of users and create a new user. It includes loading and error state handling, as well as data invalidation on mutation success. The example utilizes `useQuery` for GET requests and `useMutation` for POST requests. ```tsx import React from "react"; import { Zodios } from "@zodios/core"; import { ZodiosHooks } from "@zodios/react"; import { z } from "zod"; const baseUrl = "https://jsonplaceholder.typicode.com"; const zodios = new Zodios(baseUrl, [...]); const zodiosHooks = new ZodiosHooks("jsonplaceholder", zodios); const Users = () => { const { data: users, isLoading, error, invalidate: invalidateUsers, // zodios also provides invalidation helpers key // zodios also returns the generated key } = zodiosHooks.useQuery("/users"); // or useGetUsers(); const { mutate } = zodiosHooks.useMutation("post", "/users", undefined, { onSuccess: () => invalidateUsers(), }); // or .useCreateUser(...); return ( <>

Users

{isLoading &&
Loading...
} {error &&
Error: {(error as Error).message}
} {users && ( )} ); }; ``` -------------------------------- ### ParametersBuilder Usage Examples Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/api/helpers.md Demonstrates various ways to use ParametersBuilder to define API parameters, showcasing chaining and equivalent constructions for clarity. ```ts import { parametersBuilder } from "@zodios/core"; import { z } from "zod"; // Example 1: Using addParameters for multiple query parameters const params1 = parametersBuilder() .addParameters("Query", { limit: z.number().positive(), offset: z.number().positive(), }) .build(); // Example 2: Equivalent construction using addQuery for each parameter const params2 = parametersBuilder() .addQuery("limit", z.number().positive()) .addQuery("offset", z.number().positive()) .build(); // Example 3: Using addQueries for multiple query parameters (alternative syntax) const params3 = parametersBuilder() .addQueries({ limit: z.number().positive(), offset: z.number().positive(), }) .build(); // Example 4: Using addParameter for individual parameters with type specified const params4 = parametersBuilder() .addParameter("limit", "Query", z.number().positive()) .addParameter("offset", "Query", z.number().positive()) .build(); // Example 5: Using makeParameters (a different function, shown for comparison) import { makeParameters } from "@zodios/core"; const params5 = makeParameters([ { name: "limit", type: "Query", schema: z.number().positive(), }, { name: "offset", type: "Query", schema: z.number().positive(), }, ]); // Example 6: Combining parameters with makeApi import { makeApi } from "@zodios/core"; // Assuming 'user' is a defined Zod schema // const user = z.object({ id: z.number(), name: z.string() }); const api1 = makeApi([ { method: "get", path: "/users", response: z.array(user), alias: "getUsers", description: "Get users", parameters: params1, // Using parameters built with ParametersBuilder }, ]); // Example 7: Equivalent API definition with inline parameters const api2 = makeApi([ { method: "get", path: "/users", response: z.array(user), alias: "getUsers", description: "Get users", parameters: [ { name: "limit", type: "Query", schema: z.number().positive(), }, { name: "offset", type: "Query", schema: z.number().positive(), }, ], }, ]); ``` -------------------------------- ### Zodios Plugin Integration Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/client.md Illustrates how to add a plugin to a Zodios client instance using the `use` method, with an example of using the `pluginFetch` plugin. ```ts import { pluginFetch } from "@zodios/plugins"; apiClient.use(pluginFetch({ keepAlive: true, })); ``` -------------------------------- ### Install Zodios Server Source: https://github.com/ecyrbe/zodios/blob/main/README.md Installs Zodios core along with the Express.js integration for building API servers. ```bash > npm install @zodios/core @zodios/express or > yarn add @zodios/core @zodios/express ``` -------------------------------- ### dev.to User API Documentation Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/api/examples.md API endpoints for interacting with dev.to user data. Includes methods to retrieve a specific user by ID, the currently authenticated user, and a user's profile image. ```APIDOC getUser: method: get path: /users/:id description: Get a user parameters: path: id: type: number description: The ID of the user to retrieve response: schema: | { id: number, type_of: string, name: string, username: string, summary: string | null, twitter_username: string | null, github_username: string | null, website_url: string | null, location: string | null, joined_at: string, profile_image: string, profile_image_90: string } errors: - status: 404 description: User not found schema: | { error: { code: string, message: string } } - status: default description: Default error schema: | { error: { code: string, message: string } } getMe: method: get path: /users/me description: Get current user response: schema: | { id: number, type_of: string, name: string, username: string, summary: string | null, twitter_username: string | null, github_username: string | null, website_url: string | null, location: string | null, joined_at: string, profile_image: string, profile_image_90: string } errors: - status: 404 description: User not found schema: | { error: { code: string, message: string } } - status: default description: Default error schema: | { error: { code: string, message: string } } getProfileImage: method: get path: /profile_image/:username description: Get a user's profile image parameters: path: username: type: string description: The username of the user response: schema: | { type_of: string, image_of: string, profile_image: string, profile_image_90: string } errors: - status: 404 description: User not found schema: | { error: { code: string, message: string } } - status: default description: Default error schema: | { error: { code: string, message: string } } ``` -------------------------------- ### Merge Multiple Routers with Context Example Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/server/express-router.md Illustrates merging multiple Zodios routers into an Express application using context awareness. This example sets up user context and then uses context-aware routers. ```typescript import { zodiosContext } from "@zodios/express"; const ctx = zodiosContext(z.object({ user: z.object({ id: z.number(), name: z.string(), isAdmin: z.boolean(), }), })); const app = ctx.app(); const userRouter = ctx.router(userApi); const adminRouter = ctx.router(adminApi); app.use(userRouter,adminRouter); app.listen(3000); ``` -------------------------------- ### Plugin Execution Order Example Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/plugins.md Provides an example demonstrating the execution order of Zodios plugins. Plugins attached globally are executed before endpoint-specific plugins. Request plugins run in declaration order, while response plugins run in reverse declaration order. ```typescript apiClient.use("getUser", pluginLog('2')); apiClient.use(pluginLog('1')); apiClient.use("get","/users/:id", pluginLog('3')); apiClient.get("/users/:id", { params: { id: 7 } }); // output : // request 1 // request 2 // request 3 // response 3 // response 2 // response 1 ``` -------------------------------- ### Express Application from Context Example Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/server/express-app.md Demonstrates creating a context-aware Express application using `zodiosContext`. It shows how to add middleware to populate the context and how routes benefit from type safety and autocompletion for parameters and context data. ```typescript import { zodiosContext } from "@zodios/express"; import z from "zod"; import { userApi } from "../../common/api"; import { userMiddleware } from "./userMiddleware"; const ctx = zodiosContext(z.object({ user: z.object({ id: z.number(), name: z.string(), isAdmin: z.boolean(), }), })); const app = ctx.app(userApi); // middleware that adds the user to the context app.use(userMiddleware); // auto-complete path fully typed and validated input params (body, query, path, header) // ▼ ▼ ▼ app.get("/users/:id", (req, res) => { // auto-complete user fully typed // ▼ if(req.user.isAdmin) { // res.json is typed thanks to zod return res.json({ // auto-complete req.params.id // ▼ id: req.params.id, name: "John Doe", }); } return res.status(403).end(); }) app.listen(3000); ``` -------------------------------- ### Zodios GET Method Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/client.md The `get` method is used for making HTTP GET requests. It takes a path string and optional `ZodiosRequestOptions`. Path parameters can be specified in the URL or via the `params` option, and query parameters via the `queries` option. ```ts get(path: string, config?: ZodiosRequestOptions): Promise; ``` ```ts const users = await api.get("/users"); ``` ```ts const user = await api.get("/users/:id", { params: { id: 1 } }); // GET /users/1 ``` ```ts const users = await api.get("/users", { queries: { limit: 10 } }); // GET /users?limit=10 ``` -------------------------------- ### React Query Provider Setup Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/react.md Sets up the React Query client and provides it to the application using `QueryClientProvider`. This is necessary for `useQuery` and `useMutation` hooks from `@tanstack/react-query` (which ZodiosHooks relies on) to function correctly. ```tsx import { QueryClient, QueryClientProvider } from "react-query"; import { Users } from "./users"; const queryClient = new QueryClient(); export const App = () => { return ( ); }; ``` -------------------------------- ### Merge Multiple Routers Example Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/server/express-router.md Shows how to merge multiple Zodios routers into a single Express application. This example creates an app and uses both userRouter and adminRouter. ```typescript import { zodiosApp, zodiosRouter } from "@zodios/express"; const app = zodiosApp(); // just an axpess app with type annotations const userRouter = zodiosRouter(userApi); // just an express router with type annotations and validation middlewares const adminRouter = zodiosRouter(adminApi); // just an express router with type annotations and validation middlewares const app.use(userRouter,adminRouter); app.listen(3000); ``` -------------------------------- ### application/x-www-form-urlencoded Submission (IE with qs) Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/client.md Provides an example of submitting application/x-www-form-urlencoded requests for older browsers like IE, using the `qs` library to stringify the data and setting the appropriate Content-Type header. ```typescript import qs from 'qs'; const apiClient = new Zodios( "https://mywebsite.com", [{ method: "post", path: "/login", alias: "login", description: "Submit a form", parameters:[ { name: "body", type: "Body", schema: z.object({ userName: z.string(), password: z.string(), }).transform(data=> qs.stringify(data)), } ], response: z.object({ id: z.number(), }), }], ); const id = await apiClient.login({ userName: "user", password: "password" }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); ``` -------------------------------- ### dev.to User API Definition Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/api/examples.md Defines the Zod schemas for dev.to user data and profile images, along with custom error schemas. It also includes the Zodios API definition for fetching user information and profile images. ```ts import { z } from "zod"; import { makeApi, makeErrors } from "@zodios/core"; export const devUser = z.object({ id: z.number(), type_of: z.string(), name: z.string(), username: z.string(), summary: z.string().or(z.null()), twitter_username: z.string().or(z.null()), github_username: z.string().or(z.null()), website_url: z.string().or(z.null()), location: z.string().or(z.null()), joined_at: z.string(), profile_image: z.string(), profile_image_90: z.string(), }); export type User = z.infer; export const devProfileImage = z.object({ type_of: z.string(), image_of: z.string(), profile_image: z.string(), profile_image_90: z.string(), }); export const userErrors = makeErrors([ { status: 404, description: "User not found", schema: z.object({ error: z.object({ code: z.string(), message: z.string(), }), }), }, { status: "default", description: "Default error", schema: z.object({ error: z.object({ code: z.string(), message: z.string(), }), }), }, ]); export type ProfileImage = z.infer; export const userApi = makeApi([ { method: "get", path: "/users/:id", alias: "getUser", description: "Get a user", response: devUser, errors: userErrors, }, { method: "get", path: "/users/me", alias: "getMe", description: "Get current user", response: devUser, errors: userErrors, }, { method: "get", path: "/profile_image/:username", alias: "getProfileImage", description: "Get a user's profile image", response: devProfileImage, errors: userErrors, }, ]); ``` -------------------------------- ### Error Handling Example with Zodios Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/server/express-app.md Demonstrates how Zodios Express handles API errors, including inferring status codes and typing error responses. The example shows how to define different error schemas for specific status codes (e.g., 404) and a default error schema. ```typescript import { makeApi } from "@zodios/core"; import { zodiosApp } from "@zodios/express"; import { z } from "zod"; const userApi = makeApi([ { method: "get", path: "/users/:id", alias: "getUser", description: "Get a user", response: z.object({ id: z.number(), name: z.string(), }), errors: [ { status: 404, response: z.object({ code: z.string(), message: z.string(), id: z.number(), }), }, { status: 'default', // default status code will be used if error is not 404 response: z.object({ code: z.string(), message: z.string(), }), }, ], }, ]); const app = zodiosApp(userApi); app.get("/users/:id", (req, res) => { try { const id = +req.params.id; const user = service.findUser(id); if(!user) { // match error 404 schema with auto-completion res.status(404).json({ code: "USER_NOT_FOUND", message: "User not found", id, // compile time error if you forget to add id }); } else { // match response schema with auto-completion res.json(user); } } catch(err) { // match default error schema with auto-completion res.status(500).json({ code: "INTERNAL_ERROR", message: "Internal error", }); } }) app.listen(3000); ``` -------------------------------- ### Zodios API Integration with SolidJS Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/solid.md An example demonstrating the integration of Zodios with SolidJS for making API requests. It includes defining Zod schemas, creating an API client, and using ZodiosHooks for data fetching and mutations. ```tsx import { createSignal, For, Match, Show, Switch } from "solid-js"; import { QueryClient, QueryClientProvider } from "@tanstack/solid-query"; import { makeApi, Zodios } from "@zodios/core"; import { ZodiosHooks } from "../src"; import { z } from "zod"; // you can define schema before declaring the API to get back the type const userSchema = z .object({ id: z.number(), name: z.string(), }) .required(); const createUserSchema = z .object({ name: z.string(), }) .required(); const usersSchema = z.array(userSchema); // you can then get back the types type User = z.infer; type Users = z.infer; const api = makeApi([ { method: "get", path: "/users", alias: "getUsers", description: "Get all users", parameters: [ { name: "page", type: "Query", schema: z.number().positive().optional(), }, { name: "limit", type: "Query", schema: z.number().positive().optional(), }, ], response: usersSchema, }, { method: "get", path: "/users/:id", description: "Get a user", response: userSchema, }, { method: "post", path: "/users", alias: "createUser", description: "Create a user", parameters: [ { name: "body", type: "Body", schema: createUserSchema, }, ], response: userSchema, }, ]); const baseUrl = "https://jsonplaceholder.typicode.com"; const zodios = new Zodios(baseUrl, api); const zodiosHooks = new ZodiosHooks("jsonplaceholder", zodios); const Users = () => { const [page, setPage] = createSignal(0); const users = zodiosHooks.createInfiniteQuery( "/users", { queries: { limit: 10 } }, { getPageParamList: () => { return ["page"]; }, getNextPageParam: () => { return { queries: { get page() { return page() + 1; }, }, }; }, } ); const user = zodiosHooks.createCreateUser(undefined, { onSuccess: () => users.invalidate(), }); return ( <> Loading... Fetching...
    {(user) => ( {(user) =>
  • {user.name}
  • }
    )}
); }; // on another file const queryClient = new QueryClient(); export const App = () => { return ( ); }; ``` -------------------------------- ### Manual CRUD API Definition for User Resource Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/client.md Provides the equivalent manual API definition for a user resource, showcasing the structure of each CRUD operation (GET, POST, PUT, PATCH, DELETE) with detailed parameters and responses. ```apidoc User Resource API Endpoints: GET /users alias: getUsers description: Get all users response: Array of user objects GET /users/:id alias: getUser description: Get a user by ID parameters: - name: id type: Path description: The ID of the user to retrieve response: User object POST /users alias: createUser description: Create a new user parameters: - name: body type: Body description: The user object to create schema: Partial user schema response: Created user object PUT /users/:id alias: updateUser description: Update an existing user by ID parameters: - name: id type: Path description: The ID of the user to update - name: body type: Body description: The user object with updated fields schema: Full user schema response: Updated user object PATCH /users/:id alias: patchUser description: Partially update an existing user by ID parameters: - name: id type: Path description: The ID of the user to patch - name: body type: Body description: The user object with fields to patch schema: Partial user schema response: Patched user object DELETE /users/:id alias: deleteUser description: Delete a user by ID parameters: - name: id type: Path description: The ID of the user to delete response: Deleted user object ``` -------------------------------- ### Zodios Error Handling Example Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/error.md Demonstrates how to use `isErrorFromPath` and `isErrorFromAlias` to handle different API error responses. It shows how to define expected errors in the API schema and how to narrow down the error type within a catch block. ```ts import { isErrorFromPath, makeApi, Zodios } from "@zodios/core"; const api = makeApi([ { path: "/users/:id", method: "get", alias: "getUser", response: z.object({ id: z.number(), name: z.string(), }), errors: [ { status: 404, schema: z.object({ message: z.string(), specificTo404: z.string(), }), }, { status: 'default', schema: z.object({ message: z.string(), }), } ], }, ]); const apiClient = new Zodios(api); try { const response = await apiClient.getUser({ params: { id: 1 } }); } catch (error) { // you can also do: // - isErrorFromPath(zodios.api, "get", "/users/:id", error) // - isErrorFromAlias(api, "getUser", error) // - isErrorFromAlias(zodios.api, "getUser", error) if(isErrorFromPath(api, "get", "/users/:id", error)){ // error type is now narrowed to an axios error with a response from the ones defined in the api if(error.response.status === 404) { // error.response.data is guaranteed to be of type { message: string, specificTo404: string } } else { // error.response.data is guaranteed to be of type { message: string } } } } ``` -------------------------------- ### Zodios Hooks Instance Creation Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/solid.md Demonstrates how to create an instance of ZodiosHooks, which requires a name for key prefixing and an instance of the Zodios API client. ```typescript import { Zodios, ZodiosHooks } from "zodios"; const baseUrl = "http://example.com"; const apiClient = new Zodios(baseUrl, []); const apiHooks = new ZodiosHooks("myAPI", apiClient); ``` -------------------------------- ### Zodios Client Instantiation Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/client.md Demonstrates how to create a Zodios client instance with a base URL and API endpoint definitions. Includes predefined Zod schemas for responses and error handling. ```ts import { Zodios, makeErrors } from "@zodios/core"; import z from "zod"; const errors = makeErrors([ { status: "default", schema: z.object({ error: z.object({ code: z.number(), message: z.string(), }), }), }, ]); const user = z.object({ id: z.number(), name: z.string(), age: z.number().positive(), email: z.string().email(), }); const apiClient = new Zodios('/api', [ { method: "get", path: "/users", alias: "getUsers", response: z.array(user), }, { method: "get", path: "/users/:id", alias: "getUser", response: user, errors, }, { method: "post", path: "/users", alias: "createUser", parameters: [ { name: "user", type: "Body", schema: user.omit({ id: true }), }, ], response: user, errors, }, ]); ``` -------------------------------- ### Zodios GET Query Hook Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/solid.md Creates a GET query hook that returns a `QueryResult` object from solid-query. This object includes response data, solid-query properties, the generated query key, and an `invalidate` helper function. ```ts createGet(path: string, config?: ZodiosRequestOptions, queryOptions?: CreateQueryOptions): CreateQueryResult; ``` -------------------------------- ### Exposing OpenAPI Documentation with Zodios Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/api/openapi.md This snippet demonstrates how to set up an Express application using Zodios to serve OpenAPI documentation. It includes defining API endpoints, building the OpenAPI document, and configuring Swagger UI. ```ts import { serve, setup } from "swagger-ui-express"; import { zodiosApp } from "@zodios/express"; import { openApiBuilder } from "@zodios/openapi"; import { userApi, adminApi } from "./api"; import { userRouter } from './userRouter'; import { adminRouter } from './adminRouter'; const app = zodiosApp(); // expose user api endpoints app.use('/api/v1', userRouter); app.use('/api/v1', adminRouter); // expose openapi documentation const document = openApiBuilder({ title: "User API", version: "1.0.0", description: "A simple user API", }) // you can declare as many security servers as you want .addServer({ url: "/api/v1" }) // you can declare as many security schemes as you want .addSecurityScheme("admin", bearerAuthScheme()) // you can declare as many apis as you want .addPublicApi(userApi) // you can declare as many protected apis as you want .addProtectedApi("admin", adminApi) .build(); app.use(`/docs/swagger.json`, (_, res) => res.json(document)); app.use("/docs", serve); app.use("/docs", setup(undefined, { swaggerUrl: "/docs/swagger.json" })); app.listen(3000); ``` -------------------------------- ### Using Zodios Client for API Calls Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/client.md Shows how to use a Zodios client instance to make API requests, including fetching all users, a specific user by ID, and creating a new user. ```ts // get all users const users = await apiClient.getUsers(); // get user by id const user = await apiClient.getUser({ params: { id: 1 } }); // create user const newUser = await apiClient.createUser({ name: "John", age: 20, email: "jodn@doe.com"}); ``` -------------------------------- ### OpenAPI Builder Initialization Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/api/openapi.md Initializes the openApiBuilder to create OpenAPI documentation. It requires an InfoObject containing metadata about the API. ```ts function openApiBuilder(info: OpenAPIV3.InfoObject): OpenApiBuilder ``` -------------------------------- ### Zodios Project Documentation Links Source: https://github.com/ecyrbe/zodios/blob/main/README.md Provides shortcuts to various sections of the Zodios documentation, covering API definition, HTTP client, React hooks, Solid hooks, API server, and Next.js integration. ```APIDOC Full documentation: https://www.zodios.org Shortcuts: - API definition: https://www.zodios.org/docs/category/zodios-api-definition - Http client: https://www.zodios.org/docs/category/zodios-client - React hooks: https://www.zodios.org/docs/client/react - Solid hooks: https://www.zodios.org/docs/client/solid - API server: http://www.zodios.org/docs/category/zodios-server - Nextjs integration: http://www.zodios.org/docs/server/next ``` -------------------------------- ### Zodios Methods Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/client.md Details the available methods on a Zodios client instance, focusing on the `use` method for adding plugins. ```APIDOC Zodios Methods: use(plugin: ZodiosPlugin): PluginId - Adds a plugin to the client instance. use(method: string, path: string, plugin: ZodiosPlugin): PluginId - Adds a plugin to a specific endpoint. use(alias: string, plugin: ZodiosPlugin): PluginId - Adds a plugin to a specific aliased endpoint. ``` -------------------------------- ### Get Query Key by Alias Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/solid.md Demonstrates how to obtain a query key for an aliased endpoint using `getKeyByAlias`. This is useful for managing cache data with SolidJS Query. ```ts getKeyByAlias(alias: string, config?: ZodiosRequestOptions): QueryKey; ``` ```ts const key = zodios.getKeyByAlias('getUser', { params: { id: 1 } }); const user = queryClient.getQueryData(key); ``` ```ts const key = zodios.getKeyByAlias('getUser'); queryClient.invalidateQueries(key); ``` -------------------------------- ### Zod Transformations Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/client.md Demonstrates how to use Zod transformations to modify response data. This example transforms a user's full name into first and last names. ```typescript const apiClient = new Zodios( "https://jsonplaceholder.typicode.com", [ { method: "get", path: "/users/:id", alias: "getUser", description: "Get a user", response: z.object({ id: z.number(), name: z.string(), }).transform(({ name,...rest }) => ({ ...rest, firstname: name.split(" ")[0], lastname: name.split(" ")[1], })), }, ] ); const user = await apiClient.getUser({ params: { id: 7 } }); console.log(user); ``` ```javascript console.log({ id: 7, firstname: 'Kurtis', lastname: 'Weissnat' }); ``` -------------------------------- ### Zodios GET Request Hook Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/react.md A query hook that returns a `QueryResult` object from react-query, including response data, react-query properties, the generated query key, and an `invalidate` helper function. ```ts useGet(path: string, config?: ZodiosRequestOptions, reactQueryOptions?: ReactQueryOptions): ReactQueryResult; // Example: const { data: user, isLoading, isError, invalidate, key } = hooks.useGet("/users/:id", { params: { id: 1 } }); ``` -------------------------------- ### Generic createInfiniteQuery Method Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/solid.md Describes the `createInfiniteQuery` method for fetching paginated data. It requires a `getPageParamList` function to correctly generate query keys for infinite loading. ```typescript import { ZodiosHooks } from "zodios"; // Assuming 'apiHooks' is an instance of ZodiosHooks const state = apiHooks.createInfiniteQuery( "/users", { queries: { limit: 10 }, }, { getPageParamList: () => ["page"], getNextPageParam: (lastPage, pages) => lastPage.nextPage ? { queries: { page: lastPage.nextPage, }, }: undefined; } ); ``` -------------------------------- ### Peer Dependencies Source: https://github.com/ecyrbe/zodios/blob/main/README.md Zodios does not embed any dependencies. Users are responsible for installing necessary peer dependencies. Key internal libraries used across all platforms include 'zod' and 'axios'. ```javascript // Zodios does not embed any dependencies. Install peer dependencies yourself. // Internal libraries: zod, axios ``` -------------------------------- ### Multipart/form-data Upload (Node.js FormData) Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/client.md Demonstrates sending multipart/form-data requests using the `form-data` library in a Node.js environment. This example appends a file to a FormData object and sends it with custom headers. ```typescript import FormData from 'form-data'; const apiClient = new Zodios( "https://mywebsite.com", [{ method: "post", path: "/upload", alias: "upload", description: "Upload a file", parameters:[ { name: "body", type: "Body", schema: z.instanceof(FormData), } ], response: z.object({ id: z.number(), }), }], ); const form = new FormData(); form.append('file', document.querySelector('#file').files[0]); const id = await apiClient.upload(form, { headers: form.getHeaders() }); ``` -------------------------------- ### Using Fetch Plugin Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/client/plugins.md Demonstrates how to use the fetch plugin with Zodios to leverage the browser's fetch API for API calls. This is useful when XHR limitations are a concern. Note that this plugin is not recommended for Node.js environments without a polyfill. ```typescript import { pluginFetch } from "@zodios/plugins"; apiClient.use(pluginFetch({ // all fetch options are supported keepAlive: true, })); ``` -------------------------------- ### Next.js Project File Structure Source: https://github.com/ecyrbe/zodios/blob/main/website/docs/server/next.md Provides a recommended file structure for integrating Zodios with a Next.js application, including common directories for API definitions, pages, and server logic. ```bash │ ├── src │ ├── common │ │ └── api.ts # API definition │ ├── pages │ │ ├── _app.tsx │ │ ├── api │ │ │ └── [...zodios].ts # import and re-export your main server app router here │ │ └── [..] │ ├── server │ │ ├── routers │ │ │ ├── app.ts # import your API definition and export your main app router here │ │ │ ├── users.ts # sub routers │ │ │ └── [..] │ │ ├── context.ts # export your main app context here └── [..] ```