Just brainstorming; nothing may actually come out of this!
I've been looking at the ServerRequest
and ServerResponse
interfaces a lot lately & wondering if they should even be here 🤔
Background
First, an overview of the PROs/CONs of everything, which lays out the reasoning for their existence:
ServerRequest
PROs
- the
ServerRequest<P>
TS interface makes for really nice DX as it can give confidence wrt req.params
contents
- the
req.body()
"smart helper" is nice for auto-detecting & auto-parsing the body
- ...nice to still have direct access to the
req.body.json()
(and other) methods, if needed
- it's nice that
new URL
is done once and its values are stored on the request
directly, so don't have to repeat
CONs
- See #52
- Only specific properties are forwarded from
Request
to ServerRequest
- Impossible to do
req.clone
as it no longer exists
- Cannot support
new Request(req.url, req)
out of the box (related #52)
- It's invented, which means it requires setup/buy-in in order to use some (but not all) utilities Worktop offers
ws.connect
doesn't have a preference
ws.listen
returns a handler than needs to be given a ServerRequest
because of the req.params
usage within it
- A
ServerRequest
must be created from a FetchEvent
in order for req.extend
to exist
- this is not ideal because Module Workers don't have
FetchEvent
s
Visually
Compared to Request
, these are the property differences:
url: string;
++ path: string;
method: Method;
++ origin: string;
++ hostname: string;
++ search: string;
++ query: URLSearchParams;
++ extend: FetchEvent['waitUntil'];
cf: IncomingCloudflareProperties;
headers: Headers;
++ params: P;
-- json(): Promise<any>;
-- formData(): Promise<FormData>;
-- arrayBuffer(): Promise<ArrayBuffer>;
-- blob(): Promise<Blob>;
-- text(): Promise<string>;
++ body: {
++ <T>(): Promise<T|void>;
++ json<T=any>(): Promise<T>;
++ arrayBuffer(): Promise<ArrayBuffer>;
++ formData(): Promise<FormData>;
++ text(): Promise<string>;
++ blob(): Promise<Blob>;
++ };
-- cache: RequestCache;
-- credentials: RequestCredentials;
-- destination: RequestDestination;
-- integrity: string;
-- keepalive: boolean;
-- mode: RequestMode;
-- redirect: RequestRedirect;
-- referrer: string;
-- referrerPolicy: ReferrerPolicy'
-- signal: AbortSignal;
-- clone(): Request;
ServerResponse
The main purpose of ServerResponse
was to surface a Node.js-like API for composing responses.
PROs
- Has
res.end
, res.setHeader
, res.writeHead
and a bunch of others
- Still able to do
new Response(res.body, res)
for ServerResponse
-> Response
transform
- Contents remain mutable for request lifecycle (desired) until
res.end
or res.send
is called
- Only relies on
req.method
for construction – used for HEAD
checks
- Provides
res.send
for automatic Content-*
headers and res.body
serialization
CONs
- Custom, requires manual construction and/or adjustment for type match
- Does not satisfy native
Response
type requirements
- AKA, can't pass a
ServerResponse
to an external library/helper if it wants a Response
value
- Even though
ServerResponse
is tiny, it's still extra code
Handler
The Handler
right now is strictly tied to the ServerRequest, ServerResponse
pair. It makes sense for this to always have some worktop-specific signature to it, but the question boils down to whether or not ServerRequest
and ServerResponse
are the right base units.
The signature now is this:
type Handler<P> = (req: ServerRequest<P>, res: ServerResponse) => Promisable<Response|void>;
...which satisfies all "middleware" and "final/route handler" requirements. Worktop loops through all route handlers until either:
- a
Response
or Promise<Response>
is returned directly
- the internal
res.send
or res.end
have been called, which marks the ServerResponse
as finished, and a Response
is created from the ServerResponse
contents
PROs
- Easily composable
- Satisfies middleware & final handler use cases
- Predictable & easily understood
- Allows mix/match of Promises
- No need for
next()
CONs
- Requires
ServerRequest
and ServerResponse
to be setup first
With the background out of the way, I have a few ideas of how these could be simplified and/or reworked to be compatible with libraries outside of worktop.
Important: All of these suggestions are breaking changes, which is not taken lightly.
If any of these are to happen, Worktop would have a strong division between old-vs-new through versioning – supporting the existing API and {new stuff} would not be considered.
Request Changes
1. Raw Request
and add $
object for all customizations
This drops ServerRequest
and instead uses Request
directly, adding a $
property that has an object with all worktop extras. This would be like how Cloudflare adds the cf
key with its own metadata.
interface RequestExtras<P extends Params> {
params: P;
path: string;
origin: string;
hostname: string;
search: string;
query: URLSearchParams;
body<T>(): Promise<T | void>;
extend: FetchEvent['waitUntil'];
}
interface Request<P extends Params = Params> {
$: RequestExtras<P>;
}
TypeScript Playground
Breaks:
req.params
-> req.$.params
req.path
-> req.$.path
req.*
-> req.$.*
req.body()
-> req.$.body()
req.body.json()
-> req.json()
(rely on native)
req.body.*()
-> req.*()
(rely on native)
req.extend()
-> req.$.extend()
Additionally, I see two potential issues with this:
- It converts the
Request
interface to a generic, which means code can throw/cause TS errors when used outside of worktop. In other words, if someone tries to do Request<MyParams>
outside of worktop, then that's gunna throw an error because Request
, natively, is not a generic. Not having the generic means that worktop loses its params
insights.
- Worktop can ensure
req.$
always exists, but if a user writes a middleware/handler to be used outside of worktop, then something like req.$.path
will throw a cannot access "path" of undefined
error
2. Raw Request
and use context
object for all customizations
This is the exact same thing as above, but it uses the context
key instead of $
for the object.
TypeScript Playground
3. Add all customizations directly to a Request
object
Uses the incoming Request
as is, but adds all the worktop customizations to it directly:
interface Request<P extends Params = Params> {
params: P;
path: string;
origin: string;
hostname: string;
search: string;
query: URLSearchParams;
extend: FetchEvent['waitUntil'];
}
TypeScript Playground
Breaks:
req.body()
-> removed – use external utility
req.body.json()
-> removed – use req.json()
req.body.*()
-> removed – use req.*()
Additionally, this shares the same potential gotchas as Options 1 & 2
- Worktop assumes/requires
Request
to be a generic; might cause issues externally
- Worktop provides the
req.params
object; any user middleware running outside of worktop might include req.params.foo
and req.params
is not defined
Request Changes: Poll
![](https://camo.githubusercontent.com/1959601f762783a4912f1d452b22f0c46b2a8b8bdfce950b36ee679066cda52d/68747470733a2f2f6170692e67682d706f6c6c732e636f6d2f706f6c6c2f30314645573931324e514d51453245443041334347444a314a482f4b6565702532302536305365727665725265717565737425363025323061732532306973)
![](https://camo.githubusercontent.com/36229224b8c36ac6593610c8637f7c1fd97db29313dd30f834c4b8d973c8b4a3/68747470733a2f2f6170692e67682d706f6c6c732e636f6d2f706f6c6c2f30314645573931324e514d51453245443041334347444a314a482f52617725323025363052657175657374253630253230776974682532302536302532342536302532306f626a656374253230666f72253230657874726173)
![](https://camo.githubusercontent.com/08ed102cef36033649adf07ba57e3015803be24fe4e6427b4d4aba6a770a24f9/68747470733a2f2f6170692e67682d706f6c6c732e636f6d2f706f6c6c2f30314645573931324e514d51453245443041334347444a314a482f5261772532302536305265717565737425363025323077697468253230253630636f6e746578742536302532306f626a656374253230666f72253230657874726173)
![](https://camo.githubusercontent.com/114a9e06e4a7bad9ad53876311cc56a4394b08bdaef90d6bd9bf499bc39d2cf2/68747470733a2f2f6170692e67682d706f6c6c732e636f6d2f706f6c6c2f30314645573931324e514d51453245443041334347444a314a482f526177253230253630526571756573742536302532307769746825323025363070617468253630253243253230253630706172616d7325324325323065746325323070726f7065727469657325323061646465642532306469726563746c79)
Response Changes
There's not much that can really change about ServerResponse
since it's all custom/worktop's to begin with... Really, there's only been on thing on my mind:
Move res.send
to external utility
If res.send
were exported as a top-level send
utility (either from worktop/response
or from worktop/utils
), then people could use it externally.
In order to accomodate this change, send
would have to return a Response
directly. Right now it mutates the ServerResponse
to signal the worktop.Router
that the Handler loop is complete. All of the serialization & statusCode
checks would happen within the send
utility itself. However, it would be up to the Router
to perform the HEAD
check. This would keep its API more or less comparable to @polka/send
.
Note: It's entirely possible to keep res.send
and add a send
export.
Response Changes: Poll
![](https://camo.githubusercontent.com/a8fa40c80ccf0fb2417be0f3cdb1f57d282e8f391921337e62d3567b3b3a4946/68747470733a2f2f6170692e67682d706f6c6c732e636f6d2f706f6c6c2f303146455739525835345850315850304a484d5247464344344e2f4b6565702532302532327265732e73656e6425323225323061732532306973)
![](https://camo.githubusercontent.com/600f639af6bd2fe0ded09ae065b87f5d3f28fc7d1a275f40562ed02f65b2d250/68747470733a2f2f6170692e67682d706f6c6c732e636f6d2f706f6c6c2f303146455739525835345850315850304a484d5247464344344e2f4d6f766525323025323273656e64253232253230746f2532302532327574696c732532322532306d6f64756c65)
![](https://camo.githubusercontent.com/08d2933b38a492aedc662e8f4f032c955cf5bd8d8f45c7aa09995ce471601420/68747470733a2f2f6170692e67682d706f6c6c732e636f6d2f706f6c6c2f303146455739525835345850315850304a484d5247464344344e2f4d6f766525323025323273656e64253232253230746f253230253232726573706f6e73652532322532306d6f64756c65)
Handler Changes
As mentioned before, the Handler
itself depends on decisions made to (Server)Request
and (Server)Response
. So any suggestions here will be made in addition to those, as this section is focusing on the Handler
function signature itself.
Important: For brevity, I'll use Promise<Response>
as a return type to refer to Promisable<Response | void>
1. Absolutely no changes
Keep the signature the same and use the exactly same ServerRequest
and ServerResponse
types:
type Handler<P> = (req: ServerRequest<P>, res: ServerResponse): Promise<Response>;
2. Keep the signature, but use Request
type
Maintain the (req, res)
parameters, but replace ServerRequest
with one of the suggestions above.
type Handler<P> = (req: Request<P>, res: ServerResponse): Promise<Response>;
3. Use Request+
and a Context
object
Note: Using Request+
to denote an overloaded/modified Request
type; see above.
Changes the signature so that a Request
is always used, leaving it up to Context
to store additional/extra information. Your Handlers
will be passing around the same Context object, which allows middleware/handlers (including Router.prepare
) to mutate the context
as needed.
For this Option 3 entry, the Context
object looks like this:
type Context = {
response: ServerResponse;
waitUntil: FetchEvent['waitUntil'];
}
type Handler<
P extends Params = Params,
C extends Context = Context,
> = (req: Request<P>, context: C) => Promise<Response>;
// ^ this means you can inject your own `Context` types
4. Use pure Request
and a Context
object
Similar to Option 3, but moves all would-be ServerRequest
extras into the Context
object. This means that the Request
is pure and has nothing added onto it (other than Cloudflare's cf
property)
type Context<P extends Params = Params> = {
// Request extras
params: P;
path: string;
origin: string;
hostname: string;
search: string;
query: URLSearchParams;
// the FetchEvent information
extend: FetchEvent['waitUntil']; // name TBD
waitUntil: FetchEvent['waitUntil']; // name TBD
passThroughOnException: FetchEvent['passThroughOnException']; // name TBD
// the ServerResponse
response: ServerResponse;
}
type Handler<
P extends Params = Params,
C extends Context = Context,
> = (req: Request, context: C<P>) => Promise<Response>;
// ^ this means you can inject your own `Context` types
5. Only receive a Context
parameter
Change the Handler
signature so that it's just receiving a single object with everything in it. It may look something like this:
interface Context<P extends Params = Params> {
// raw request
request: Request;
// the ServerResponse
response: ServerResponse;
// request extras
params: P;
path: string;
origin: string;
hostname: string;
search: string;
query: URLSearchParams;
// the FetchEvent information
extend: FetchEvent['waitUntil']; // name TBD
waitUntil: FetchEvent['waitUntil']; // name TBD
passThroughOnException: FetchEvent['passThroughOnException']; // name TBD
}
type Handler<
P extends Params = Params,
C extends Context = Context,
> = (context: C<P>) => Promise<Response>;
Handler Changes: Poll
![](https://camo.githubusercontent.com/47cac962bb85a85e0cd2170f09299613ee4783cd3f02b0e7d7fdadae932f4360/68747470733a2f2f6170692e67682d706f6c6c732e636f6d2f706f6c6c2f30314645574245334539425456504e575131344d4d56585346392f312e2532305a65726f2532304368616e676573)
![](https://camo.githubusercontent.com/978dc04ac5a6e25521ca92fbcead6213fffab9a4089b63d93b541bdff418fe40/68747470733a2f2f6170692e67682d706f6c6c732e636f6d2f706f6c6c2f30314645574245334539425456504e575131344d4d56585346392f322e2532305573652532307369676e61747572652533422532306275742532307769746825323052657175657374)
![](https://camo.githubusercontent.com/89e4ce17012eb5a5828a53fc291d7b282069a94329601103e93c0174fc1c9fae/68747470733a2f2f6170692e67682d706f6c6c732e636f6d2f706f6c6c2f30314645574245334539425456504e575131344d4d56585346392f332e2532305573652532305265717565737425324225323077697468253230436f6e746578742532306f626a656374)
![](https://camo.githubusercontent.com/672871cb6750dace01011fc5c85a936bcbcba3d064073b91480426361a9aa542/68747470733a2f2f6170692e67682d706f6c6c732e636f6d2f706f6c6c2f30314645574245334539425456504e575131344d4d56585346392f342e253230557365253230707572652532305265717565737425323077697468253230436f6e746578742532306f626a656374)
![](https://camo.githubusercontent.com/1afdba74226083087aa416ab8317fb003072cc7c8c9917a00bdc44cb48798d8c/68747470733a2f2f6170692e67682d706f6c6c732e636f6d2f706f6c6c2f30314645574245334539425456504e575131344d4d56585346392f352e2532305573652532306f6e6c7925323061253230436f6e746578742532306f626a656374)
Now, if you voted for something that involved a Context
object, should worktop auto-create a ServerResponse
for you?
All Context
-based answers assume that ServerRequest
is gone, shifting its properties either to the req
directly or to the Context
object. In this world, Worktop can continue providing a context.response
(name TBD) for you, or you can create it yourself as part of your Router.prepare
hook.
The purists among you may have despised the wannabe-Nodejs all this time, so this would be the opportunity to explicitly opt into ServerResponse
only when needed ... something like this:
import { Router } from 'worktop';
import { ServerResponse } from 'worktop/response';
import type { Context } from 'worktop';
interface MyContext extends Context {
response: ServerResponse;
}
const API = new Router<MyContext>();
API.prepare = function (req, context) {
// assumes no changes to ServerResponse API
context.response = new ServerResponse(req.method);
}
// or
API.prepare = function (context) {
// assumes no changes to ServerResponse API
context.response = new ServerResponse(context.request.method);
}
![](https://camo.githubusercontent.com/7c2cc5ed69aa90e2a9bf594dca8959e234a777a7a3fbb7c016ad6ed7bb30f26d/68747470733a2f2f6170692e67682d706f6c6c732e636f6d2f706f6c6c2f30314645574259435a514e445348484b595042303045375038362f4175746f2d636f6e737472756374253230253232536572766572526573706f6e7365253232253230666f722532306d65)
![](https://camo.githubusercontent.com/93a4ce593a1df48f85f7b9a263d3e739dd61ef4485abbdcc301e766e90ac1017/68747470733a2f2f6170692e67682d706f6c6c732e636f6d2f706f6c6c2f30314645574259435a514e445348484b595042303045375038362f446f2532304e4f542532306175746f2d636f6e737472756374253230253232536572766572526573706f6e7365253232253230666f722532306d65)
Thank you!
I know this a lot (too much) to read and sift through. If you managed to go through it – or even some of it – thank you so much. I really really appreciate the feedback.