How to call mutation from one subgraph to another in Apollo federation gateway GraphQL

233 Views Asked by At

There is 2 subgraphs User and Posts, I want to create post and add newly created post Id to the user's posts array.

User and Post are different services with different databases.

createPost mutation is present in Post service and addUserPost is present in User service.

createPost mutation:

const Posts = require("../models/Posts");

const resolvers = {
  Mutation: {
    createPost: async (parent, args, context) => {

      const {input} = args;
      const newPost = await Posts.create({input})
      return newPost;
    }
  }
};
module.exports = { resolvers };

addUserPost mutation:

const User = require("../models/User");

const resolvers = {
  Mutation: {
    addUserPost : async (parent, args, context) => {

      const {newPostId} = args
      const {email} = context; 
      const updateUser = await User.findOneAndUpdate({email},{$push: {posts: newPostId}});
      return updateUser;
    }
  }
};
module.exports = { resolvers };

fedration gateway:

const { ApolloServer } = require ('apollo-server');
const { ApolloGateway, RemoteGraphQLDataSource  } = require ('@apollo/gateway');

class AuthenticatedDataSource extends RemoteGraphQLDataSource {
  willSendRequest({ request, context }) {
    const headers = context?.req?.headers || {};
    request.http.headers.set('Authorization', headers.authorization || '');
  }
}

const gateway = new ApolloGateway({
  serviceList: [
      { name: 'user', url: 'http://localhost:5000' },
      { name: 'post', url: 'http://localhost:4000' },
    ],
    buildService: ({ url }) => new AuthenticatedDataSource({ url }),
});

const server = new ApolloServer({ gateway, subscriptions: false,
  context: ({ req }) => ({
    req: req
  }), });

server.listen(8000, ()=>{
    console.log(`Gateway Server is running on port 8000`);
})
0

There are 0 best solutions below