Skip to content

Commit

Permalink
Add hello world example for Durable Objects
Browse files Browse the repository at this point in the history
  • Loading branch information
joshthoward committed Jan 16, 2024
1 parent 8d6b3ee commit 3290c37
Show file tree
Hide file tree
Showing 14 changed files with 760 additions and 0 deletions.
4 changes: 4 additions & 0 deletions packages/create-cloudflare/src/templateMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ export const templateMap: Record<string, TemplateConfig> = {
label: `"Hello World" Worker`,
handler: runWorkersGenerator,
},
"hello-world-durable-object": {
label: `"Hello World" Durable Object`,
handler: runWorkersGenerator,
},
webFramework: {
label: "Website or web app",
handler: runPagesGenerator,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# http://editorconfig.org
root = true

[*]
indent_style = tab
tab_width = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.yml]
indent_style = space
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
# Logs

logs
_.log
npm-debug.log_
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)

report.[0-9]_.[0-9]_.[0-9]_.[0-9]_.json

# Runtime data

pids
_.pid
_.seed
\*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover

lib-cov

# Coverage directory used by tools like istanbul

coverage
\*.lcov

# nyc test coverage

.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)

.grunt

# Bower dependency directory (https://bower.io/)

bower_components

# node-waf configuration

.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)

build/Release

# Dependency directories

node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)

web_modules/

# TypeScript cache

\*.tsbuildinfo

# Optional npm cache directory

.npm

# Optional eslint cache

.eslintcache

# Optional stylelint cache

.stylelintcache

# Microbundle cache

.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history

.node_repl_history

# Output of 'npm pack'

\*.tgz

# Yarn Integrity file

.yarn-integrity

# dotenv environment variable files

.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)

.cache
.parcel-cache

# Next.js build output

.next
out

# Nuxt.js build / generate output

.nuxt
dist

# Gatsby files

.cache/

# Comment in the public line in if your project uses Gatsby and not Next.js

# https://nextjs.org/blog/next-9-1#public-directory-support

# public

# vuepress build output

.vuepress/dist

# vuepress v2.x temp and cache directory

.temp
.cache

# Docusaurus cache and generated files

.docusaurus

# Serverless directories

.serverless/

# FuseBox cache

.fusebox/

# DynamoDB Local files

.dynamodb/

# TernJS port file

.tern-port

# Stores VSCode versions used for testing VSCode extensions

.vscode-test

# yarn v2

.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.\*

# wrangler project

.dev.vars
.wrangler/
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"printWidth": 140,
"singleQuote": true,
"semi": true,
"useTabs": true
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"name": "<TBD>",
"version": "0.0.0",
"private": true,
"scripts": {
"deploy": "wrangler deploy",
"dev": "wrangler dev",
"start": "wrangler dev"
},
"devDependencies": {
"wrangler": "^3.0.0"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/**
* Welcome to Cloudflare Workers! This is your first Durable Objects application.
*
* - Run `npm run dev` in your terminal to start a development server
* - Open a browser tab at http://localhost:8787/ to see your Durable Object in action
* - Run `npm run deploy` to publish your application
*
* Learn more at https://developers.cloudflare.com/durable-objects
*/

/**
* Env provides a mechanism to reference bindings declared in wrangler.toml within JavaScript
*
* @typedef {Object} env
* @property {DurableObjectNamespace} MY_DURABLE_OBJECT - The Durable Object namespace binding
*/

/** A Durable Object's behavior is defined in an exported Javascript class */
export class MyDurableObject {
/**
* The constructor is invoked once upon creation of the Durable Object, i.e. the first call to
* `DurableObjectStub::get` for a given identifier
*
* @param {DurableObjectState} state - The interface for interacting with Durable Object state
* @param {Env} env - The interface to reference bindings declared in wrangler.toml
*/
constructor(state, env) {}

/**
* The Durable Object fetch handler will be invoked when a Durable Object instance receives a
* request from a Worker via an associated stub
*
* @param {Request} request - The request submitted to a Durable Object instance from a Worker
* @returns {Promise<Response>} The response to be sent back to the Worker
*/
async fetch(request) {
return new Response("Hello World");
}
}

export default {
/**
* This is the standard fetch handler for a Cloudflare Worker
*
* @param {Request} request - The request submitted to the Worker from the client
* @param {Env} env - The interface to reference bindings declared in wrangler.toml
* @param {ExecutionContext} ctx - The execution context of the Worker
* @returns {Promise<Response>} The response to be sent back to the client
*/
async fetch(request, env, ctx) {
// We will create a `DurableObjectId` using the pathname from the Worker request
// This id refers to a unique instance of our 'MyDurableObject' class above
let id = env.MY_DURABLE_OBJECT.idFromName(new URL(request.url).pathname);

// This stub creates a communication channel with the Durable Object instance
// The Durable Object constructor will be invoked upon the first call for a given id
let stub = env.MY_DURABLE_OBJECT.get(id);

// We call `fetch()` on the stub to send a request to the Durable Object instance
// The Durable Object instance will invoke its fetch handler to handle the request
let response = await stub.fetch(request);

return response;
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
name = "<TBD>"
main = "src/index.js"
compatibility_date = "<TBD>"

# Variable bindings. These are arbitrary, plaintext strings (similar to environment variables)
# Note: Use secrets to store sensitive data.
# Docs: https://developers.cloudflare.com/workers/platform/environment-variables
# [vars]
# MY_VARIABLE = "production_value"

# Bind a KV Namespace. Use KV as persistent storage for small key-value pairs.
# Docs: https://developers.cloudflare.com/workers/runtime-apis/kv
# [[kv_namespaces]]
# binding = "MY_KV_NAMESPACE"
# id = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"

# Bind an R2 Bucket. Use R2 to store arbitrarily large blobs of data, such as files.
# Docs: https://developers.cloudflare.com/r2/api/workers/workers-api-usage/
# [[r2_buckets]]
# binding = "MY_BUCKET"
# bucket_name = "my-bucket"

# Bind a Queue producer. Use this binding to schedule an arbitrary task that may be processed later by a Queue consumer.
# Docs: https://developers.cloudflare.com/queues/get-started
# [[queues.producers]]
# binding = "MY_QUEUE"
# queue = "my-queue"

# Bind a Queue consumer. Queue Consumers can retrieve tasks scheduled by Producers to act on them.
# Docs: https://developers.cloudflare.com/queues/get-started
# [[queues.consumers]]
# queue = "my-queue"

# Bind another Worker service. Use this binding to call another Worker without network overhead.
# Docs: https://developers.cloudflare.com/workers/platform/services
# [[services]]
# binding = "MY_SERVICE"
# service = "my-service"

# Bind a Durable Object. Durable objects are a scale-to-zero compute primitive based on the actor model.
# Durable Objects can live for as long as needed. Use these when you need a long-running "server", such as in realtime apps.
# Docs: https://developers.cloudflare.com/workers/runtime-apis/durable-objects
[[durable_objects.bindings]]
name = "MY_DURABLE_OBJECT"
class_name = "MyDurableObject"

# Durable Object migrations.
# Docs: https://developers.cloudflare.com/workers/learning/using-durable-objects#configure-durable-object-classes-with-migrations
[[migrations]]
tag = "v1"
new_classes = ["MyDurableObject"]
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# http://editorconfig.org
root = true

[*]
indent_style = tab
tab_width = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true

[*.yml]
indent_style = space
Loading

0 comments on commit 3290c37

Please sign in to comment.