Skip to content

[Feature] Make accessing Durable Object name more ergonomic #760

@lukevalenta

Description

@lukevalenta

Is there an existing issue for this?

  • I have searched the existing issues

Description

Durable Object IDs created with https://developers.cloudflare.com/durable-objects/api/namespace/#idfromname have a name property, which can be useful to be able to access within the Durable Object's new() function, for example for logging or to retrieve a specific configuration based on the name (e.g., https://github.com/cloudflare/azul/blob/56720294b68225bce8fba0273178639080fcba8f/crates/ct_worker/src/sequencer_do.rs#L24).

This can be done using a function like this:

/// Retrieve the
/// [name](https://developers.cloudflare.com/durable-objects/api/id/#name) that
/// was used to create a Durable Object Id with `id_from_name`. The signature of
/// this function is a little funny since the only way to access the `State`'s
/// inner `DurableObjectState` is via the `_inner()` method which takes
/// ownership of the state. Thus, we just re-derive the State from the inner
/// state and return it in case the calling function still needs it.
///
/// # Errors
///
/// Returns an error if the 'name' property is not present, for example if the
/// object was created with a random ID.
pub fn get_durable_object_name(state: State) -> Result<(State, String)> {
    let inner_state = state._inner();
    let id = inner_state.id()?;
    let obj = js_sys::Object::from(id);
    let name = js_sys::Reflect::get(&obj, &"name".into())?
        .as_string()
        .unwrap_or_default();
    Ok((State::from(inner_state), name))
}

The ask in this ticket is to either make this more ergonomic (e.g., add a fn name(&self) -> Option<String> method to the State struct, or just to document the above. Happy to file a PR if this seems useful to others.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions