Section 5: The Data Layer
The Data Layer connects your SvelteKit Application to the WordPress endpoint. We've setup the User Interface of the application, now lets get the card data from WordPress.
In this section we’ll set up the
Type Definitions
Fetch Utility
GraphQL Queries
TypeScript Type Definitions
What is TypeScript?
TypeScript is JavaScript with types - it adds a type system on top of JavaScript
Types are used to describe your data
For example:
title: string; // Must be text
TypeScript prevents bugs by catching mistakes as you type by keeping track of the type of data being used.
Type Definitions
Type definitions are used to define the structure of data.
By doing this the TypeScript compiler knows what types of values to expect (catch errors before the code runs).
When SvelteKit makes requests to the WordPress endpoint, it will know the shape of the data that will be returned
Types.ts
Create a
types.tsfile insrc/lib/and add this code to it
Card Type
Represents a single trading card
All fields are typed (string, boolean, nested objects)
?marks optional fields
CardsResponse Type
The structure of the data when fetching ALL trading cards
Contains an array [] of
CardnodesIncludes
pageInfofor pagination support (optional)
Fetch Utility
Fetch is a browser API that makes HTTP requests. We’ll use it to retrieve the card data from the WordPress API Endpoint.
Api.ts
Create an api.ts file in src/lib/ and add this code:
In your code from step 1 above, update WP_GRAPHQL_URL with your site's GraphQL URL
Its on line 3
const WP_GRAPHQL_URL=You can find your GraphQL url in your WordPress Admin > GraphQL > Settings

Testing your setup
Test the WordPress endpoint
Visit your WordPress GraphQL endpoint url in your browser
You should see the GraphiQL IDE from WPGraphQL
If you see the IDE, your endpoint is reachable
After completing this section, your src/lib/ folder should look like:

Understanding the Data Flow
