Search code examples
typescriptexpressapolloapollo-servertypegraphql

ApolloServer schema option


I'm watching a youtube fullstack tutorial on react, graphQL, typeScript and on the apollo server part i try to pass buildSchema(function from type-graphql) in the schema option and get this error message

my code - im using typescript

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);
});

my error message

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.

Solution

  • The solution is add as Config<ExpressContext> after ApolloServer object parameter

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