Skip to content

Instantly share code, notes, and snippets.

View justinnoel's full-sized avatar

Justin Noel justinnoel

View GitHub Profile
@justinnoel
justinnoel / gist:74f28a203672b66aaee80629991f5edb
Created December 14, 2021 19:45 — forked from cryptoskillz/gist:98b8e7090b7cc8d51531bb9dcfe7654a
Tips on how to use a KV namespace with Cloudflare Pages
This gist aims to show you how to use KV datastore using Cloudflare pages. The reason I created this quick guide is it took
me almost 2 weeks to get it working, mainly because it is very new and the documentation is not up fully fleshed out yet
https://developers.cloudflare.com/workers/runtime-apis/kv
https://developers.cloudflare.com/pages/platform/functions
https://blog.cloudflare.com/wrangler-v2-beta/
Steps:
Install wrangler 2
@justinnoel
justinnoel / getJson.js
Last active November 13, 2021 12:54
Helper function to get JSON data from an API call and handle failures.
export async function getJson(url, options) {
try {
const response = await fetch(url, options);
const contentType = response.headers.get("content-type");
if (! response.ok || ! contentType.includes("application/json")) {
console.log(`ERROR: getJSON -> Invalid Response -> response.status = ${
response.status
}`,);
console.log(`ERROR: getJSON -> Invalid Response ->response.statusText = ${
@justinnoel
justinnoel / get-form-data.js
Last active November 12, 2021 11:46
Extract Form Submission Details for a Cloudflare Worker.
async function getFormData(request) {
const { headers } = request;
const contentType = headers.get("content-type") || "";
if (contentType.includes("application/json")) {
return await request.json();
}
if (contentType.includes("form")) {
const formData = await request.formData();