GraphQL學習與實踐5(連接數據庫mongodb與mysql)

GraphQL學習與實踐5(連接數據庫mongodb與mysql)

接口最終還是得持久化物理容器中做增刪改查的操作。
新建一下圖片的目錄,test12-db:
在這裏插入圖片描述

mongodb

通常鏈接mongodb,我們使用mongoose模塊來處理:

npm install --save mongoose

然後在db目錄中封裝了一個獲取數據庫鏈接對象的類MongoClient:

const mongoose = require('mongoose');

module.exports = class MongoClient {
    constructor({ uri, options, schemas } = {}) {
        this.schemas = schemas;
        this.uri = uri;
        this.options = options;
        this.models = {};
        this.connection = null;
    }

    async connect() {
        let { uri, options } = this;
        mongoose.set('useCreateIndex', true);
        mongoose.set('bufferCommands', false);
        mongoose.set('bufferMaxEntries', 0);
        mongoose.set('autoIndex', false);
        mongoose.connection.on('error', function () {
            console.error('connection error: uri is %s,options is %s', uri, JSON.stringify(options));
        });
        mongoose.connection.once('open', function () {
            console.info('connection success', uri);
        });
        let connection = await mongoose.createConnection(uri, options);
        this.connection = connection;
        console.info('Init mongoose success');
        return connection;
    }

    getCollection(key) {
        if (this.schemas[key]) {
            if (this.models[key]) {
                return this.models[key];
            }
            let model = this.connection.model(key, this.schemas[key]);
            this.models[key] = model;
            return model;
        }
        throw new Error("illegal key");
    }
}

在MongoClient中提供一個connect的方法返回鏈接對象,以面對多重鏈接的情況,同時提供getCollection提供給沒有model首次鏈接的時候再獲取鏈接對象,這種情況一般用於serverless的lambda函數,這裏就直接拿着之前的封裝直接來用了。
然後在mongodb目錄下再提供了一個對象的index.js:

const MongoClient = require("../mongo_client");
const schemas = require("./schema");
const [uri, options] = [
    "mongodb://127.0.0.1:27017/onsen",
    {
        useNewUrlParser: true,
        useCreateIndex: true,
    },
]

const client = new MongoClient({ uri: uri, options: options, schemas: schemas });
module.exports = client;

注:這裏的數據庫,就需要自己去創建模擬數據了。

在根目錄的server.js文件中,創建graphql的服務:

const express = require('express');
const cors = require('cors')
const graphqlHTTP = require('express-graphql');
const graphql = require('graphql');
const { queryType } = require("./schema/schema");

require("./db").mongodb.connect();

const schema = new graphql.GraphQLSchema({ query: queryType });
const app = express();
app.use(cors());
app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');

相比之前的代碼,可以看到增加了:

require("./db").mongodb.connect();

mysql

安裝mysql的模塊:

npm install --save mysql

同樣的類似於mongodb的封裝一樣,這裏也封裝了一個mysql的客戶對象:

var mysql = require('mysql');

class MysqlClient {
    constructor(options = {}) {
        this.pool = mysql.createPool(options);
    }

    doQuery(query) {
        return new Promise((resolve, reject) => {
            this.pool.getConnection((err, conn) => {
                if (err) {
                    return reject(err);
                }
                console.info('getConnection ok')
                conn.query(query, (err, results, fields) => {
                    conn.release();
                    if (err) {
                        return reject(err);
                    }
                    return resolve(results || null);
                })
            })
        });
    }
}

const options = {
    connectionLimit: 1000,
    host: '127.0.0.1',
    password: 'password',
    database: 'yiibaidb',
    user: 'root',
}

module.exports = new MysqlClient(options);

具體有關mysql模塊的,見:
https://www.npmjs.com/package/mysql

做好了數據庫的引用,然後就可以像前面一樣,直接使用schema中寫業務邏輯了,見schema.js:

const graphql = require('graphql');
const mongodb = require("../db").mongodb;
const mysql = require("../db").mysql;

const ArticleType = new graphql.GraphQLObjectType({
   name: 'Article',
   fields: {
      _id: {
         type: graphql.GraphQLString
      },
      title: {
         type: graphql.GraphQLString
      },
      source: {
         type: graphql.GraphQLString
      },
   }
});

const OrderType = new graphql.GraphQLObjectType({
   name: 'Order',
   fields: {
      orderNumber: {
         type: graphql.GraphQLInt
      },
      status: {
         type: graphql.GraphQLString
      },
      comments: {
         type: graphql.GraphQLString
      },
   }
});

const queryType = new graphql.GraphQLObjectType({
   name: 'Query',
   fields: {
      articles: {
         type: graphql.GraphQLList(ArticleType),
         resolve: async () => await mongodb.getCollection('Article').find({}),
      },
      orders: {
         type: graphql.GraphQLList(OrderType),
         args: {
            page: {
               type: graphql.GraphQLInt
            },
            pageSize: {
               type: graphql.GraphQLInt
            },
         },
         resolve: async (_, { page = 0, pageSize = 10 }) => await mysql.doQuery(`
             SELECT  * FROM orders limit ${((page - 1) < 0 ? 0 : (page - 1)) * pageSize},${pageSize};
         `),
      }
   }
});

module.exports = { queryType };

這裏的業務提供了articles和orders的兩個查詢,分別用的是mongodb和mysql的數據庫操作。

在工具上進行驗證,輸入:

{
  articles{
    _id,
    title,
    source,
  },
  orders(page:1,pageSize:5){
   orderNumber,
    status,
    comments,
  }
}

在這裏插入圖片描述

更多

[GraphQL學習與實踐1(入門介紹)](http
s://blog.csdn.net/onsenOnly/artic
le/details/102639327)
GraphQL學習與實踐2(類型、傳參與構造函數類型)
GraphQL學習與實踐3(Mutations And Input Types)
GraphQL學習與實踐4(模擬客戶端請求)
GraphQL學習與實踐5(連接數據庫mongodb與mysql)

代碼:
onsenOnly:https://github.com/onsenOnly/graphql-test

有緣請點顆星,謝謝!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章