Created
May 4, 2024 23:00
-
-
Save CyberClarence/8c91b44c9c2b04b2cf77babbffad79b2 to your computer and use it in GitHub Desktop.
CloudFlare D1 Web Worker HTTP Proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Welcome to Cloudflare Workers! This is your first worker. | |
* | |
* - Run `npm run dev` in your terminal to start a development server | |
* - Open a browser tab at http://localhost:8787/ to see your worker in action | |
* - Run `npm run deploy` to publish your worker | |
* | |
* Bind resources to your worker in `wrangler.toml`. After adding bindings, a type definition for the | |
* `Env` object can be regenerated with `npm run cf-typegen`. | |
* | |
* Learn more at https://developers.cloudflare.com/workers/ | |
*/ | |
export default { | |
async fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> { | |
const { sql, params, apiKey }: any = await request.json(); | |
try { | |
if (apiKey != 'api key here') { | |
throw 'invalid api key'; | |
} | |
const query = env.DB.prepare(sql); | |
const binded = query.bind(...params); | |
const results = await binded.raw(); | |
return new Response(JSON.stringify({ results })); | |
} catch (error: any) { | |
const err = error?.message || error; | |
return new Response(JSON.stringify({ error: { msg: err, meta: { sql, params, apiKey } } })); | |
} | |
}, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment