- Super lightweight
- First-class TypeScript support
- Custom Middleware Support
- Well-organized submodules for à la carte functionality*
- Includes Router with support for pattern definitions
- Familiar Request-Response handler API
- Supports
async
/await
handlers - Fully treeshakable
*More to come!
$ npm install --save worktop
Check out
/examples
for a list of working demos!
import { Router } from 'worktop';
import * as utils from 'worktop/utils';
import { reply } from 'worktop/response';
// Cloudflare-specific Submodules
import { start } from 'worktop/cfw';
import * as Cache from 'worktop/cfw.cache';
import { read, write } from 'worktop/cfw.kv';
import type { KV } from 'worktop/cfw.kv';
import type { Context } from 'worktop';
interface Bindings extends Context {
bindings: {
DATA: KV.Namespace
}
}
interface Message {
id: string;
text: string;
// ...
}
// Create new Router instance
const API = new Router<Bindings>();
// Any `prepare` logic runs 1st for every request, before routing
// ~> use `Cache` for request-matching, when permitted
// ~> store Response in `Cache`, when permitted
API.prepare = Cache.sync();
API.add('GET', '/messages/:id', async (req, context) => {
// Pre-parsed `context.params` object
const key = `messages::${context.params.id}`;
// Assumes JSON (can override)
const message = await read<Message>(context.bindings.DATA, key);
// Smart `send` helper
// ~> automatically stringifies JSON objects
// ~> auto-sets `Content-Type` & `Content-Length` headers
return reply(200, message, {
'Cache-Control': 'public, max-age=60'
});
});
API.add('POST', '/messages', async (req, context) => {
try {
// Smart `utils.body` helper
// ~> parses JSON header as JSON
// ~> parses form-like header as FormData, ...etc
var input = await utils.body<Message>(req);
} catch (err) {
return reply(400, 'Error parsing request body');
}
if (!input || !input.text.trim()) {
return reply(422, { text: 'required' });
}
const value: Message = {
id: utils.uid(16),
text: input.text.trim(),
// ...
};
// Assumes JSON (can override)
const key = `messages::${value.id}`;
const success = await write<Message>(context.bindings.DATA, key, value);
// ^ boolean
// Alias for `event.waitUntil`
// ~> queues background task (does NOT delay response)
context.waitUntil(
fetch('https://.../logs', {
method: 'POST',
headers: { 'content-type': 'application/json '},
body: JSON.stringify({ success, value })
})
);
if (success) return reply(201, value);
return reply(500, 'Error creating record');
});
// Init: Module Worker
export default start(API.run);
The main module – concerned with routing.
This is core of most applications. Exports the Router
class.
The worktop/cfw.kv
submodule contains all classes and utilities related to Workers KV.
The worktop/cache
submodule contains all utilities related to Cloudflare's Cache.
The worktop/cfw.durable
submodule includes native types for Cloudflare's Durable Objects as well as an Actor
abstract class that provides a blueprint for authoring a Durable Object that handles WebSocket connections.
Note: Durable Objects can only be used with the Module Worker format. You must integrate the
Router
with theworktop/modules
submodule.
The worktop/cfw
submodule includes two utilities related to Cloudflare's Module Worker format. Most notably, it includes TypeScript annotations specific to Cloudflare's environment.
The worktop/response
submodule contains the ServerResponse
class, which provides an interface similar to the IncomingMessage
(aka, "response") object that Node.js provides.
Note: This module is used internally and will (very likely) never be imported by your application.
The worktop/base64
submodule contains a few utilities related to the Base 64 encoding.
The worktop/cookie
submodule contains parse
and stringify
utilities for dealing with cookie header(s).
The worktop/cors
submodule offers utilities for dealing with Cross-Origin Resource Sharing (CORS) headers.
The worktop/crypto
submodule is a collection of cryptographic functionalities.
The worktop/utils
submodule is a collection of standalone, general-purpose utilities that you may find useful. These may include – but are not limited to – hashing functions and unique identifier generators.
The worktop/cfw.ws
submodule contains the WebSocket
class definition, as well as middleware handler for validating and/or setting up a SocketHandler
for the WebSocket connection.
MIT © Luke Edwards