简体   繁体   English

如何为MySQL模型制作GraphQL模式?

[英]How to make GraphQL schema for MySQL models?

I have the following table in mysql. 我在mysql中有下表。

Users 用户

CREATE TABLE users(
    id INTEGER AUTO_INCREMENT PRIMARY KEY,
    username VARCHAR(255) UNIQUE NOT NULL,
    email VARCHAR(255) UNIQUE NOT NULL,
    password VARCHAR(100) NOT NULL,
    created_at TIMESTAMP DEFAULT NOW()
);

and Posts 帖子

CREATE TABLE posts(
    id INTEGER AUTO_INCREMENT PRIMARY KEY,
    created_by INTEGER NOT NULL,
    created_at TIMESTAMP DEFAULT NOW(),
    post_title VARCHAR(100) NOT NULL UNIQUE,
    post_body VARCHAR(255) NOT NULL,
    slug VARCHAR(100) NOT NULL UNIQUE,
    FOREIGN KEY (created_by) REFERENCES users(id)
);

I am using nodejs and the mysql npm package. 我正在使用nodejs和mysql npm包。 How can I make graphQL schema for the models? 如何为模型创建graphQL架构?

I searched a lot but failed to find any solution to this. 我搜索了很多但没有找到任何解决方案。 Mostly people are using sequelize for this purpose. 大多数人都在为此目的使用续集。 Is it better than mysql package? 它比mysql包更好吗?

Yes You can use sequelize orm for connecting graphql to Mysql database 是您可以使用sequelize orm将graphql连接到Mysql数据库

Refference :- http://docs.sequelizejs.com/manual/installation/getting-started 参考: - http://docs.sequelizejs.com/manual/installation/getting-started

Sample Schema and resolvers are given 给出了示例模式和解析器

Schema.js Schema.js

const typeDefinitions = `



type Author {

  authorId: Int
  firstName: String
  lastName: String
  posts: [Post]

}

type Post {

  postId: Int
  title: String 
  text: String
  views: Int
  author: Author

}

input postInput{
  title: String 
  text: String
  views: Int
}


type Query {

  author(firstName: String, lastName: String): [Author]
  posts(postId: Int, title: String, text: String, views: Int): [Post]

}



type Mutation {

createAuthor(firstName: String, lastName: String, posts:[postInput]): Author

updateAuthor(authorId: Int, firstName: String, lastName: String, posts:[postInput]): String

}


schema {
  query: Query
  mutation:Mutation
}
`;

export default [typeDefinitions];

connectors.js connectors.js

import rp from 'request-promise';
var Sequelize = require('sequelize');
var db = new Sequelize('test', 'postgres', 'postgres', {
  host: '192.168.1.168',
  dialect: 'postgres',

  pool: {
    max: 5,
    min: 0,
    idle: 10000
  }

});


const AuthorModel = db.define('author', {
  authorId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true, field: "author_id" },
  firstName: { type: Sequelize.STRING, field: "first_name" },
  lastName: { type: Sequelize.STRING, field: "last_name" },
},{
        freezeTableName: false,
        timestamps: false,
        underscored: false,
        tableName: "author"
    });


const PostModel = db.define('post', {
    postId: { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true, field: "post_id" },
  text: { type: Sequelize.STRING },
  title:  { type: Sequelize.STRING },
  views: { type: Sequelize.INTEGER },
},{
        freezeTableName: false,
        timestamps: false,
        underscored: false,
        tableName: "post"
    });


AuthorModel.hasMany(PostModel, {
    foreignKey: 'author_id'
});
PostModel.belongsTo(AuthorModel, {
    foreignKey: 'author_id'
});

const Author = db.models.author;
const Post = db.models.post;

export { Author, Post };

resolver.js resolver.js

import { Author } from './connectors';
import { Post } from './connectors';


const resolvers = {

  Query: {
    author(_, args) {
      return Author.findAll({ where: args });
    },
    posts(_, args) {
      return Post.findAll({ where: args });
    }
  },

  Mutation: {

    createAuthor(_, args) {
      console.log(args)
      return Author.create(args, {
        include: [{
          model: Post,
        }]
      });
    },

    updateAuthor(_, args) {

      var updateProfile = { title: "name here" };
      console.log(args.authorId)
      var filter = {
        where: {
          authorId: args.authorId
        },
        include: [
          { model: Post }
        ]
      };
      Author.findOne(filter).then(function (product) {
        Author.update(args, { where: { authorId: args.authorId } }).then(function (result) {
          product.posts[0].updateAttributes(args.posts[0]).then(function (result) {
            //return result;
          })
        });
      })
      return "updated";
    },

  },


  Author: {
    posts(author) {
      return author.getPosts();
    },
  },
  Post: {
    author(post) {
      return post.getAuthor();
    },
  },
};

export default resolvers;

You can try a new open source tool called SwitchQL (github.com/SwitchQL/SwitchQL). 您可以尝试一种名为SwitchQL的新开源工具(github.com/SwitchQL/SwitchQL)。 I've been working on the project for a while. 我一直在研究这个项目。

You pass it your connection string and it returns everything you need to run a graphql server on top of an existing database. 您传递了连接字符串,它返回在现有数据库之上运行graphql server所需的一切。 It also returns Apollo compliant client mutation and queries. 它还返回符合Apollo标准的客户端变异和查询。

We only support Postgres at the moment, but if you'd like to look into helping us support MySQL let me know! 我们目前只支持Postgres,但是如果你想帮助我们支持MySQL,请告诉我!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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