|
| 1 | +"use server"; |
| 2 | + |
| 3 | +type FetchQueryProps = { |
| 4 | + query: string; |
| 5 | + variables?: { [key: string]: unknown }; |
| 6 | +}; |
| 7 | + |
| 8 | +const fetchQuery = async ({ query, variables }: FetchQueryProps) => { |
| 9 | + try { |
| 10 | + const res = await fetch(process.env.HYPERMODE_API_ENDPOINT as string, { |
| 11 | + method: "POST", |
| 12 | + headers: { |
| 13 | + "Content-Type": "application/json", |
| 14 | + Authorization: `Bearer ${process.env.HYPERMODE_API_TOKEN}`, |
| 15 | + }, |
| 16 | + body: JSON.stringify({ |
| 17 | + query, |
| 18 | + variables, |
| 19 | + }), |
| 20 | + cache: "no-store", |
| 21 | + }); |
| 22 | + |
| 23 | + if (res.status < 200 || res.status >= 300) { |
| 24 | + throw new Error(res.statusText); |
| 25 | + } |
| 26 | + |
| 27 | + const { data, error, errors } = await res.json(); |
| 28 | + return { data, error: error || errors }; |
| 29 | + } catch (err) { |
| 30 | + console.error("error in fetchQuery:", err); |
| 31 | + return { data: null, error: err }; |
| 32 | + } |
| 33 | +}; |
| 34 | + |
| 35 | +export async function searchProducts( |
| 36 | + query: string, |
| 37 | + maxItems: number, |
| 38 | + thresholdStars: number, |
| 39 | + inStockOnly: boolean = false |
| 40 | +) { |
| 41 | + const graphqlQuery = ` |
| 42 | +query searchProducts($query: String!, $maxItems: Int!, $thresholdStars: Float!, $inStockOnly: Boolean!) { |
| 43 | + searchProducts(query: $query, maxItems: $maxItems, thresholdStars: $thresholdStars, inStockOnly: $inStockOnly) { |
| 44 | + searchObjs { |
| 45 | + product { |
| 46 | + name |
| 47 | + id |
| 48 | + image |
| 49 | + description |
| 50 | + stars |
| 51 | + price |
| 52 | + isStocked |
| 53 | + category |
| 54 | + } |
| 55 | +} |
| 56 | + } |
| 57 | +} |
| 58 | + `; |
| 59 | + |
| 60 | + const { error, data } = await fetchQuery({ |
| 61 | + query: graphqlQuery, |
| 62 | + variables: { |
| 63 | + query, |
| 64 | + maxItems, |
| 65 | + thresholdStars, |
| 66 | + inStockOnly, |
| 67 | + }, |
| 68 | + }); |
| 69 | + |
| 70 | + if (error) { |
| 71 | + return { error: Array.isArray(error) ? error[0] : error }; |
| 72 | + } else { |
| 73 | + return { data }; |
| 74 | + } |
| 75 | +} |
0 commit comments