简体   繁体   中英

GraphQL doesn't allow querying on different fields

I'm an absolute beginner in GraphQL. So apologies if the question is amateur. I'm writing this graphQL end point where it will filter person by name. Works good, but I want to be able to

filter by multiple parameters like name, age, phone number

or

use a combination of the parameters to search..

My current program:

var express = require("express");
var express_graphql = require("express-graphql");
var { buildSchema } = require("graphql");
var Sequelize = require("sequelize")
var db = new Sequelize(
  "users",
  "root",
  "pass",
  {
    host: "localhost",
    dialect: "mysql"
  }
);

var calls = db.define(
  "calls",
  {
    person_id: {
      type: Sequelize.INTEGER,
      allowNull: false,
      primaryKey: true
    },
    name: {
      type: Sequelize.STRING,
      allowNull: false
    },
    age: {
      type: Sequelize.INTEGER,
      allowNull: false
    },
    address: {
      type: Sequelize.STRING,
      allowNull: false
    },
    company: {
      type: Sequelize.String,
      allowNull: false
    },
    email: {
      type: Sequelize.STRING,
      allowNull: false
    }
  },
  {
    tableName: "person"
  }
);

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type Query {
    Person(person_id: Integer!): [Person]
  }
  type Person {
    person_id: Integer
    name: String
    age: Integer
    address: String
    company: String
    email: String 
  }
`);

var getperson = function(args) {
  if (args.person_id) {
    var p_name = args.person_id;
    return calls.findAll({
      where: {
        name: p_name
      }
    });
  }
};

// The root provides a resolver function for each API endpoint
var root = {
  person: getperson
};

var app = express();
app.use(
  "/graphql",
  express_graphql({
    schema: schema,
    rootValue: root,
    graphiql: true
  })
);
app.listen(4000);
console.log("Running a GraphQL API server at http://localhost:4000/graphql");

Tried doing this:

 type Query {
    Person(person_id: Integer!): [Person]
    Person(name: String!): [Person]
  }

But it says Person can be defined only once.

You cannot "overload" a field definition. You can either define a single field with nullable arguments

person(personId: Int, name: String)

or create differently named fields

personById(id: Int!)
personByName(name: String!)

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