Skip to content

Instantly share code, notes, and snippets.

@lmaccherone
Created February 26, 2023 19:24
Show Gist options
  • Save lmaccherone/21d1ee2817f6a4b58fcf841c2e5ea5ec to your computer and use it in GitHub Desktop.
Save lmaccherone/21d1ee2817f6a4b58fcf841c2e5ea5ec to your computer and use it in GitHub Desktop.
export class TransactionalDOWrapperBase {
constructor(state, env) {
this.state = state
this.env = env
this.classInstance = null
}
async fetch(request) {
let response
try {
response = await this.state.storage.transaction(async (txn) => {
const alteredState = { ...this.state, storage: txn }
// TheClass is a static member of the subclass. It must be set there.
if (this.classInstance == null) this.classInstance = new this.constructor.TheClass(alteredState, this.env)
else this.classInstance.state = alteredState // Reset for each transaction. The DO must use this.state
return this.classInstance.fetch(request)
})
} catch (e) {
this.classInstance = null // Reset the instance so it will be rehydrated from storage on next request
throw e // Rethrowing to preserve the wrapped durable object's behavior.
}
return response
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment