The ApolloServer schema configuration

I recently started following a YouTube tutorial on fullstack development with React, GraphQL, TypeScript, and the Apollo Server. While working on the Apollo server part and trying to pass the buildSchema function from type-graphql in the schema option, I encountered an error message.

Here's my TypeScript code:

import { MikroORM } from "@mikro-orm/core";
import { __port__, __prod__ } from "./constants";
import { Post } from "./entity/Post";
import express from "express";
import { ApolloServer } from "apollo-server-express";
import { buildSchema, Query, Resolver } from "type-graphql";

@Resolver()
class HelloResolver {
  @Query(() => String)
  hello() {
    return "hi";
  }
}

const main = async () => {
  const orm = await MikroORM.init();
  await orm
    .getMigrator()
    .up()
    .catch((err) => {});
  const app = express();

  const apolloServer = new ApolloServer({ // line 24
    schema: await buildSchema({
      resolvers: [HelloResolver],
    }),
  });

  apolloServer.applyMiddleware({ app });

  app.listen(__port__, () => {
    console.log(`server started on localhost:${__port__}/graphql`);
  });
};

main().catch((err) => {
  console.log(err);
});

Now, here is the error message I received:

PATH/node_modules/ts-node/src/index.ts:307
        throw new TSError(formatDiagnostics(diagnosticList, cwd, ts, lineOffset))
              ^
TSError: ⨯ Unable to compile TypeScript
src/index.ts (24,41): Argument of type '{ schema: GraphQLSchema; }' is not assignable to parameter of type 'Config<ExpressContext>'.
  Type '{ schema: GraphQLSchema; }' is missing the following properties from type 'Config<ExpressContext>': formatError, debug, rootValue, validationRules, and 6 more. (2345)
    at getOutput (PATH/node_modules/ts-node/src/index.ts:307:15)
    at PATH/node_modules/ts-node/src/index.ts:336:16
    at Object.compile (PATH/node_modules/ts-node/src/index.ts:498:11)
    at Module.m._compile (PATH/node_modules/ts-node/src/index.ts:392:43)
    at Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Object.require.extensions.<computed> [as .ts] (PATH/node_modules/ts-node/src/index.ts:395:12)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
    at Object.<anonymous> (PATH/node_modules/ts-node/src/_bin.ts:182:12)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Answer №1

To resolve this issue, simply include as Config<ExpressContext> after the ApolloServer object parameter

const myApolloServer = new ApolloServer({
    schema: ...
  } as Config<ExpressContext>);

Answer №2

Encountering a similar problem, I discovered that the root cause was a nested repository structure. The ts-node and typescript dependencies were actually installed in a different location than where I was executing yarn start.

To resolve this issue, I uninstalled ts-node and typescript using npm uninstall ts-node typescript, then navigated to the top level of my project directory (where my start script was located) and reinstalled ts-node and typescript with

npm install -D ts-node typescript

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

No matter how hard I try, I can't seem to retrieve any data from the gremlin-server in my node/express application. The promise remains forever pending

As you continue reading, I have a question related to Node/Express or Gremlin - but I'm not sure which one is causing the issue. On my Linux machine as SU, I've initiated Janusgraph using the following command in Docker: docker run --name janusg ...

Adding a dynamic component to a directive in Angular 2.1

As a newcomer to Angular 2.1, I am looking to spruce up some elements for automatic translation using a custom directive. The syntax I have in mind is: <span customDirectiveTranslation="translateble">{{translateble}}</span> or simply <spa ...

Steps for Renewing Firebase Session Cookie

I am currently developing a web application utilizing Node.js/Express.js for the backend, with Firebase being used for user authentication. To manage user registration and other tasks, I rely on the Firebase Admin SDK. When a user attempts to log in, the ...

Modify the key within an array of objects that share a common key

I have an object structured as follows: NewObjName: Object { OLDCOLUMNNAME1: "NEWCOLUMN_NAME1", OLDCOLUMNNAME2: "NEWCOLUMN_NAME2", OLDCOLUMNNAME3: "NEWCOLUMN_NAME3"} Next, there is an array containing objects in this format: ...

