GraphQL是一种数据查询语言和运行时,适用于API,它在客户端中使用类型来描述数据,并将数据操作包装在统一的端点中。而MySQL则是一种关系型数据库,其中数据以表格的形式存储,它能够以多种方式为应用程序提供数据。
GraphQL可以使用各种后端存储来获取数据,并且可以使用框架或库与数据库进行连接。在本文中,我们将讨论如何使用GraphQL连接MySQL。
const { graphqlHTTP } = require('express-graphql');const express = require('express');const {GraphQLObjectType,GraphQLString,GraphQLInt,GraphQLSchema,GraphQLList,GraphQLNonNull} = require('graphql');const mysql = require('mysql');// 创建mysql连接const connection = mysql.createConnection({host: 'localhost',user: 'root',password: 'password',database: 'database_name'});// 定义schemaconst BookType = new GraphQLObjectType({name: 'Book',fields: () =>({id: { type: GraphQLInt },title: { type: GraphQLString },author: { type: GraphQLString }})});const RootQueryType = new GraphQLObjectType({name: 'Query',fields: () =>({books: {type: new GraphQLList(BookType),resolve(parent, args) {return new Promise((resolve, reject) =>{// 查询mysql中的所有书籍connection.query('SELECT * FROM books', (err, results) =>{if (err) {reject(err);} else {resolve(results);}});});}}})});const schema = new GraphQLSchema({query: RootQueryType});// 创建express服务器const app = express();app.use('/graphql', graphqlHTTP({schema,graphiql: true}));// 监听端口app.listen(3000, () =>{console.log('Server started on port 3000');});
以上代码主要分为三个部分。
第一部分是创建MySQL连接对象,并使用其中包含的数据来连接数据库。这里还可以配置连接,例如指定连接超时时间、允许的最大连接数量等。
第二部分是编写GraphQL schema,这里我们定义了一个名为Book的Object Type,并在RootQueryType中定义了一个resolver来检索所有书籍。在resovler中,我们执行了一个MySQL查询,然后将查询结果解析为GraphQL的格式并返回。
第三部分是启动Express服务器并在端口3000上监听请求。我们使用express-graphql中的graphqlHTTP来创建GraphQL API的单个端点。
通过这种方式,我们可以使用GraphQL与MySQL连接,轻松地将API提供给使用GraphQL的客户端。