/cloudflare-workers-d1-template

Experimental project focused on Cloudflare, applying clean architecture, being decoupled, and technology-agnostic to support REST, GraphQL, Node.js, Workers, D1, and Prisma.

Primary LanguageTypeScript

Cloudflare Workers D1 Template

This is a template for a Cloudflare Workers project that uses D1 and Hono. It includes multiple options for running the project locally, on Cloudflare's edge network, and testing. There is also an alternative version of the project that uses Node.js with Prisma and Express in the same codebase.

Insomnia

Run in Insomnia}

Getting started

  1. Install dependencies
npm install
  1. Create a D1 database locally
npx wrangler d1 execute d1-template --local --file ./src/infra/repository/d1/migrations/0000_init.sql
  1. Start the development server
npm run dev

This will start a server at http://localhost:3000, with the Cloudflare Workers entrypoint at ./src/workers.ts.

Deploying to Cloudflare's edge network

  1. Sign in to Cloudflare
npx wrangler login
  1. Create a D1 database on Cloudflare's edge network and fill in the database_name, database_id, and preview_database_id fields in .wrangler.toml:
npx wrangler d1 create d1-template
  1. (Optional) Create a migration
npx wrangler d1 migrations create d1-template "second migration"

There is already a migration in ./src/infra/repository/d1/migrations, so you can skip this step.

  1. Run the following command to apply the database migrations:
npx wrangler d1 migrations apply d1-template
  1. Starting the staging server
npm run dev:staging

This will start a server at Cloudflare in http://localhost:3000 through a tunnel.

  1. Deploying to production
npx wrangler publish --minify

Testing

With the dev or staging server running, you can run end-to-end, integration, and unit tests with the following command:

npm run test

Experiment with the GraphQL version

To try out the GraphQL version of the project, run the development server with the following command:

npm run dev:graphql

Open http://localhost:3000/graphql in your browser. The entrypoint for this version is ./src/workers-graphql.ts.

Alternative version using Node.js

To try the alternative version using Node.js, follow these steps:

  1. Create an environment file based on the example:
cp .env.example .env
  1. Execute the Prisma SQLite migration (this will also generate the Prisma Client):
npx prisma migrate dev
  1. Start the Node.js development server
npm run dev:node

This will start a server at http://localhost:3000, with the Node.js entrypoint at ./src/node.ts.

  1. Alternatively, start the production server:
npm run start
  1. To try the GraphQL version, run the following command:
npm run dev:node:graphql

Open http://localhost:3000/graphql in your browser. The entrypoint for this version is ./src/node-graphql.ts.