试图在Graphiql上做Graphql变异

时间:2018-02-23 17:22:47

标签: express mongoose schema graphql graphiql

所以我试图在graphiql上执行一个变异,但一直收到这个错误: enter image description here

这是我的设置:

架构:



import { GraphQLInt, GraphQLString, GraphQLList, GraphQLObjectType, GraphQLNonNull, GraphQLSchema, } from 'graphql';
import * as _ from 'lodash';

import mongoose from 'mongoose';
import messageModel from './models/messages';
import userModel from './models/users';
import groupModel from './models/groups';


export const Schema =[`
scalar Date

type  Group {
  id: String!,
  name: String,
  created_at:Date!,
  users: [User],
  messages: [Message]
}

type User {
  id: String!,
  username: String!,
  email: String!,
  password: String!,
  location: String!,
  groups: [Group],
  friends: [User]
}

type Message {
  id: String!,
  to: Group!,
  from: User!,
  message: String!,
  date: Date!
}

type Query {
  user(email: String, id: Int): User
  messages(groupId: Int, userId: Int): [Message]
  group(id: Int!): Group
}

type Mutation {
  createMessage(groupId: String!, userId: String!, text: String!): Message
  createUser(username: String!, email: String! password: String!, location:String!): User
}

schema {
  query:Query
  mutation: Mutation
}
`]

export default Schema;




用户的Mongoose架构和模型:



import mongoose from 'mongoose';
const Schema = mongoose.Schema;

const userSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    location: {
        type: String,
        required: true,
    },
    groups: [{
        type: Schema.Types.ObjectId, ref: 'group'
    }],

    friends: [{
        type: Schema.Types.ObjectId, ref: 'user'
    }]
});

let userModel = mongoose.model('user', userSchema);
export default userModel;




这是解析器:



import GraphQLDate from 'graphql-date';
import groupModel from './models/groups';
import messageModel from './models/messages';
import userModel from './models/users';

export const Resolvers = {
    Date: GraphQLDate,
    Query: {
        group(_, args) {
            return groupModel.find({ $where: args }).exec((err, groups) => {
                return groups;
            })
        },
        messages(_, args) {
            return messageModel.find()
        },
        user(_, args) {
            return userModel.findOne()
        },
    },
    Mutation: {
        createMessage(_, { text, userId, groupId }) {
            return messageModel.create({
              from:userId,
              message:text,
              to:groupId,
            });
          },
          createUser(_, { username, email, password, location}) {
            return messageModel.create({
                username:username,
                email: email,
                password: password,
                location: location
            });
          },
    },
    Group: {
        users(group) {
            return group.getUsers();
        },
        messages(group) {
            return messagemodel.findAll({
                where: { groupId: group.id },
                order: [['createdAt', 'DESC']],
            });
        },
    },
    Message: {
        to(message) {
            // return messageModel.find({id:message.id}).populate('to').exec((err,message) => {
            //     return message.to;
            // })
            return messageModel.findOne({ '_id': message.id }).populate('to').exec((err, message) => {
                if (err) return err;
                return message
            })
        },
        from(message) {
            return message.getUser();
        },
    },
    User: {
        groups(user) {
            return user.getGroups();
        },
        friends(user) {
            return user.getFriends();
        },
    },
};
export default Resolvers;




这是我对server.js的设置:



if (!process.env.NODE_ENV) process.env.NODE_ENV = "dev";
import express from 'express';

import { graphqlExpress, graphiqlExpress } from 'graphql-server-express';
import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools';
import bodyParser from 'body-parser';
import { createServer } from 'http';

import Schema from './src/schema';
import Resolvers from './src/resolvers';

import mongoose from 'mongoose';

import config from './config';
var db = process.env.DB || config.DB[process.env.NODE_ENV];
var PORT = config.PORT[process.env.NODE_ENV];
const app = express();

mongoose.connect(db, function (err) {
  if (!err) {
    console.log(`connected to the Database: ${db}`);
  } else {
    console.log(`error connecting to the Database ${err}`);
  }
});

const executableSchema = makeExecutableSchema({
  typeDefs: Schema,
  resolvers: Resolvers,
});

app.use('/graphql', bodyParser.json(), graphqlExpress({
  schema: executableSchema,
  context: {}, // at least(!) an empty object
}));

app.use('/graphiql', graphiqlExpress({
  endpointURL: '/graphql',
}));

const graphQLServer = createServer(app);

graphQLServer.listen(PORT, () => console.log(`GraphQL Server is now running on http://localhost:${PORT}/graphql`));




所以我正在尝试学习Graphql来构建一个api,但是很多关于如何做事的不同教程很难找到它。任何人都可以告诉我或指出我正确的方向,我做错了吗?

1 个答案:

答案 0 :(得分:1)

您说的用户名参数是'用户名'这不是有效类型(与电子邮件,密码和位置相同)。假设用户名,电子邮件,密码和位置是字符串并且是必需的,突变应该如下所示:

mutation createUser(username: String!, $email: String!, $password: String!, $location: String!) {
   createUser(username: $username, email: $email, password: $password, location: $location {
      username
      email
      password
      location
    }
}