juniper
juniper copied to clipboard
Converting between Contexts
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?
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?
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()
}
}
Well, yeah, this is a workaround, but you are duplicating all fields. Now in case the fields are not clone or copy....