cloudflare / cloudflare/workerd

Support class exports with constructors for stateless workers

Open
#121 2 comments 3 reactions 0 assignees View on GitHub
feature proposal
Dominant language
C++
Stars
8.7k
Forks
739
Avg merge
2d 20h
Merged PRs (30d)
174

Description

Durable Objects let me do this
```js
export class Worker {
constructor(state, env) {
// hell yea constructors
this.state = state
this.env = env
}

async fetch(req) {
return new Response(`Hello world`)
}
}
```
and that's cool. It's especially helpful with SubtleCrypto since a lot of the API uses promises for some reason. I can then call SubtleCrypto APIs _once_ on Worker construction to make keys and store them in the class using a call to `state.blockConcurrencyWhile`.
```js
this.state.blockConcurrencyWhile((async () {
this.key = crypto.subtle.importKey(
'raw',
this.env.keyData,
{ name: 'HMAC', hash: 'SHA-256' },
false,
['verify']
);
})());
```
But what if _stateless workers_ could do this?
```js
export default class {
constructor(ctx, env) {
// hell yea constructors
this.ctx = ctx
this.env = env
this.ctx.blockConcurrencyWhile((async () {
this.key = crypto.subtle.importKey(
'raw',
this.env.keyData,
{ name: 'HMAC', hash: 'SHA-256' },
false,
['verify']
);
})());
}

async fetch(req) {
return new Response(`Hello world`)
}
}
```
This way users can do things like SubtleCrypto key imports once instead of every request in a way that makes more _obvious sense_ (the fact that the env object is reused and your modifications persist across requests is _not obvious_ or _pure_).

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.