How to get the name of a durable object
I'm creating durable objects via
this.env.SWARM.get(this.env.SWARM.idFromName(HEX_STRING))
But when i call this.ctx.id.name
inside the object it is undefined.
Is there a way to get name -- or associate other state with the object during its construction/instantiation?7 Replies
Inside the object constructor, you get two parameters,
state
and env
. The first one (state) has an id
parameter that you can use - see the types here: https://workers-types.pages.dev/#DurableObjectStateIIRC
id.name
is only defined if you created said id
instance with idFromName()
, so the id
instance within the DO will not have a way to access its own nameoh yeah, if you didn't give it a name, it won't automatically assign one - but you can use
id.toString()
to always get a hex idI meant too that even if the original ID was created with a name, the name will only exist on that instance of the id, so within the DO it will still be undefined
ah, that's kinda sad
thanks @HardlyWorkin' and @Purple Blob | Green -- that all makes sense and -- yes that's what i've observed. so is there another way to attach data to the object when it's created/references. e.g., the name i'm using to create the id is my external key -- and i'd like for the object to know that. of course i can set an RPC method to set that, but i was wondering if there's a way to get that into the constructoror so that it's immutable?
I don't think you can influence the constructor directly in such a way :/. You could either provide it in all requests as you mentioned, or store it in transactional storage after the first request - which could get expensive