简体   繁体   中英

how to import schema and resolvers in graphql-yoga/node?

Since graphql-yoga V1 is no longer supported, I'd want to switch to graphql-yoga/node V2.

I've studied the official documentation on the website, but I'm having trouble migrating from V1 to V2.

Is a third-party package required?

here is a basic code:

const server = createServer({
  schema: `type Query {
    me: User!
    posts(query: String): [Post!]!
    users(query: String): [User!]!
    comments(query: String): [Comment!]!
  }`,
  resolvers:{
    Query: {
      posts(parent, args, ctx, info) {
        if (!args.query) {
          return posts;
        }
        return posts.filter((post) => {
          const isTitleMatch = post.title
            .toLowerCase()
            .includes(args.query.toLowerCase());
          const isBodyMatch = post.body
            .toLowerCase()
            .includes(args.query.toLowerCase());
          return isTitleMatch || isBodyMatch;
        });
      }
    }
  }
})

As you can see, I have resolvers and schema both are in single file named server.js

Could someone please assist me in this situation?

According to the docs it should be:

const server = createServer({
  schema: {
    typeDefs: `type Query {
      me: User!
      posts(query: String): [Post!]!
      users(query: String): [User!]!
      comments(query: String): [Comment!]!
    }`,
    resolvers: {
      Query: {
        posts(parent, args, ctx, info) {
          if (!args.query) {
            return posts;
          }
          return posts.filter((post) => {
            const isTitleMatch = post.title
              .toLowerCase()
              .includes(args.query.toLowerCase());
            const isBodyMatch = post.body
              .toLowerCase()
              .includes(args.query.toLowerCase());
            return isTitleMatch || isBodyMatch;
          });
        }
      }
    }
  }
})

anyway, here is an example for basic setup with typedefs and resolver in external files. note that it uses graphql-tools for uploading .graphql file for the schema, but you can easily use same method as resolvers for schema as .js file:

import { createServer } from '@graphql-yoga/node';
import { resolvers } from './resolvers.js';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { loadFiles } from '@graphql-tools/load-files';

const getSchema = async () =>
  makeExecutableSchema({
    typeDefs: await loadFiles('./*.graphql'),
    resolvers,
  });

async function main() {
  const schema = await getSchema();
  const server = createServer({ schema });
  await server.start();
}

main();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM