Fetching From D1 using Workers

How Do I Create an endpoint using Cloudflare D1 and workers that returns the entire table as JSON when fetched? I want to know what code I need to put in the workers.js file to return the entire table from a D1 database as JSON when fetched. I need this so that on an HTML page, I can fetch the JSON using the public read-only endpoint, and then I already have the rest of the code working, where it creates a array using the JSON. In other words, I want to create a read-only D1 worker that will replace my current nocodb endpoint: async function fetchAllData() { try { const response = await fetch('https://app.nocodb.com/api/v1/db/data/noco/phgforxa020gg7q/ml1ww2bojawn3mf/views/vwy72p5sijrhvnmg?where=(Public,eq,true)', options); if (!response.ok) throw new Error('Failed to fetch data'); return (await response.json()).list; } catch (error) { console.error(error); return []; } }
4 Replies
AndyJessop
AndyJessop2mo ago
I think you'll want something like this:
async function getAllData(env) {
try {
const result = await env.DB.prepare('SELECT * FROM name_of_your_table').all();

return new Response(JSON.stringify(result.results), {
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
return new Response('Internal Server Error', { status: 500 });
}
}
async function getAllData(env) {
try {
const result = await env.DB.prepare('SELECT * FROM name_of_your_table').all();

return new Response(JSON.stringify(result.results), {
headers: { 'Content-Type': 'application/json' },
});
} catch (error) {
return new Response('Internal Server Error', { status: 500 });
}
}
Farwalker3 | Rogues
I put that in workers.js and got "D1 bindings require module-format workers. (Code: 10021)"
AndyJessop
AndyJessop2mo ago
I think the best thing here is for you to take a look at this page, and follow along to ensure that you have the worker setup correctly. The function I gave you was just following your original code (e.g. using fetchAllData), but you will need to call that from inside the fetch function detailed on the docs page I just linked.
Farwalker3 | Rogues
Okay, thank you!