Graphql query variables. Can you pass JS variable into the query?

This works fine when i set the query variable as the literal string.

import { FAUNADB_SECRET_KEY } from "$env/static/private";
export const POST = async ({ request }) => {
	const query = `
	query findByWallet($wallet: String!){
		findByWallet(wallet:$wallet){
		  data{
			wallet
			points
			rank
		  }
		}
	  }
    `;
	const variables = {
		"wallet": "0x7EC0DB5eB524D16e229110D1c637DCBCCe62Cd7d"
	}
	const res = await fetch("https://graphql.us.fauna.com/graphql", {
		method: "POST",
		headers: {
			Authorization: `Bearer ${FAUNADB_SECRET_KEY}`
		},
		body: JSON.stringify({
			query,
			variables
		})
	});
	let data = await res.json();
console.log(data);

	return new Response(JSON.stringify({data}), { status: 200 });
};

If I try and use a JavaScript variable in my query variable that equals the same as the previous example it returns empty. I don’t understand why this doesn’t work. How do I pass in JS variables as query variable?

import { FAUNADB_SECRET_KEY } from "$env/static/private";
export const POST = async ({ request }) => {

	const body = await request.json();
	const wallet = body.id;
	console.log(typeof wallet);
	//String
	console.log(wallet);
	//0x7ec0db5eb524d16e229110d1c637dcbcce62cd7d
	
	const query = `
	query findByWallet($wallet: String!){
		findByWallet(wallet:$wallet){
		  data{
			wallet
			points
			rank
		  }
		}
	  }
    `;
	const variables = {
		"wallet": wallet
	}
	const res = await fetch("https://graphql.us.fauna.com/graphql", {
		method: "POST",
		headers: {
			Authorization: `Bearer ${FAUNADB_SECRET_KEY}`
		},
		body: JSON.stringify({
			query,
			variables
		})
	});
	let data = await res.json();
console.log(data);

	return new Response(JSON.stringify({data}), { status: 200 });
};

Hi @flygOn-LiTe and welcome! :wave:

The short answer is: Yes!

graphql.org documentation includes an example using javascript restructuring.

If your first example returns the data that you want, then you need to figure out what the difference is between it and your second example. Somehow, it may be that wallet is not serializing (converted to a string) the same way in both examples.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.