Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Converting between Contexts #1308

Open
axos88 opened this issue Jan 20, 2025 · 3 comments
Open

Converting between Contexts #1308

axos88 opened this issue Jan 20, 2025 · 3 comments

Comments

@axos88
Copy link

axos88 commented Jan 20, 2025

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
Copy link
Author

axos88 commented Jan 20, 2025

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?

@antontroskie
Copy link

antontroskie commented Mar 10, 2025

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()
    }
}

@axos88
Copy link
Author

axos88 commented Mar 12, 2025

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants