首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >GraphQL学习第四篇 -在Koa中使用GraphQL

GraphQL学习第四篇 -在Koa中使用GraphQL

作者头像
越陌度阡
发布2020-11-26 12:24:42
1.2K2
发布2020-11-26 12:24:42
举报

在Koa中使用GraphQL主要有以下几步:

1. 安装 graphql、koa-graphql 和 koa-mount

2. 引入koa-mount 和 koa-graphql。

3. 引入自定义的schema,其中定义schema又分为以下几步:

(1). 定义查询字段的schema类型。

(2). 定义一个根 , 根里面定义调用schema类型的方法。

(3). 把根挂载到 GraphQLSchema。

4. 配置中间件,注意要放在实例化koa之后。

下面用代码来说明具体的实现步骤:

首先是Koa中的主文件app.js。

const Koa = require('koa');
const router = require('koa-router')();

// const DB = require('./model/db.js');

// 1. npm install graphql koa-graphql koa-mount --save

// 2. 引入koa-mount和koa-graphql
const mount = require('koa-mount');
const graphqlHTTP = require('koa-graphql');
// 3. 引入自定义的schema
var GraphQLDefaultSchema = require('./schema/default.js')

var app = new Koa();

// 4. 配置中间件,要放在实例化koa之后
app.use(mount('/graphql', graphqlHTTP({
    // 自定义的schema
    schema: GraphQLDefaultSchema,
    // 上线改为false,调试模式时为true
    graphiql: true
})));


// router.get('/', async (ctx) => {
//     ctx.body = "首页";
// })

// router.get('/getNavList', async (ctx) => {
//     var navList = await DB.find('nav', {});
//     ctx.body = navList;
// })

app.use(router.routes());  
app.use(router.allowedMethods());
app.listen(4000);

然后是app.js里引入的自定义的schema,文件名为default.js。

const DB = require('../model/db.js');
// 从graphql中获取所需要的子模块
const {
    // schema类型
    GraphQLObjectType,
    // 字段的类型
    GraphQLString,
    GraphQLInt,
    // 数组类型
    GraphQLList,
    GraphQLSchema
} = require('graphql')

// 1.获取导航列表,定义导航的schema类型
var NavSchema = new GraphQLObjectType({
    // 取个名字
    name: 'nav',
    // 字段,与数据库对应
    fields: {
        _id: {
            type: GraphQLString
        },
        title: {
            type: GraphQLString
        }, url: {

            type: GraphQLString
        },
        sort: {
            type: GraphQLInt

        },
        status: {
            type: GraphQLString
        },
        add_time: {
            type: GraphQLString
        }
    }
})

// 2.定义一个根 ,根里面定义调用导航schema类型的方法
var RootSchema = new GraphQLObjectType({
    name: 'root',
    fields: {
        // 获取导航列表
        navList: {
            type: GraphQLList(NavSchema),
            // 如果没有参数,可以不写args
            async resolve(parent, args) {
                var navList = await DB.find('nav', {});
                return navList;
            }

        },
        // 获了一个导航类型下的数据
        oneNavList: {
            type: NavSchema,
            args: {
                _id: {
                    type: GraphQLString
                },
                status: {
                    type: GraphQLString
                }
            },
            async resolve(parent, args) {
                var oneNavList = await DB.find('nav', { "_id": DB.getObjectId(args._id), "status": args.status });
                return oneNavList[0];
            }
        }
    }
})

// 3.把根挂载到 GraphQLSchema
module.exports = new GraphQLSchema({
    query: RootSchema
})

最后是在default.js里引入的封装过的数据库。

var MongoDB = require('mongodb');
var MongoClient = MongoDB.MongoClient;
var ObjectID = MongoDB.ObjectID;
var Config = {
    dbUrl: 'mongodb://localhost:27017/',
    dbName: 'koa'
};

class DB {
    static getInstance() {
        if (!DB.instance) {
            DB.instance = new DB();
        }
        return DB.instance;
    }

    constructor() {
        this.dbClient = '';
        this.connect();
    }
    // 连接数据库
    connect() {
        let that = this;
        return new Promise((resolve, reject) => {
            if (!that.dbClient) {
                MongoClient.connect(Config.dbUrl, { useNewUrlParser: true }, (err, client) => {
                    if (err) {
                        reject(err)
                    } else {
                        that.dbClient = client.db(Config.dbName);
                        resolve(that.dbClient)
                    }
                })
            } else {
                resolve(_that.dbClient);

            }
        })
    }
    // 查找方法
    find(collectionName, json1, json2, json3) {
        if (arguments.length == 2) {
            var attr = {};
            var slipNum = 0;
            var pageSize = 0;

        } else if (arguments.length == 3) {
            var attr = json2;
            var slipNum = 0;
            var pageSize = 0;
        } else if (arguments.length == 4) {
            var attr = json2;
            var page = json3.page || 1;
            var pageSize = json3.pageSize || 20;
            var slipNum = (page - 1) * pageSize;

            if (json3.sortJson) {
                var sortJson = json3.sortJson;
            } else {
                var sortJson = {}
            }
        } else {
            console.log('传入参数错误')
        }
        return new Promise((resolve, reject) => {
            this.connect().then((db) => {
                var result = db.collection(collectionName).find(json1, { fields: attr }).skip(slipNum).limit(pageSize).sort(sortJson);
                result.toArray(function (err, docs) {
                    if (err) {
                        reject(err);
                        return;
                    }
                    resolve(docs);
                })

            })
        })
    }
    // 更新方法
    update(collectionName, json1, json2) {
        return new Promise((resolve, reject) => {
            this.connect().then((db) => {
                db.collection(collectionName).updateOne(json1, {
                    $set: json2
                }, (err, result) => {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(result);
                    }
                })

            })
        })
    }
    // 插入方法
    insert(collectionName, json) {
        return new Promise((resolve, reject) => {
            this.connect().then((db) => {
                db.collection(collectionName).insertOne(json, function (err, result) {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(result);
                    }
                })
            })
        })
    }
    // 删除方法
    remove(collectionName, json) {
        return new Promise((resolve, reject) => {
            this.connect().then((db) => {
                db.collection(collectionName).removeOne(json, function (err, result) {
                    if (err) {
                        reject(err);
                    } else {
                        resolve(result);
                    }
                })
            })
        })
    }
    // MongoDB按ID的查询方法
    getObjectId(id) {
        return new ObjectID(id);
    }
    // 统计数量的方法
    count(collectionName, json) {
        return new Promise((resolve, reject) => {
            this.connect().then((db) => {
                var result = db.collection(collectionName).count(json);
                result.then(function (count) {
                    resolve(count);
                })
            })
        })
    }
}
module.exports = DB.getInstance();
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-01-15 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云数据库 MongoDB
腾讯云数据库 MongoDB(TencentDB for MongoDB)是腾讯云基于全球广受欢迎的 MongoDB 打造的高性能 NoSQL 数据库,100%完全兼容 MongoDB 协议,支持跨文档事务,提供稳定丰富的监控管理,弹性可扩展、自动容灾,适用于文档型数据库场景,您无需自建灾备体系及控制管理系统。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档