Skip to content

Commit

Permalink
I got it working!!!
Browse files Browse the repository at this point in the history
  • Loading branch information
BMorearty committed Jan 18, 2023
1 parent 5b935a9 commit 33cbca1
Show file tree
Hide file tree
Showing 10 changed files with 56 additions and 50 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ node_modules
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
kv-data/
1 change: 1 addition & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"singleQuote": true,
"printWidth": 100,
"proseWrap": "always",
"plugins": ["prettier-plugin-svelte"],
"pluginSearchDirs": ["."],
"overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
Expand Down
40 changes: 4 additions & 36 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,38 +1,6 @@
# create-svelte
# svelte-local-cloudflare-dev-working

Everything you need to build a Svelte project, powered by [`create-svelte`](https://github.com/sveltejs/kit/tree/master/packages/create-svelte).
This ended up just being a playground for me to figure out how to run a Sveltekit app on Cloudflare
and attach to KVs, DOs, etc.

## Creating a project

If you're seeing this, you've probably already done this step. Congrats!

```bash
# create a new project in the current directory
npm create svelte@latest

# create a new project in my-app
npm create svelte@latest my-app
```

## Developing

Once you've created a project and installed dependencies with `npm install` (or `pnpm install` or `yarn`), start a development server:

```bash
npm run dev

# or start the server and open the app in a new browser tab
npm run dev -- --open
```

## Building

To create a production version of your app:

```bash
npm run build
```

You can preview the production build with `npm run preview`.

> To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.
See my SvelteKit Tips & Tricks doc, "Local development with Cloudflare."
7 changes: 3 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
{
"name": "giftideas",
"name": "svelte-local-cloudflare-dev-working",
"version": "0.0.1",
"private": true,
"scripts": {
"--": "should I use --ext js,ts,svelte,html,png,gif,jpg,jpeg ?",
"watch": "nodemon --ext '*' --watch src --exec \"vite build --minify false --sourcemap true\"",
"dev": "wrangler pages dev .svelte-kit/cloudflare --kv GIFTS --live-reload",
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"test": "playwright test",
Expand All @@ -25,6 +23,7 @@
"eslint": "^8.32.0",
"eslint-config-prettier": "^8.6.0",
"eslint-plugin-svelte3": "^4.0.0",
"miniflare": "^2.11.0",
"nodemon": "^2.0.20",
"prettier": "^2.8.3",
"prettier-plugin-svelte": "^2.9.0",
Expand Down
2 changes: 2 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 11 additions & 0 deletions src/hooks.server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { dev } from '$app/environment';
import type { Handle } from '@sveltejs/kit';

export const handle: Handle = async ({ event, resolve }) => {
if (dev) {
const { fallBackPlatformToMiniFlareInDev } = await import('$lib/clients/miniflare');
// @ts-expect-error I don't know why
event.platform = await fallBackPlatformToMiniFlareInDev(event.platform);
}
return resolve(event);
};
31 changes: 31 additions & 0 deletions src/lib/clients/miniflare.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { Miniflare, Log, LogLevel } from 'miniflare';
import { dev } from '$app/environment';

export const fallBackPlatformToMiniFlareInDev = async (_platform: App.Platform) => {
if (!dev) return _platform;

if (_platform) return _platform;
const mf = new Miniflare({
log: new Log(LogLevel.INFO),
kvPersist: './kv-data', // Use filebase or in memory store
kvNamespaces: ['GIFTS'], //Declare array with NameSpaces
globalAsyncIO: true,
globalTimers: true,
globalRandom: true,

script: `
addEventListener("fetch", (event) => {
event.waitUntil(Promise.resolve(event.request.url));
event.respondWith(new Response(event.request.headers.get("X-Message")));
});
addEventListener("scheduled", (event) => {
event.waitUntil(Promise.resolve(event.scheduledTime));
});
`,
});

const env = await mf.getBindings();
// @ts-expect-error i don't know why
const platform: App.Platform = { env };
return platform;
};
9 changes: 1 addition & 8 deletions src/routes/+page.server.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
import type { Actions, PageServerLoad } from './$types';
import { redirect } from '@sveltejs/kit';
import { env } from '$env/dynamic/private';

export const load: PageServerLoad = async ({ platform }) => {
console.log({platform});
Expand All @@ -16,16 +14,11 @@ export const load: PageServerLoad = async ({ platform }) => {

export const actions: Actions = {
default: async ({ platform, request }) => {
const promises = [];
try {
const data = await request.formData();
const hello = data.get('hello') as string;
console.log({ actions: 'yes', hello });
if (hello) {
promises.push(platform?.env?.GIFTS.put('hello', hello));
await platform?.env?.GIFTS.put('hello', hello);
}
} finally {
await Promise.all(promises);
}
},
};
2 changes: 1 addition & 1 deletion src/routes/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

<h1>Welcome to SvelteKit</h1>
<p>Data.hello is now {data.hello}</p>
<form method="POST" use:enhance>
<form method="POST">
Change it to
<input name="hello" bind:value={hello} type="text" />
<input type="submit" />
Expand Down
2 changes: 1 addition & 1 deletion wrangler.toml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name = "giftideas"
name = "svelte-local-cloudflare-dev-working"
compatibility_date = "2023-01-11"

[env.dev]
Expand Down

1 comment on commit 33cbca1

@ajgeiss0702
Copy link

@ajgeiss0702 ajgeiss0702 commented on 33cbca1 Apr 27, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know im a bit late, but the // @ts-expect-error I don't know why in hooks.server.ts is due to event.platform possibly being undefined, however the fallBackPlatformToMiniFlareInDev function is typed to not accept undefined. Adding | undefined fixes the issue:

export const fallBackPlatformToMiniFlareInDev = async (_platform: App.Platform | undefined) => {
  ...
}

The issue inside fallBackPlatformToMiniFlareInDev is because Context (returned by miniflare) is not in App.Platform. Asserting it as App.Platform fixes it:

const platform: App.Platform = { env } as App.Platform;

Please sign in to comment.