Schema Stitching in Apollo GraphQL doesn't resolve types from other parts - graphql

I'm trying to make my GraphQL schema composable through schema stitching, but I'm struggling with how to resolve properties of types from a different part.
Here's the schema before decomposing:
type Referee {
id: ID!
stringProp: String!
}
type Referer {
id: ID!
pointer: Referee!
}
type Query {
referers: [Referer]
}
The types both have resolvers, in their respective schemas, that expand object { id } into { id, stringProp } or { id, pointer: { id } }, so that a query
query FromSingleSchema {
referers: {
id
pointer {
id
stringProp
}
}
}
resolves as expected; Query.referers resolves to a list of [{id}] objects, and each of those in turn resolve first into a Referer and then fetches the pointed-to Referee through type resolvers.
Now, I try to decompose the schema:
// schema A
type Referee {
id: ID!
stringProp: String!
}
// schema B
type Referer {
id: ID!
}
type Query {
referers: [Referer]
}
// schema Extensions
extend type Referer {
pointer: Referee!
}
and compose it again:
// both schemaA and schemaB have been created with makeExecutableSchema
import schemaA from './A'
import schemaB from './B'
// schemaExtensions is just a raw GraphQL string
// resolverExtensions is shown below
import { schemaExtensions, resolverExtensions } from './B'
const schema = mergeSchemas({
schemas: [schemaA, schemaB, schemaExtensions],
resolvers: Object.assign({}, resolverExtensions)
})
// resolverExtensions defined as follows:
{
Referer: {
pointer: {
fragment: 'fragment IdFragment on Referee { id }',
resolve: o => ({ id: o.pointerId })
}
}
}
With this, I can run this query without problems:
query OnlyIdFromDecomposedSchemas {
referers: {
id
pointer {
id
}
}
}
but this fails
query FullRefereeFromDecomposedSchemas {
referers: {
id
pointer {
id
stringProp
}
}
}
with the error message
Cannot return null for non-nullable field Referee.stringProp.
What do I need to do for the type resolver for Referee to be able to fill in the rest of the properties once { id } is available, like it does in a single, non-decomposed, schema?

I think you are looking for schema delegation. Schema Delegation is a way to automatically forward a query (or a part of a query) from a parent schema to another schema (called a subschema) that is able to execute the query.
You can use delegateToSchema method like this in your resolver:
{
Referer: {
pointer : {
resolve(parent, args, context, info) {
return info.mergeInfo.delegateToSchema({
schema: schemaA,
operation: 'query',
fieldName: 'referee', // modify according to your query for referee
context,
info,
});
}
}
}
}

Related

Apollo + GraphQL: Fragment on interface works for one concrete type but not on the other

I have an interface CommonUser with PublicUser and User that implements CommonUser.
I have two endpoints: one for PublicUser and one for User:
interface CommonUser {
id
...
}
type User implements CommonUser {
id
...
}
type PublicUser implements CommonUser {
id
...
}
extend type Query {
publicUser(id: ID!): PublicUser
}
extend type Mutation {
fetchCreateUser(id: ID!): User!
}
On the front end, I want to use a fragment to share common fields,
const COMMON_FIELDS = gql`
fragment CommonUserFields on CommonUser {
id
...
}
`
const FETCH_CREATE_USER = gql`
${COMMON_FIELDS}
mutation fetchCreateUser {
fetchCreateUser(id: 123) {
...CommonUserFields
...
}
}
`
const PUBLIC_USER = gql`
${COMMON_FIELDS}
query publicUser {
publicUser(id: 123) {
...CommonUserFields
someOtherField
}
}
`
When I use the FETCH_CREATE_USER mutation, it works as intended, returning all the common user fields.
However, when I use the PUBLIC_USER query, it only returns someOtherField in the response.
I have verified on the backend resolver that graphQLFields(info) does contain all the requested fields, and the object being returned contains all requested fields.

Apollo Graphql: Rename schema for backward compatibility

What I want do ?
In Apollo Graphl server, I want to change an entity Person to Human in schema but i don't want to break my clients (frontend that are querying graphql). So if client is making query for Person i want to map it to Human.
Example:
CLIENT QUERY
query {
Person {
ID
firstName
}
}
REWRITE TO
query {
Human {
ID
name
}
}
REWRITE THE RESPONSE
{
data: {
Person: {
Id: 123,
name:"abc"
}
}
}
Things that I have tried
graphql-rewriter provides something similar to what i am looking for. I went through it documentation but it doesn't have the option to rewrite the field name.
In apollo graphql documentation Apollow graphql directives, They have mentioned about rename directive but i did not find rename-directive-package the node module.
apollo-directives-package I have tried this as well but it doesn't have the option to rename the scaler field e.g
import { makeExecutableSchema } from "graphql-tools";
import { RenameDirective } from "rename-directive-package";
const typeDefs = `
type Person #rename(to: "Human") {
name: String!
currentDateMinusDateOfBirth: Int #rename(to: "age")
}`;
const schema = makeExecutableSchema({
typeDefs,
schemaDirectives: {
rename: RenameDirective
}
});
Any suggestions/help would be appreciated.
Here i hope this gives helps you, first we have to create the schema-directive
import { SchemaDirectiveVisitor } from "graphql-tools";
import { GraphQLObjectType, defaultFieldResolver } from "graphql";
/**
*
*/
export class RenameSchemaDirective extends SchemaDirectiveVisitor {
/**
*
* #param {GraphQLObjectType} obj
*/
visitObject(obj) {
const { resolve = defaultFieldResolver } = obj;
obj.name = this.args.to;
console.log(obj);
}
}
type-defs.js
directive #rename(to: String!) on OBJ
type AuthorizedUser #rename(to: "Human1") {
id: ID!
token: ID!
fullName: String!
roles: [Role!]!
}

Nested query and mutation in type-Graphql

I found a feature in graphql to write nested query and mutation, I tried it but got null. I found the best practices of building graphqL schema on Meetup HolyJs and the speaker told that one of the best ways is building "Namespaced" mutations/queries nested, in this way you can write some middlewares inside the "Namespaced" mutations/queries and for get the Child mutation you should return an empty array because if you return an empty array, Graphql understand it and go one level deep.
Please check the example code.
Example in graphql-tools
const typeDefs = gql`
type Query { ...}
type Post { ... }
type Mutation {
likePost(id: Int!): LikePostPayload
}
type LikePostPayload {
recordId: Int
record: Post
# ✨✨✨ magic – add 'query' field with 'Query' root-type
query: Query!
}
`;
const resolvers = {
Mutation: {
likePost: async (_, { id }, context) => {
const post = await context.DB.Post.find(id);
post.like();
return {
record: post,
recordId: post.id,
query: {}, // ✨✨✨ magic - just return empty Object
};
},
}
};
This is my Code
types
import { ObjectType, Field } from "type-graphql";
import { MeTypes } from "../User/Me/Me.types";
#ObjectType()
export class MeNameSpaceTypes {
#Field()
hello: string;
#Field({ nullable: true })
meCheck: MeTypes;
}
import { Resolver, Query } from "type-graphql";
import { MeNameSpaceTypes } from "./MeNamespace.types";
#Resolver()
export class MeResolver {
#Query(() => MeNameSpaceTypes)
async Me() {
const response = {
hello: "world",
meCheck:{}
};
return response;
}
}
Result of code
query {
Me{
hello
meCheck{
meHello
}
}
}
--RESULT--
{
"data": {
"Me": {
"hello": "world",
"meCheck": {
"meHello": null
}
}
}
}
I got a null instead a meHello resolver. Where am I wrong?
Namespaced mutations are against GraphQL spec as they are not guarranted to run sequentially - more info in this discussion in GitHub issue related to your problem:
https://github.com/MichalLytek/type-graphql/issues/64

Running a graphql query from inside a resolver - for nested data

I am implementing an apollo server graphql schema. All my schema definition are modules in .graphql files. All my resolvers are modules in .js files.
I have the following type :
productSchema.graphql
type Product {
_id: Int
company: Company
productSellingPrice: [PriceHistoryLog]
productName: String
category: String
productDetails: [ProductDetail]
globalId: Int
isActive: Boolean
}
extend type Query {
ProductList: [Product]
}
productDetailSchema.graphql
type ProductDetail {
_id: Int
company: Company
root: Product
catalogItem: CatalogItem
product: Product
isPerishable: Boolean
quantity: Float
isActive: Boolean
}
extend type Query {
ProductDetailsList(productId: Int!): [ProductDetail]
}
What I want to do is, when querying for ProductList, to run a ProductDetailsList query and resolve the field in product from there.
As you can see ProductDetail also have nested fields so I can't just query the DB for that field in the Product resolver.
Any ideas? I am kind of lost.
Edit:
this is my resolver code:
Product: {
company: product => product.companyId,
category: async product => {
try {
let res = await SaleModel.findOne({ productName:
product.productName }) ;
return res.productCategory;
} catch (err) {
console.log(err);
return "Mo Category found";
}
}
},
Query: {
async ProductList(obj, args, { companyId }) {
return await ProductModel.find({
companyId,
isActive: true
}).populate("companyId");
}
},

Write resolvers for nested type definitions

Suppose I have following type definition for my GraphQL API:
const typeDef = `
type Book {
title: String
author: Author
likes: Int
}
type Author {
id: String
name: String
age: Int
books: [Book]
}
type Query{
books(authorid: String!): Book
}
`
Then, how many resolvers do I need for this? Should I handle this query request with only one resolver books and return all books and author info or should I make many resolvers such as Query -> books, Book -> author and Author -> books? I am not sure how the modular schema and resolver works together.
No matter how many type(Book, Author etc) or input you use you need to provide .
const schema = `
type Mutation {
mutatePost(postId:Int) :Int
}
type Query {
hello: String
posts: [String]
books(authorId: String!): Book
}
`
You need to use same name as you defined in Query must be same in resolver
const resolvers = {
Query: {
async hello() {
return 'Hello';
},
async posts() {
return ['Hello', 'World];
},
async books(_, { authorId }) {
//Return data which you is defined in type Book
//return Book
}
},
Mutation: {
async mutatePost(_, {
postId
}, context) {
//return Integer
}
},
}
Only thing every Query and Mutation need queryResolver and mutationResolver

Resources