graphql 是一个开源的图形数据库(基于node.js实现), 中文文档: https://graphql.js.cool/
sequelize-auto 将 mysql 数据库转变成模型
[node] sequelize-auto -h <host> -d <database> -u <user> -x [password] -p [port] --dialect [dialect] -c [/path/to/config] -o [/path/to/models] -t [tablename] -c 参数: -h, --host 主机地址 [必须] -d, --database 数据名 [必须] -u, --user 用户名 -x, --pass 密码 -p, --port 端口号 -c, --config 配置文件,参考: https://sequelize.readthedocs.org/en/latest/api/sequelize/ -o, --output 输出目录 -e, --dialect 数据库引擎: postgres, mysql, sqlite -t, --tables 需要导入的表 -t, --skip-tables 需要排除的表 -c, --camel 使用用驼峰命名法 -n, --no-write 不需要写入文件 -s, --schema 数据库结构
使用数据模型
这里是生成的一个示例模型:
/* jshint indent: 2 */
module.exports = function(sequelize, datatypes) {
return sequelize.define('d_user', {
uid: {
type: datatypes.integer(11).unsigned,
allownull: false,
primarykey: true
},
username: {
type: datatypes.string(16),
defaultvalue: ''
mobile: {
email: {
type: datatypes.string(32),
password: {
salt: {
type: datatypes.string(8),
updatedat: {
type: datatypes.integer(10).unsigned,
allownull: false
}
}, {
tablename: 'user'
});
};
创建数据库模型:
const sequelize = require('sequelize'); const db = new sequelize('数据库名', '用户名', '密码', { host: 'localhost', dialect: 'mysql' }) const user = db.define('user', { uid: { type: sequelize.integer(11).unsigned, allownull: false, primarykey: true }, username: { type: sequelize.string(16), allownull: false, defaultvalue: '' }, mobile: { type: sequelize.string(16), allownull: false, defaultvalue: '' }, email: { type: sequelize.string(32), allownull: false, defaultvalue: '' }, password: { type: sequelize.string(32), allownull: false, defaultvalue: '' }, salt: { type: sequelize.string(8), allownull: false, defaultvalue: '' } }, { tablename: 'user', // 取消默认的时间戳, 否则会报 createdat 不存在错误 timestamps: false }); db.sync(); module.exports = { db, user };
graphql-sequelize 转换 mysql -> graphql 结构
const { graphqlobjecttype,graphqlschema,graphqllist,graphqlint,graphqlstring } = require('graphql');
const { attributefields, resolver } = require('graphql-sequelize');
const { db, user } = require('./db');
usertype = new graphqlobjecttype({
name: 'user',
description: 'a user',
fields: attributefields(user)
});
const query = new graphqlobjecttype({
name: 'query',
description: 'root query object',
fields: () => {
return {
user: {
type: new graphqllist(usertype),
args: {
uid: {
type: graphqlint
},
email: {
type: graphqlstring
}
},
resolve(root, args) {
return db.models.user.findall({ where: args });
}
}
};
}
const schema = new graphqlschema({
query: query
module.exports = schema;
启动服务器
const express =require( 'express');
const graphhttp =require( 'express-graphql');
const schema =require( './schema');
// config
const app_port = 3000;
// start
const app = express();
// graphql
app.use('/graphql', graphhttp({
schema: schema,
pretty: true,
graphiql: true
}));
app.listen(app_port, ()=> {
console.log(`app listening on port ${app_port}`);
本文作者:佚名
来源:51cto