Created
February 26, 2023 19:24
-
-
Save lmaccherone/21d1ee2817f6a4b58fcf841c2e5ea5ec to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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