juniper icon indicating copy to clipboard operation
juniper copied to clipboard

Converting between Contexts

Open axos88 opened this issue 10 months ago • 3 comments

Having a

  struct Context {
    a: u32,
    b: bool,
    c: String
  }

  struct SubContext1 {
    a: u32,
    b: bool
  }

  struct SubContext2 {
    a: u32,
    c: String
  }

How can the FromContext implementations be written? Seems like they take and return a reference, and there doesn't seem to be a way to satisfy the borrow checker.

Maybe FromContext should take, or have the ability to take a [clonable] context and produce an owned value?

axos88 avatar Jan 20 '25 21:01 axos88

Something like:

pub trait FromContext<'a, T> {
    fn from(v: &'a T) -> Self;
}

with a default implementation of

impl<'a, T> FromContext<'a, T> for &'a T {
    fn from(v: &'a T) -> Self {
        v
    }
}

perhaps?

axos88 avatar Jan 20 '25 21:01 axos88

Given this trait I believe the contexts should share the same lifetime.

Perhaps you could use a single context and encapsulate the sub-context's as required?

use juniper::FromContext;

struct Context {
    a: u32,
    b: bool,
    c: String,
}

struct SubContext1 {
    a: u32,
    b: bool,
}

struct SubContext2 {
    a: u32,
    c: String,
}

struct ContextManager {
    context: Context,
    sub_context1: SubContext1,
    sub_context2: SubContext2,
}

impl ContextManager {
    fn sub_context1(&self) -> &SubContext1 {
        &self.sub_context1
    }

    fn sub_context2(&self) -> &SubContext2 {
        &self.sub_context2
    }
}

impl<'a> FromContext<&'a ContextManager> for SubContext1 {
    fn from(manager: &&'a ContextManager) -> &'a Self {
        manager.sub_context1()
    }
}

impl<'a> FromContext<&'a ContextManager> for SubContext2 {
    fn from(manager: &&'a ContextManager) -> &'a Self {
        manager.sub_context2()
    }
}

antontroskie avatar Mar 10 '25 23:03 antontroskie

Well, yeah, this is a workaround, but you are duplicating all fields. Now in case the fields are not clone or copy....

axos88 avatar Mar 12 '25 19:03 axos88