试一试 GraphQL (2)

以前:

const schema = buildSchema(` type Account { name: String age: Int sex: String department: String salary(city: String): Int } type Query { account (username: String): Account } `)

现在

const AccountType = new graphql.GraphQLObjectType({ name: 'Account', fields: { name: {type: graphql.GraphQLString}, age: {type: graphiql.GraphQLInt}, sex: {type: raphql.GraphQLString}, department: {type: graphql.GraphQLString}, } }) const queryType = new graphiql.GraphQLObjectType({ name: 'Query', fields: { account: { type: AccountType, args: { username: {type: graphiql.GraphQLString} }, resolve(_, {username}){ const name = username const sex = 'nan' const age = 18 const department = '开发部' return { name, age, sex, department } } } } }) const schema = new graphiql.GraphQLSchema({query: queryType})

代码量提升,编辑器提示,可维护性提升,报错信息更精准。

结合 MySql CURD

接下来需要稍作更改,拼接几个 SQL 语句, 操作数据库。

创建数据库 test , 表 account,并添加几个字段如下:

试一试 GraphQL

npm i mysql -S const mysql = require('mysql') const pool = mysql.createPool({ connectionLimit: 10, host: 'localhost', user: 'root', password: '123456', database: 'test', }) const schema = buildSchema(` type Account { name: String age: Int sex: String department: String salary(city: String): Int } input AccountInput { name: String age: Int sex: String department: String salary: Int } type Query { accounts: [Account] } type Mutation { createAccount(input: AccountInput): Account updateAccount(id: ID!, input: AccountInput): Account deleteAccount(id: ID!): Boolean } `) const rootValue = { createAccount({ input }) { const data = { name: input.name, age: input.age, sex: input.sex, department: input.department, } // query 是异步操作, 使用 promise return new Promise((resolve, reject) => { pool.query('insert into account set ?', data, err => { if (err) { console.log('出错了' + err.message) return } resolve(data) }) }) }, deleteAccount({ id }) { return new Promise((resolve, reject) => { pool.query('delete from account where id = ?', id, err => { if (err) { console.log('出错了' + err) reject(false) return } resolve(true) }) }) }, updateAccount({ id, input }) { const data = input return new Promise((resolve, reject) => { pool.query('update account set ? where id = ?', [data, id], err => { if (err) { console.log('出错了' + err.message) return } resolve(data) }) }) }, accounts() { return new Promise((resolve, reject) => { pool.query('select name, age, sex, department from account', (err, res) => { if (err) { console.log('出错了' + err) return } let arr = [] for (let i = 0; i < res.length; i++) { arr.push({ name: res[i].name, sex: res[i].sex, age: res[i].age, department: res[i].department, }) } resolve(arr) }) }) }, } 代码片段

为方便操作,我将完整代码片段放在最后,供你试一试。

fakeDbconst express = require('express') const app = express() const { graphqlHTTP } = require('express-graphql') const { buildSchema } = require('graphql') const schema = buildSchema(` type Account { name: String age: Int sex: String department: String salary(city: String): Int } input AccountInput { name: String age: Int sex: String department: String salary: Int } type Query { hello: String getClassMates(classNo: Int!): [String] account (username: String): Account accounts: [Account] } type Mutation { createAccount(input: AccountInput): Account updateAccount(id: ID!, input: AccountInput): Account } `) const fakeDb = {} const rootValue = { hello: () => 'Hello world!', getClassMates: ({ classNo }) => { const obj = { 31: ['张三', '李四', '王五'], 61: ['张大三', '李大四', '王大五'], } return obj[classNo] }, account: ({ username }) => { const name = username const sex = 'nan' const age = 10 const department = '开发部' const salary = ({ city }) => { if (city === '北京' || city === '上海' || city === '深圳' || city === '广州') { return 10000 } return 3000 } return { name, sex, age, department, salary, } }, createAccount({ input }) { // 模拟数据库保存 fakeDb[input.name] = input // 返回保存结果 return fakeDb[input.name] }, updateAccount({ id, input }) { // 模拟更新数据库 const updatedAccount = Object.assign({}, fakeDb[id], input) fakeDb[id] = updatedAccount return updatedAccount }, accounts() { let arr = [] for (const key in fakeDb) { arr.push(fakeDb[key]) } return arr }, } // 公开文件夹 供用户访问静态资源 app.use(express.static('public')) // const middleware = (req, res, next) => { // // console.log(req.headers.cookie) // if (req.url.indexOf('/graphql') !== -1) { // res.send( // JSON.stringify({ // error: '您没有权访问这个接口', // }) // ) // return // } // next() // } // app.use(middleware) app.use( '/graphql', graphqlHTTP({ schema, rootValue, graphiql: true, }) ) app.listen(4000, () => console.log('Now browse to localhost:4000/graphql')) MySQLconst express = require('express') const app = express() const { graphqlHTTP } = require('express-graphql') const { buildSchema } = require('graphql') const mysql = require('mysql') const { resolve } = require('path') const pool = mysql.createPool({ connectionLimit: 10, host: 'localhost', user: 'root', password: '123456', database: 'test', }) const schema = buildSchema(` type Account { name: String age: Int sex: String department: String salary(city: String): Int } input AccountInput { name: String age: Int sex: String department: String salary: Int } type Query { hello: String getClassMates(classNo: Int!): [String] account (username: String): Account accounts: [Account] } type Mutation { createAccount(input: AccountInput): Account updateAccount(id: ID!, input: AccountInput): Account deleteAccount(id: ID!): Boolean } `) const rootValue = { hello: () => 'Hello world!', getClassMates: ({ classNo }) => { const obj = { 31: ['张三', '李四', '王五'], 61: ['张大三', '李大四', '王大五'], } return obj[classNo] }, account: ({ username }) => { const name = username const sex = 'nan' const age = 10 const department = '开发部' const salary = ({ city }) => { if (city === '北京' || city === '上海' || city === '深圳' || city === '广州') { return 10000 } return 3000 } return { name, sex, age, department, salary, } }, accounts() { return new Promise((resolve, reject) => { pool.query('select name, age, sex, department from account', (err, res) => { if (err) { console.log('出错了' + err) return } let arr = [] for (let i = 0; i < res.length; i++) { arr.push({ name: res[i].name, sex: res[i].sex, age: res[i].age, department: res[i].department, }) } resolve(arr) }) }) }, createAccount({ input }) { const data = { name: input.name, age: input.age, sex: input.sex, department: input.department, } return new Promise((resolve, reject) => { pool.query('insert into account set ?', data, err => { if (err) { console.log('出错了' + err.message) return } resolve(data) }) }) }, updateAccount({ id, input }) { const data = input return new Promise((resolve, reject) => { pool.query('update account set ? where id = ?', [data, id], err => { if (err) { console.log('出错了' + err.message) return } resolve(data) }) }) }, deleteAccount({ id }) { return new Promise((resolve, reject) => { pool.query('delete from account where id = ?', id, err => { if (err) { console.log('出错了' + err) reject(false) return } resolve(true) }) }) }, } // 公开文件夹 供用户访问静态资源 app.use(express.static('public')) app.use( '/graphql', graphqlHTTP({ schema, rootValue, graphiql: true, }) ) app.listen(4000, () => console.log('Now browse to localhost:4000/graphql'))

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpfzfg.html