Utilizing dual sets of typedefs within Apollo

Running a server with ApolloServer on my Node environment:

// App.js

const express = require('express');
const { ApolloServer } = require('apollo-server-express');
const resolvers = require('./resolvers.js');
const typeDefs = require('./schema');

const apolloServer = new ApolloServer({
  resolvers,
  typeDefs,
});

async function startServer() {
    await apolloServer.start();
    const app = express();
    apolloServer.applyMiddleware({ app });
    app.listen(4000, function () {
      console.log(`🚀 Server ready at http://localhost:4000${apolloServer.graphqlPath}`)
    });
}

startServer();

ApolloServer constructor requires typeDefs as an argument:

// schema.js

const { gql } = require('apollo-server-express');

const typeDefs = gql`
  type Query{
    hello: String
  }
`;

module.exports = typeDefs;

I also need to define the typeDefs in my front-end client for queries:

// MyComponent

import { useQuery } from '@apollo/client';
import { FC } from 'react';
import './MyComponent.css';
import typedefs from '../../server/typedefs'

interface MyComponentProps {}

const MyComponent: FC<MyComponentProps> = () => {
  const { data: hello, loading: isLoading } = useQuery(typedefs.Hello);

  if (isLoading) {
    return (
      <div>Loading...</div>
    )
  }

  return (
    <div className="MyComponent">
      data: {hello.hello}
     </div>
   )
}

export default MyComponent
// typeDefs.ts

import {gql} from '@apollo/client';

const Hello = gql`
  query {
    hello
  }
`;

const queries = { Hello };

export default queries;

The redundancy of defining the same typeDef in both the Apollo Server schema and client side leaves me unsure about how to optimize this setup.

Answer â„–1

One of my favorite tools is the codegen package, which you can learn more about in the official documentation.

If you're curious to see how it works, check out an example in my repository.

By using Codegen, you can easily fetch your schema via HTTP and generate types automatically, as demonstrated here. Make sure to follow the instructions provided in the documentation.

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

Experiencing issues while trying to render a component with dynamic content in Next.js

Currently, I am facing an issue while trying to display Leaflet maps in Next.js with Typescript. I came across the suggestion to disable server-side rendering (ssr) to prevent the 'window not defined' error. However, when implementing the followi ...

Bidirectional Data Binding with Angular 2 Services

Wondering about the connection between salary.service and player.component in Angular 2. If the salary variable is updated in the service, will it automatically reflect in the view of the player component? Initially, the player.component view displays a s ...

TypeScript function encountering issues with proper evaluation of set iteration

Whenever I attempt to run the code below, I consistently receive this console message: "undefined is not an object (evaluating 'this.courseAvailThisTerm')". Even though the courseAvailThisTerm() function functions properly in other scenarios. Any ...

Exploring the concept of nested arrays in Angular 2 using Typescript

I'm exploring the possibility of defining an array in Angular 2 that contains multiple other arrays within it. To clarify, here's what I had initially: export class PaymentDetails { account: any[]; bpNumber: number; } The issue with t ...

Text in Angular vanishes upon reopening

I have a code snippet where I am trying to allow the user to edit and save a paragraph displayed on a side panel of the main page. Although the code works fine, allowing users to update the text and see it reflected in the network upon saving, there seems ...

Exploring Observable Functionality in Angular 6

I've been grappling with understanding Angular Observables, but I've managed to get it working. My goal is to fetch data for my dynamic navigation bar. I successfully verified whether the user is logged in or not and displayed the Login or Logout ...

Invoke the ngOnInit method in Angular 7 or any other method within the component itself

My current dilemma involves a component named user-table-list, which essentially represents a table with entries corresponding to various users. Within this setup, there exists another component called table-list, responsible for defining the structure a ...

Angular 2: A guide to resetting dropdown and text values when changing radio button selections

When the user interface displays two radio buttons - one for YES and one for NO - and the user clicks on YES, a dropdown is shown. Conversely, if the user clicks on NO, a textbox is displayed. How can I clear the values in the dropdown and textbox when s ...

There was a build error in npm run due to the inability to destructure the 'store' property from 'useReduxContext2()' when it is null. Additionally, hooks cannot be conditional in Next Js

Next.js with Redux is the framework I am working on, aiming to host the application on Vercel. However, during the local app building process, I'm facing a particular error: The following error occurs - TypeError: Cannot destructure property 's ...

Retrieve the value of [routerLinkActive] in the component's class

Recently, I've been working on a tab component called TabComponent and it includes the following HTML template: <a [routerLink]='link' [routerLinkActive]="[is-active]">link label</a> <button>Close tab</button> The c ...

Using the appropriate asynchronous action in Redux with the Redux-Thunk middleware

While learning middleware redux-thunk, I created a simple React App. However, I am facing a transpilation issue due to an incorrect type of async action fetchPosts in the interface PostListProps. Below is the code snippet of the functional component where ...

Access an array to filter by specific key-value pairs

How can I efficiently filter an array using key and value pairs from within nested arrays? I am in need of a method to filter the elements of an array based on specific key-value pairs nested within another array. The key will always contain boolean value ...

An issue has occurred in Vue3 where the argument type 'typeof import("../dist/vue")' cannot be assigned to the parameter type 'PublicAPIComponent'

I recently installed Vue using the CLI version 4.4.1. Following that, I executed the command 'vue add vue-next' to update to Vue3. However, upon opening 'main.ts', I encountered a Typescript error: Argument of type 'typeof impor ...

Encountering errors with abstract keyword in TypeORM while implementing concrete table inheritance is a common issue

Looking for some guidance on class inheritance in TypeORM. Currently, I am trying to implement concrete table inheritance as outlined here: https://github.com/typeorm/typeorm/blob/master/docs/entity-inheritance.md#concrete-table-inheritance. However, I am ...

Sending information from service.ts to component

I'm encountering a roadblock with this issue, hopefully I can find some assistance here. Essentially, I am attempting to make a simple get http request in http.service and then pass the json object to the filter.service. From there, I aim to transfer ...

What is the process for adding various font weights in styled-components?

Hey there, I'm looking to incorporate different font weights of the Inter font (400, 500, 700) into my project. Currently, it's only loading the Inter regular font. I'm working with create-react-app, TypeScript, and styled-components. Here& ...

Issues encountered with async await functionality in TypeScript causing unexpected behavior

In my TypeScript code, I implemented a method to retrieve the collection names from a MongoDB database. public async getTables(): Promise<String[]> { let collectionNames = []; const connection = await mongoose.connect("mongodb://localhos ...

Raycast failing to detect objects that have been displaced from their original starting position

I am facing a challenge with using a raycast to locate objects under the mouse cursor. The issue arises when the objects are not positioned at (0, 0, 0) as they cannot be detected by the raycast. Once I move the object to any other position, it no longer r ...

Conditional validation in Typescript based on the nullability of a field

I have come across the following code snippet: type DomainFieldDefinition<T> = { required?: boolean } type DomainDefinition<F, M> = { fields?: { [K in keyof F]: DomainFieldDefinition<F[K]> }, methods?: { [K in keyof M]: M[K] & ...

Guide on transferring ElementHandle to a different webpage

My goal is to loop through an array of ElementHandles and insert them into a second Page using the following code: const htmlContent: string = ` <html><head></head><body> <div class="section">Section 1</div> ...