I am looking to extract currency exchange rate data from an API and store it in an MSSQL database using Node.js. How can I

Is there anyone who has a similar example of fetching data from the website API and then saving it into an MSSql database, with a scheduled time of 10am? If so, I would greatly appreciate any guidance or assistance you can provide. Thank you in advance! ...

The function ValueChange remains uninvoked

Query: The issue is that valueChanges is only triggered for the entire form and not for specific controllers. Although this approach works, it returns the complete object. public ngOnInit(): void { this.form.createWagonBodyForm(); ...

Jest lingered on beyond the test completion by one second, without any involvement of Mongoose

I am currently working on a scenario where I am testing a route and verifying the response. While my tests are functioning as expected, I always encounter this particular message: Jest did not exit one second after the test run has completed. This usuall ...

Accessing global variables from within a function in Typescript

How can I successfully return a value from a function in TypeScript? When using pdf.create().tofile() function, it always returns undefined. Even when I try to make the variable global and explicitly return it, I run into issues with TypeScript. Can someon ...

Showcasing information from a database on an HTML page with the use of Node

I am currently attempting to fetch data from my database and display it on an HTML page in a table using EJS for rendering. I found inspiration for my code on this website: Although the database connection is successful, I am encountering difficulties wit ...

Leveraging asynchronous operations in Nodejs

As I delve into writing a validation script in Node, I've encountered an interesting scenario where error codes are accumulated in an `error` array upon failing certain validation checks. To add to the complexity, there's a function named `transl ...

What is the best way to deliver client/index.html using server/app.js?

Here is my current file structure: - simulated-selves - client - index.html - server - app.js The goal is to serve the user index.html when they visit the / route. // server/app.js app.get('/', function(req, res) { res.sendFile( ...

Displaying images dynamically in React from a source that is not public

There are 3 image options being imported, determined by the value in the state which dictates which of the 3 to display. import csv from '../../images/csv.svg'; import jpg from '../../images/jpg.svg'; import png from '../../images/ ...

A problem arises when the React effect hook fails to trigger while utilizing React Context

I have created a component that is supposed to generate different pages (one for each child) and display only the selected page: import * as React from "react"; export interface SwitchProps { pageId: number; children: React.ReactChild[]; } ...

The issue of ngModel not binding to the value of ion-select in Angular Ionic

Having an ion select outside of a form with an ngModel attribute bound to "selectedValue", I encounter an issue where my selections are not being properly populated in the selectedValue variable even though they appear in the ionChange method. The main pur ...

Tips for sending an Angular http post request including both data and an image:

When making a post request in Angular, I typically send data (such as 'product' data) using an object like this: product: any = {}; // filled with properties (code, barcode, name, description...) and then include it in the request: return this.h ...

Using NextJS's API routes to implement Spotify's authorization flow results in a CORS error

I am currently in the process of setting up the login flow within NextJS by referring to the guidelines provided in the Spotify SDK API Tutorial. This involves utilizing NextJS's api routes. To handle this, I've created two handlers: api/login.t ...

"Import data from a text file and store it as an array of objects using Types

I need assistance with converting the information in my text file into an array of objects. Below is a snippet of the data from the text file: DOCNO NETAMOUNT IREF1 IREF2 DOCDT 001 30000 50 100 6/7/2020 2 40000 40 90 6/7/2020 Currently, t ...

Cloudflare SSL Error 522 Express: Troubleshooting Tips for Res

After setting up my express project using express-generator, I decided to make it work with a cloudflare SSL Certificate for secure browsing over https. My express app is running on port 443. Despite my efforts, when I try to access the domain, I encount ...

Package.json encountered an error in the campus network when attempting to utilize a proxy for nodejs express

As a fullstack developer, I am currently working on a project that involves using reactjs and express. The express server is located in the server folder, while the reactjs client is in the server/client folder. In order to set up proper communication be ...

Obtaining the current row index in React MUI Data Grid using React-Context

Scenario In my application, I have implemented an MUI Data Grid with custom components in each row: RowSlider, RowDate, and RowLock using the MUI Components Slider, Date Picker, and Button respectively. View the Data Grid Visualization The Slider and Da ...