Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add deploy to Cloudflare Workers button #29

Merged
merged 1 commit into from
Mar 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions .github/workflows/cloudflare_worker.yml
Original file line number Diff line number Diff line change
@@ -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 }}
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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?

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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

Expand Down
80 changes: 80 additions & 0 deletions worker-index.js
Original file line number Diff line number Diff line change
@@ -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)
}
}
7 changes: 7 additions & 0 deletions wrangler.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
name = "flotiq-gatsby-event-1"
main = "worker-index.js"
compatibility_date = "2024-03-27"
workers_dev = true

[site]
bucket = "./public"
Loading