Does Apollo Federation provide support for a code-first development approach?

I have declarations using 'code-first' approach in my project, but now I want to utilize them as microservices. How can I separate my 'typeDefs' and 'resolvers' following Apollo's 'schema-first' methodology? Is this even possible? I couldn't find any resources that discuss this specific scenario in the documentation for 'graphql-js' and 'apollo'. Any advice would be greatly appreciated.

The Apollo documentation mentions (accessible here):

const server = new ApolloServer({
  schema: buildSubgraphSchema([{ typeDefs, resolvers }])
});

It seems that 'buildSubgraphSchema()' does not accept schema as an argument.

Desired approach:

const server = new ApolloServer({
  // Moving away from schema-first style
  // schema : buildSubgraphSchema([{ typeDefs, resolvers }])
  // towards this:
  schema: buildSubgraphSchema([userSchema])
});

Take a look at the code :

userType.ts

const userType = new GraphQLObjectType({
  name: 'User',
  description: 'User Type Definition',
  fields: (): any => ({
    username: {
      type: new GraphQLNonNull(GraphQLString),
    },
    email: {
      type: GraphQLString,
    },
    phone: {
      type: GraphQLString,
    },
    firstName: {
      type: GraphQLString,
    },
    lastName: {
      type: GraphQLString,
    },
  }),
});

userQueries.ts

const userQueries = {
  users: {
    type: new GraphQLList(userType),
    description: 'Return users',
    resolve: () => {
      return getUsers();
    },
  },
};

query.ts

const query = new GraphQLObjectType({
  name: 'Query',
  description: 'Queries',
  fields: userQueries,
});

schema.ts

const userSchema = new GraphQLSchema({
  query,
  types: [userType],
});

server.ts

const server = new ApolloServer({ userSchema });
server.listen(4000).then(({ url }) => {
  console.log('Running a GraphQL API server at localhost:4000/graphql');
});

Answer №1

The solution to the specified problem can be found using the graphql and apollo-server packages.

To retrieve the typeDefs, you can utilize the gql and printSchema functions like this:

Note: Any undefined objects and variables should be referenced in the question.

import { gql } from 'apollo-server';
import { /* GraphQLSchema */ printSchema } from 'graphql';

const typeDefs = gql(
    printSchema(
      userSchema,
      // Or 
      //  new GraphQLSchema({
      //    query: queryType,
      //    mutation: mutationType,
      //  })
    )
);

const resolvers = {
  Query: userQueries,
  // Mutation: someMutationObject, if there is a mutation.
};

const server = new ApolloServer({
  schema: buildSubgraphSchema([{ typeDefs, resolvers }]),
});

Important: The schema created with buildSubgraphSchema() does not support subfield resolver. The exact term for this is unknown to me, but it works like this:

fullName: {
      type: GraphQLString,
      description: 'TESTSETSET',
      resolve: (
        parent: { firstName: any; lastName: any },
        args: any,
        context: any,
        info: any,
      ) => {
        console.log('This part won't work when using buildSubgraphSchema().');

        return parent.firstName + parent.lastName;
      },
    },

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for accessing the PR number in a Node.js GitHub Probot listening for the `pull_request` event

I've recently developed a GitHub probot application using nodejs and typescript. Currently, I have set up an event listener for the pull_request event. How can I extract the pr_number from the context object within the probot? The snippet below is fr ...

Dividing the text by its position value and adding it to a fresh object

I needed to divide the paragraph into sections based on its entityRanges. Here is what the original paragraph looks like: { type: 'paragraph', depth: 1, text: 'Do you have questions or comments and do you wish to contact ABC? P ...

Having trouble importing the Renderer2 component in Angular

Trying to include Renderer2 with the following import: import { Renderer2 } from '@angular/core'; Encountering an error: "Module 'project/node_modules/@angular/core/index' does not have an exported member 'Renderer2'. Puzz ...

Generate dynamic forms utilizing JSON data

I am in the process of developing an application that enables users to answer questions about themselves. The questions are being retrieved from an API. My next step is to generate a form with these questions as entry fields. I am currently utilizing a met ...

Angular - Loading images on the fly

After scouring numerous resources, I couldn't find a resolution to my issue. For your information, I am utilizing ASP.net Core 2.0's default angular project In the process of developing an Angular application, I am faced with the challenge of ...

Accessing the return value from an Angular subscription and storing it in

How can I use the value from a subscription to set the property for returning date and time? Component ngOnInit() { this.resetForm(); let defaultWIPEndTime = this.service.getDefaultWIPEndTime().subscribe(res => {}); console.log(defaultW ...

Angular 6: Issue TS2339 - The attribute 'value' is not recognized on the 'HTMLElement' type

I have a textarea on my website that allows users to submit comments. I want to automatically capture the date and time when the comment is submitted, and then save it in a JSON format along with the added comment: After a comment is submitted, I would li ...

Writing a CSV file to AWS S3 proves to be unsuccessful

I have been working with TypeScript code that successfully writes a CSV file to AWS S3 when running locally. However, I have recently encountered an error message: s3 upload error unsupported body payload object NOTES: The code is not passing creden ...

There seems to be an issue with AppModule in your code. The error message states that it is not recognized as an NgModule and the problem

After upgrading to node 6, angular 4, typescript 2.3.2, and @angular/cli 1.02, I meticulously followed the steps outlined in the Guide for updating @angular/cli. I will include my entire package.json below in case there are any relevant details. The specif ...

Using Material UI date picker with TypeScript: A Complete Guide

Well, I have to admit that I usually don't resort to putting 'any' as the type when I'm uncertain what to do, but right now, I'm starting to feel quite frustrated. I'm currently working with Material UI date picker in conjunct ...

Netlify failing to build CRA due to inability to locate local module for method?

I encountered an issue with deploying my site on Netlify. The problem arises when it fails to locate local modules. Below is the log: 12:54:43 AM: Build ready to start 12:54:45 AM: build-image version: 09c2cdcdf242cf2f57c9ee0fcad9d298fad9ad41 12:54:45 AM: ...

Error in TypeScript in VSCode when using the React.forwardRef function in a functional component

We are developing our component library using JavaScript instead of TypeScript. In our project's jsconfig.json file, we have set checkJs: true. All components in our library are functional and not based on class components. Whenever a component needs ...

Invalidity of types occurs when dispatching data to redux

My reducer code is as follows: import { profileAPI } from '../api/api' import shortid from 'shortid' const ADD_POST = 'profile/ADD-POST' const SET_USER_PROFILE = 'profile/SET_USER_PROFILE' const SET_STATUS = 'p ...

A single click is required for Observables to load on an HTML page

While working on my Angular web application, I encountered an issue with displaying data when using Observables and Subjects. Typically, when searching the Firebase DB, I use *ngFor="let myvar of _myvar | async" in my HTML to display the retrieve ...

Tips for effectively invoking an API within a Next.js application

I've been exploring the most effective method for calling an external API within a Next.js application recently. Given my experience in developing MERN stack applications, I typically rely on axios for handling API requests and utilize it within a use ...

The firebase-admin module encounters compatibility issues with middleware due to the OS Module

I'm facing a major issue with my API implementation. I am working on integrating an authentication and verification middleware, but the problem arises when using firebase-admin due to its dependencies on Edge Runtime modules that are incompatible with ...

How do I import NPM modules in Angular 5 without using @types?

Currently experimenting with Angular 5 and beginning a project from angular-cli. I am interested in incorporating a NPM module called J2M (https://github.com/kylefarris/J2M). During my research, I came across these two commands: npm install j2m --save npm ...

The optimal location to declare a constructor in Typescript

When it comes to adding properties in an Angular component, the placement of these properties in relation to the constructor function can be a topic of discussion. Is it best to declare them before or after the constructor? Which method is better - Method ...

Styling <Link> component with styled-components: A step-by-step guide

Utilizing the Link component from @material-ui/core/Link in my TypeScript code was initially successful: <Link href="#" variant="body2"> Forgot? </Link> However, I am exploring the transition to styled-components located in a separate file. ...

When using Angular forms, the password or username may be duplicated if entered twice when pressing the

I am currently working on a basic username and password form using Angular. Here's the template I have: <label class="welcome-content">Username:</label> <input #userName type="text" id="txtLoginUsername" (keyup.enter)="loginUser(userNa ...