Apollo Client Field Resolution
See original GitHub issueI am using Apollo Client 2.5 with local state and trying to return a class from the resolvers but it appears that Apollo Client doesn’t resolve the returned fields if they are methods/functions. I’ve demonstrated below what I’m talking about.
This same schema and resolver setup works fine in Apollo Server and I’m curious if this will be supported in Apollo Client local state? Or maybe it does work and there is something I’m doing wrong with the setup?
Here is a link to the same code in a Codesandbox https://codesandbox.io/s/n4rom4jkpp
This code should output {"user":{"name":"Tyler","nameLength":5,"__typename":"User"}}
But instead it is outputing: {"user":{"name":"Tyler","__typename":"User"}}
You’ll see it is missing the nameLength field as that field is a method on the User class and not a static value.
import React from "react";
import ReactDOM from "react-dom";
import { ApolloClient } from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import { ApolloProvider, Query } from "react-apollo";
import gql from "graphql-tag";
function App() {
const GET_USER = gql`
query getUser {
user @client {
name
nameLength
}
}
`;
const render = ({ loading, error, data }) => {
if (loading) return <h4>Loading...</h4>;
if (error) return <h4>Error...</h4>;
return <div className="App">{JSON.stringify(data)}</div>;
};
return <Query query={GET_USER}>{render}</Query>;
}
class User {
constructor({ name }) {
this.__typename = "User";
this.name = name;
}
nameLength() {
return this.name.length;
}
}
const client = new ApolloClient({
cache: new InMemoryCache(),
resolvers: {
Query: {
user: () => new User({ name: "Tyler" })
}
},
typeDefs: gql`
type Query {
user: User
}
type User {
name: String
nameLength: Int
}
`
});
ReactDOM.render(
<ApolloProvider client={client}>
<App />
</ApolloProvider>,
document.getElementById("root")
);
Issue Analytics
- State:
- Created 5 years ago
- Comments:5 (3 by maintainers)
Top GitHub Comments
Hey, benjamn thanks for the replies. I think I already ended up doing what you suggested in your last paragraph:
You can try my original code with
nameLength
as a getter but that breaks it even more.This is no longer an issue for me, but I guess my original point was it’s strange that my class resolver methods work in apollo-server but not with Apollo Local State. If that provides any value for you or the team then great if not then feel free to close the issue.
Sounds like this was resolved - closing, thanks!