Skip to content

Commit bb65d1e

Browse files
committed
Add Cloudflare workers starter server
1 parent bf29fcc commit bb65d1e

18 files changed

Lines changed: 946 additions & 0 deletions
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
# Generated files
2+
node_modules
3+
dist
4+
jest.config.js
5+
jest.setup.js
6+
.lintstagedrc.js
7+
**.d.ts
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
const baseConfig = require("../../.lintstagedrc.js");
2+
3+
module.exports = {
4+
...baseConfig,
5+
};
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
# Generated files
2+
pnpm-lock.yaml
3+
node_modules
4+
dist
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2023 NodeBoot
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
# NodeBoot Cloudflare Server
2+
3+
Cloudflare Workers server package for NodeBoot framework. Provides seamless integration with the Cloudflare Workers
4+
Fetch API while maintaining all NodeBoot features including dependency injection, middleware, routing, and error
5+
handling.
6+
7+
## Features
8+
9+
- **Multi-route Worker Functions**: Handle multiple HTTP routes in a single Cloudflare Worker
10+
- **Full NodeBoot Integration**: Complete support for controllers, services, middleware, and dependency injection
11+
- **Standard Fetch API**: Native support for the Web Fetch API `Request`/`Response` objects used by Cloudflare Workers
12+
- **Request/Response Handling**: Automatic parsing of JSON bodies, query parameters, headers, and cookies
13+
- **Error Handling**: Integrated error handling with proper HTTP status codes
14+
- **Authorization**: Built-in authorization support using NodeBoot's authorization system
15+
- **Environment Bindings**: Access to Worker environment bindings (KV, D1, secrets, etc.) via the action context
16+
- **Codegen-free routing**: Ships its own dependency-free `SimpleRouter` instead of `find-my-way`, since
17+
Workers' V8 isolate disallows `eval`/`new Function` (which `find-my-way` relies on internally)
18+
19+
## Installation
20+
21+
```bash
22+
npm install @nodeboot/cloudflare-server
23+
```
24+
25+
## Basic Usage
26+
27+
### 1. Create your NodeBoot application
28+
29+
```typescript
30+
import {NodeBoot, NodeBootApp, NodeBootApplication, NodeBootAppView} from "@nodeboot/core";
31+
import {CloudflareServer} from "@nodeboot/cloudflare-server";
32+
import {EnableDI} from "@nodeboot/di";
33+
import {Container} from "typedi";
34+
35+
// A plain object, not a YAML file - see the note below.
36+
const appConfig = {
37+
app: {name: "my-app", platform: "node-boot"},
38+
api: {routePrefix: "/api"},
39+
};
40+
41+
/**
42+
* NodeBoot application entry point.
43+
*
44+
* Notice that, unlike the Express/Koa/Fastify samples, this application does not
45+
* "listen" on a port. Instead, it is bootstrapped once per Worker isolate (cold start)
46+
* and its `CloudflareServer` exposes a `fetch` handler function that the Cloudflare
47+
* runtime invokes for every incoming request.
48+
*/
49+
@EnableDI(Container)
50+
@NodeBootApplication()
51+
export class CloudflareSampleApp implements NodeBootApp {
52+
start(): Promise<NodeBootAppView> {
53+
// Cloudflare Workers have no filesystem, so `app-config.yaml`-style file-based config
54+
// discovery can never succeed at runtime. Pass your configuration in directly instead.
55+
return NodeBoot.run(CloudflareServer, appConfig);
56+
}
57+
}
58+
```
59+
60+
> **Note:** Unlike the Express/Koa/Fastify samples, this package does **not** support
61+
> `@EnableComponentScan()` (it relies on `fs.readdirSync`/`require.cache`, unavailable in
62+
> Workers). Import your controllers/services/middleware explicitly for their decorator side
63+
> effects instead - Wrangler's esbuild bundler will include them regardless. See the
64+
> [sample-cloudflare](../../samples/sample-cloudflare) README for the full rationale and every
65+
> other Workers-specific caveat (routing, dependency injection, logging, etc.).
66+
67+
### 2. Create your Worker entry point
68+
69+
```typescript
70+
import {CloudflareHandler, CloudflareServer} from "@nodeboot/cloudflare-server";
71+
import {CloudflareSampleApp} from "./app";
72+
73+
// Reused across warm invocations of the same Worker isolate.
74+
// Only re-initialized when Cloudflare spins up a brand-new isolate (cold start).
75+
let fetchHandler: CloudflareHandler | null = null;
76+
77+
export default {
78+
async fetch(request: Request, env: Record<string, unknown>, ctx: ExecutionContext): Promise<Response> {
79+
if (!fetchHandler) {
80+
const app = await new CloudflareSampleApp().start();
81+
const cloudflareServer = app.server as CloudflareServer;
82+
fetchHandler = cloudflareServer.getHandler();
83+
}
84+
85+
return fetchHandler(request, env, ctx);
86+
},
87+
};
88+
```
89+
90+
### 3. Create Controllers
91+
92+
```typescript
93+
import {Controller, Get, Post, Param, Body} from "@nodeboot/core";
94+
95+
@Controller("/api")
96+
export class UserController {
97+
@Get("/users/:id")
98+
getUser(@Param("id") id: string) {
99+
return {id, name: `User ${id}`};
100+
}
101+
102+
@Post("/users")
103+
createUser(@Body() userData: any) {
104+
return {success: true, user: userData};
105+
}
106+
}
107+
```
108+
109+
### 4. Deploy to Cloudflare Workers
110+
111+
Bundle your Worker (e.g. with `wrangler` or `esbuild`) and deploy using [Wrangler](https://developers.cloudflare.com/workers/wrangler/):
112+
113+
```bash
114+
wrangler deploy
115+
```
116+
117+
## Environment Bindings
118+
119+
Cloudflare Workers environment bindings (KV namespaces, D1 databases, secrets, service bindings, etc.) are made
120+
available through the `response`/execution context passed to every request, so they can be reached from middleware
121+
and error handlers via `action.response.env`.
122+
123+
## Middleware Support
124+
125+
All NodeBoot middleware is supported:
126+
127+
```typescript
128+
import {Middleware, MiddlewareInterface, Action} from "@nodeboot/core";
129+
130+
@Middleware({type: "before"})
131+
export class LoggingMiddleware implements MiddlewareInterface {
132+
@Inject("logger")
133+
private logger: Logger;
134+
135+
use(action: Action, payload: any): void {
136+
this.logger.info(`${action.request.method} ${action.request.url.pathname}`);
137+
}
138+
}
139+
```
140+
141+
> **Note:** Wrangler bundles your Worker with esbuild, which does not emit TypeScript decorator
142+
> metadata. Always use explicit injection tokens (`@Inject("logger")`, `@Inject(() =>
143+
SomeService)`) rather than bare `@Inject()`, and prefer **property injection** over constructor
144+
> injection - without decorator metadata, TypeDI can't determine constructor arity and will
145+
> silently fail to inject constructor parameters.
146+
147+
## Error Handling
148+
149+
Custom error handlers work seamlessly:
150+
151+
```typescript
152+
import {ErrorHandler, ErrorHandlerInterface} from "@nodeboot/core";
153+
154+
@ErrorHandler()
155+
export class CustomErrorHandler implements ErrorHandlerInterface {
156+
onError(error: any, action: Action): void {
157+
// Custom error handling logic
158+
}
159+
}
160+
```
161+
162+
## Authorization
163+
164+
NodeBoot's authorization system is fully supported. Use decorators like `@Authorize()` in your controllers to protect
165+
routes.
166+
167+
```typescript
168+
import {Authorize, Controller, Get} from "@nodeboot/core";
169+
170+
@Controller("/secure")
171+
export class SecureController {
172+
@Get("/data")
173+
@Authorize("admin")
174+
getSecureData() {
175+
return {secret: "This is secure data"};
176+
}
177+
}
178+
```
179+
180+
## Conclusion
181+
182+
The NodeBoot Cloudflare Server package provides a powerful way to build serverless applications using the familiar
183+
NodeBoot framework. With full support for routing, middleware, error handling, and authorization, you can create
184+
robust APIs that run on Cloudflare Workers with ease.
185+
186+
## License
187+
188+
This project is licensed under the MIT License.
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
module.exports = {
2+
transform: {
3+
"^.+\\.(t|j)sx?$": "@swc/jest",
4+
},
5+
};
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
{
2+
"$schema": "https://json.schemastore.org/nodemon.json",
3+
"watch": ["./src/**", "./node_modules/@mme/**/dist/**"],
4+
"ignoreRoot": [],
5+
"ext": "ts,js",
6+
"exec": "pnpm tsc && pnpm build"
7+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
{
2+
"name": "@nodeboot/cloudflare-server",
3+
"version": "1.0.0",
4+
"description": "Node-Boot Cloudflare Workers server package. It provides a simple way to create Cloudflare Workers fetch handlers using NodeBoot, with support for routing, middleware, and request handling.",
5+
"author": "Manuel Santos <ney.br.santos@gmail.com>",
6+
"license": "MIT",
7+
"keywords": [
8+
"nodeboot",
9+
"cloudflare",
10+
"cloudflare-workers",
11+
"serverless"
12+
],
13+
"repository": {
14+
"type": "git",
15+
"url": "https://github.com/nodejs-boot/node-boot.git"
16+
},
17+
"publishConfig": {
18+
"access": "public"
19+
},
20+
"main": "dist/index.js",
21+
"types": "dist/index.d.ts",
22+
"scripts": {
23+
"build": "tsc -p tsconfig.build.json",
24+
"clean:build": "rimraf ./dist",
25+
"lint": "eslint . --ext .js,.ts",
26+
"lint:fix": "pnpm lint --fix",
27+
"format": "prettier --check .",
28+
"format:fix": "prettier --write .",
29+
"pretest": "pnpm run clean:build && pnpm run build",
30+
"test": "node --test --test-reporter node-test-reporter --require ts-node/register test/**/*.{test,it.test}.ts",
31+
"test:coverage": "node --experimental-test-coverage --test --test-reporter node-test-reporter --require ts-node/register test/**/*.{test,it.test}.ts",
32+
"tsc": "tsc"
33+
},
34+
"dependencies": {
35+
"@nodeboot/context": "workspace:*",
36+
"@nodeboot/core": "workspace:*",
37+
"@nodeboot/engine": "workspace:*",
38+
"@nodeboot/error": "workspace:*",
39+
"cookie": "^1.0.2"
40+
},
41+
"devDependencies": {
42+
"@types/node": "^24.0.1"
43+
},
44+
"files": [
45+
"dist/**/*",
46+
"README.md",
47+
"LICENSE"
48+
]
49+
}

0 commit comments

Comments
 (0)