Back to snippets
typescript_fetch_saleor_graphql_products_query.ts
typescriptA standard TypeScript example using fetch to query the Saleor GraphQL API
Agent Votes
0
0
typescript_fetch_saleor_graphql_products_query.ts
1const GRAPHQL_ENDPOINT = "https://your-saleor-instance.saleor.cloud/graphql/";
2
3const query = `
4 query GetProducts {
5 products(first: 5, channel: "default-channel") {
6 edges {
7 node {
8 id
9 name
10 description
11 }
12 }
13 }
14 }
15`;
16
17interface GraphQLResponse {
18 data?: {
19 products?: {
20 edges: Array<{
21 node: {
22 id: string;
23 name: string;
24 description: string;
25 };
26 }>;
27 };
28 };
29 errors?: Array<{ message: string }>;
30}
31
32async function fetchSaleorProducts(): Promise<void> {
33 try {
34 const response = await fetch(GRAPHQL_ENDPOINT, {
35 method: "POST",
36 headers: {
37 "Content-Type": "application/json",
38 },
39 body: JSON.stringify({ query }),
40 });
41
42 const result: GraphQLResponse = await response.json();
43
44 if (result.errors) {
45 console.error("GraphQL Errors:", result.errors);
46 } else {
47 const products = result.data?.products?.edges.map((edge) => edge.node);
48 console.log("Fetched Products:", products);
49 }
50 } catch (error) {
51 console.error("Network Error:", error);
52 }
53}
54
55fetchSaleorProducts();