From 2e42d800c7b58960d17ee09d702830d21c3d8ca0 Mon Sep 17 00:00:00 2001 From: Maciej Niemcewicz Date: Fri, 29 Mar 2024 16:22:14 +0100 Subject: [PATCH] add deploy to Cloudflare Workers button --- .github/workflows/cloudflare_worker.yml | 36 +++++++++++ README.md | 17 +++++- worker-index.js | 80 +++++++++++++++++++++++++ wrangler.toml | 7 +++ 4 files changed, 139 insertions(+), 1 deletion(-) create mode 100644 .github/workflows/cloudflare_worker.yml create mode 100644 worker-index.js create mode 100644 wrangler.toml diff --git a/.github/workflows/cloudflare_worker.yml b/.github/workflows/cloudflare_worker.yml new file mode 100644 index 0000000..b17ecc6 --- /dev/null +++ b/.github/workflows/cloudflare_worker.yml @@ -0,0 +1,36 @@ +name: Deploy Cloudflare Worker +on: + repository_dispatch: + workflow_dispatch: + +jobs: + deploy: + runs-on: ubuntu-latest + strategy: + matrix: + node-version: [ 18.x ] + steps: + - uses: actions/checkout@v2 + - name: Use Node.js {{ matrix.node-version }} + uses: actions/setup-node@v1 + with: + node-version: ${{ matrix.node-version }} + - name: Check if Flotiq API key is set. + env: + GATSBY_FLOTIQ_API_KEY: ${{ secrets.GATSBY_FLOTIQ_API_KEY }} + run: | + if [ -z "$GATSBY_FLOTIQ_API_KEY" ]; then + echo "Flotiq API Key is not set, using a starter one." && echo "GATSBY_FLOTIQ_API_KEY=f42a50abdedb94da5ff573d08cbaee97" >> $GITHUB_ENV + else + echo "Using user-provided Flotiq API Key. Importing starter data to Flotiq." && echo "GATSBY_FLOTIQ_API_KEY=$GATSBY_FLOTIQ_API_KEY" >> $GITHUB_ENV + npm install -g flotiq-cli + flotiq import . $GATSBY_FLOTIQ_API_KEY + fi + - run: npm install -g gatsby-cli + - run: yarn install + - run: gatsby build + - name: Build & Deploy Worker + uses: cloudflare/wrangler-action@v3 + with: + apiToken: ${{ secrets.CF_API_TOKEN }} + accountId: ${{ secrets.CF_ACCOUNT_ID }} diff --git a/README.md b/README.md index ad5db3c..5a531ba 100644 --- a/README.md +++ b/README.md @@ -112,6 +112,15 @@ Or to [Netlify](https://www.netlify.com/): [![Deploy](https://www.netlify.com/img/deploy/button.svg)](https://app.netlify.com/start/deploy?repository=https://github.com/flotiq/flotiq-gatsby-event-1) +Or to [Cloudflare Workers](https://workers.cloudflare.com/): + +[![Deploy to Cloudflare Workers](https://deploy.workers.cloudflare.com/button)](https://deploy.workers.cloudflare.com/?url=https://github.com/flotiq/flotiq-gatsby-event-1) + +### Note +Cloudflare Workers deployment uses Flotiq starter API key, if you want to deploy a worker with your own Flotiq API key, after deployment go to your forked repository on GitHub and add a GATSBY_FLOTIQ_API secret in repository's settings, then in Actions, select "Deploy Cloudflare Worker" workflow and click "Run workflow" to deploy the worker again. + +More information about GitHub secrets can be found [here](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions). + ## What's inside? @@ -144,6 +153,8 @@ A quick look at the top-level files and directories you'll see in a Gatsby proje ├── README.md ├── static.json ├── tailwind.config.js + ├── worker-index.js + ├── wrangler.toml └── yarn.lock 1. **`.flotiq`**: This directory contains content types necessary to starter to work. @@ -198,7 +209,11 @@ A quick look at the top-level files and directories you'll see in a Gatsby proje 26. **`tailwind.config.js`**: Configuration file for tailwind. -27. **`yarn.lock`**: This is an automatically generated file based on the exact versions of your yarn dependencies that were installed for your project. **(You won’t change this file directly).** +27. **`worker-index.js`**: Main file for Cloudflare Workers. + +28. **`wrangler.toml`**: Configuration file for Cloudflare Workers deployment. + +29. **`yarn.lock`**: This is an automatically generated file based on the exact versions of your yarn dependencies that were installed for your project. **(You won’t change this file directly).** ## Learning Gatsby diff --git a/worker-index.js b/worker-index.js new file mode 100644 index 0000000..f980a77 --- /dev/null +++ b/worker-index.js @@ -0,0 +1,80 @@ +import { getAssetFromKV, mapRequestToAsset } from '@cloudflare/kv-asset-handler' + +/** + * The DEBUG flag will do two things that help during development: + * 1. we will skip caching on the edge, which makes it easier to + * debug. + * 2. we will return an error message on exception in your Response rather + * than the default 404.html page. + */ +const DEBUG = false + +addEventListener('fetch', event => { + try { + event.respondWith(handleEvent(event)) + } catch (e) { + if (DEBUG) { + return event.respondWith( + new Response(e.message || e.toString(), { + status: 500, + }), + ) + } + event.respondWith(new Response('Internal Error', { status: 500 })) + } +}) + +async function handleEvent(event) { + const url = new URL(event.request.url) + let options = {} + + /** + * You can add custom logic to how we fetch your assets + * by configuring the function `mapRequestToAsset` + */ + // options.mapRequestToAsset = handlePrefix(/^\/docs/) + + try { + if (DEBUG) { + // customize caching + options.cacheControl = { + bypassCache: true, + } + } + return await getAssetFromKV(event, options) + } catch (e) { + // if an error is thrown try to serve the asset at 404.html + if (!DEBUG) { + try { + let notFoundResponse = await getAssetFromKV(event, { + mapRequestToAsset: req => new Request(`${new URL(req.url).origin}/404.html`, req), + }) + + return new Response(notFoundResponse.body, { ...notFoundResponse, status: 404 }) + } catch (e) {} + } + + return new Response(e.message || e.toString(), { status: 500 }) + } +} + +/** + * Here's one example of how to modify a request to + * remove a specific prefix, in this case `/docs` from + * the url. This can be useful if you are deploying to a + * route on a zone, or if you only want your static content + * to exist at a specific path. + */ +function handlePrefix(prefix) { + return request => { + // compute the default (e.g. / -> index.html) + let defaultAssetKey = mapRequestToAsset(request) + let url = new URL(defaultAssetKey.url) + + // strip the prefix from the path for lookup + url.pathname = url.pathname.replace(prefix, '/') + + // inherit all other props from the default request + return new Request(url.toString(), defaultAssetKey) + } +} \ No newline at end of file diff --git a/wrangler.toml b/wrangler.toml new file mode 100644 index 0000000..811a461 --- /dev/null +++ b/wrangler.toml @@ -0,0 +1,7 @@ +name = "flotiq-gatsby-event-1" +main = "worker-index.js" +compatibility_date = "2024-03-27" +workers_dev = true + +[site] +bucket = "./public" \ No newline at end of file