Here’s how you can use the openapi-ts library with the undb platform in a Node.js environment to generate TypeScript types and create an API client for SvelteKit.
Step 1: Install Dependencies
First, install the necessary dependencies:
Step 2: Fetch the OpenAPI Schema and Generate TypeScript Types
Create a script (generate-types.js) that fetches the OpenAPI schema from the undb platform and generates the corresponding TypeScript types:
Step 3: Run the Type Generation Script
You can run this script using Node.js:
This will generate the TypeScript types in the ./src/lib/api/templates.d.ts file.
Step 4: Use the Generated Types in Your SvelteKit Project
In your SvelteKit project, you can use the generated types and set up an API client as follows:
Step 5: Make API Requests Using the Client
Now, you can use the templateClient to interact with your undb API. Here’s an example of how to fetch records:
Summary
Generate Types: The script fetches the OpenAPI spec from undb and generates TypeScript types.
Create API Client: The generated types are used to create a type-safe API client.
Use in SvelteKit: The API client can be used in SvelteKit to make requests with proper type checking.
This approach ensures that your API interactions are type-safe and well-integrated into your SvelteKit project.