在《Graphql實戰系列(上)》中咱們已經完成技術選型,並將graphql橋接到凝膠gels項目中,並動手寫了schema,並能夠經過 http://localhost:5000/graphql 查看效果。這一節,咱們根據數據庫表來自動生成基本的查詢與更新schema,並能方便的擴展schema,實現咱們想要的業務邏輯。node
用navicat在數據庫中設計的表
自動生成的graphql測試mysql
對象定義在apollo-server中是用字符串來作的,而Query與Mutation只能有一個,而咱們的定義又會分散在多個文件中,所以只能先以必定的形式把它們存入數組中,在生成schema前一刻再組合。git
const customDefs = { textDefs: ` type ReviseResult { id: Int affectedRows: Int status: Int message: String }, queryDefs: [], mutationDefs: [] } const customResolvers = { Query: { }, Mutation: { } } export { customDefs, customResolvers }
let typeDefs = [] let dirGraphql = requireDir('../../graphql') //從手寫schema業務模塊目錄讀入文件 G.L.each(dirGraphql, (item, name) => { if (item && item.customDefs && item.customResolvers) { typeDefs.push(item.customDefs.textDefs || '') //合併文本對象定義 typeDefObj.query = typeDefObj.query.concat(item.customDefs.queryDefs || []) //合併Query typeDefObj.mutation = typeDefObj.mutation.concat(item.customDefs.mutationDefs || []) //合併Matation let { Query, Mutation, ...Other } = item.customResolvers Object.assign(resolvers.Query, Query) //合併resolvers.Query Object.assign(resolvers.Mutation, Mutation) //合併resolvers.Mutation Object.assign(resolvers, Other) //合併其它resolvers } }) //將query與matation查詢更新對象由自定義的數組轉化成爲文本形式 typeDefs.push(Object.entries(typeDefObj).reduce((total, cur) => { return total += ` type ${G.tools.bigCamelCase(cur[0])} { ${cur[1].join('')} } ` }, ''))
自動生成內容:github
定義一類型轉換,不在定義中的默認爲String。算法
const TYPEFROMMYSQLTOGRAPHQL = { int: 'Int', smallint: 'Int', tinyint: 'Int', bigint: 'Int', double: 'Float', float: 'Float', decimal: 'Float', }
let dao = new BaseDao() let tables = await dao.querySql('select TABLE_NAME,TABLE_COMMENT from information_schema.`TABLES` ' + ' where TABLE_SCHEMA = ? and TABLE_TYPE = ? and substr(TABLE_NAME,1,2) <> ? order by ?', [G.CONFIGS.dbconfig.db_name, 'BASE TABLE', 't_', 'TABLE_NAME'])
tables.data.forEach((table) => { columnRs.push(dao.querySql('SELECT `COLUMNS`.COLUMN_NAME,`COLUMNS`.COLUMN_TYPE,`COLUMNS`.IS_NULLABLE,' + '`COLUMNS`.CHARACTER_SET_NAME,`COLUMNS`.COLUMN_DEFAULT,`COLUMNS`.EXTRA,' + '`COLUMNS`.COLUMN_KEY,`COLUMNS`.COLUMN_COMMENT,`STATISTICS`.TABLE_NAME,' + '`STATISTICS`.INDEX_NAME,`STATISTICS`.SEQ_IN_INDEX,`STATISTICS`.NON_UNIQUE,' + '`COLUMNS`.COLLATION_NAME ' + 'FROM information_schema.`COLUMNS` ' + 'LEFT JOIN information_schema.`STATISTICS` ON ' + 'information_schema.`COLUMNS`.TABLE_NAME = `STATISTICS`.TABLE_NAME ' + 'AND information_schema.`COLUMNS`.COLUMN_NAME = information_schema.`STATISTICS`.COLUMN_NAME ' + 'AND information_schema.`STATISTICS`.table_schema = ? ' + 'where information_schema.`COLUMNS`.TABLE_NAME = ? and `COLUMNS`.table_schema = ?', [G.CONFIGS.dbconfig.db_name, table.TABLE_NAME, G.CONFIGS.dbconfig.db_name])) })
取數據庫表字段類型,去除圓括號與長度信息sql
getStartTillBracket(str: string) { return str.indexOf('(') > -1 ? str.substr(0, str.indexOf('(')) : str }
下劃線分隔的表字段轉化爲big camel-case數據庫
bigCamelCase(str: string) { return str.split('_').map((al) => { if (al.length > 0) { return al.substr(0, 1).toUpperCase() + al.substr(1).toLowerCase() } return al }).join('') }
下劃線分隔的表字段轉化爲small camel-casesegmentfault
smallCamelCase(str: string) { let strs = str.split('_') if (strs.length < 2) { return str } else { let tail = strs.slice(1).map((al) => { if (al.length > 0) { return al.substr(0, 1).toUpperCase() + al.substr(1).toLowerCase() } return al }).join('') return strs[0] + tail } }
不以_id結尾,是正常字段,判斷是否爲null,處理必填數組
typeDefObj[table].unshift(`${col['COLUMN_NAME']}: ${typeStr}${col['IS_NULLABLE'] === 'NO' ? '!' : ''}\n`)
以_id結尾,則須要處理關聯關係瀏覽器
//Book表以author_id關聯單個Author實體 typeDefObj[table].unshift(`"""關聯的實體""" ${G.L.trimEnd(col['COLUMN_NAME'], '_id')}: ${G.tools.bigCamelCase(G.L.trimEnd(col['COLUMN_NAME'], '_id'))}`) resolvers[G.tools.bigCamelCase(table)] = { [G.L.trimEnd(col['COLUMN_NAME'], '_id')]: async (element) => { let rs = await new BaseDao(G.L.trimEnd(col['COLUMN_NAME'], '_id')).retrieve({ id: element[col['COLUMN_NAME']] }) return rs.data[0] } } //Author表關聯Book列表 let fTable = G.L.trimEnd(col['COLUMN_NAME'], '_id') if (!typeDefObj[fTable]) { typeDefObj[fTable] = [] } if (typeDefObj[fTable].length >= 2) typeDefObj[fTable].splice(typeDefObj[fTable].length - 2, 0, `"""關聯實體集合"""${table}s: [${G.tools.bigCamelCase(table)}]\n`) else typeDefObj[fTable].push(`${table}s: [${G.tools.bigCamelCase(table)}]\n`) resolvers[G.tools.bigCamelCase(fTable)] = { [`${table}s`]: async (element) => { let rs = await new BaseDao(table).retrieve({ [col['COLUMN_NAME']]: element.id}) return rs.data } }
單條查詢
if (paramId.length > 0) { typeDefObj['query'].push(`${G.tools.smallCamelCase(table)}(${paramId}!): ${G.tools.bigCamelCase(table)}\n`) resolvers.Query[`${G.tools.smallCamelCase(table)}`] = async (_, { id }) => { let rs = await new BaseDao(table).retrieve({ id }) return rs.data[0] } } else { G.logger.error(`Table [${table}] must have id field.`) }
列表查詢
let complex = table.endsWith('s') ? (table.substr(0, table.length - 1) + 'z') : (table + 's') typeDefObj['query'].push(`${G.tools.smallCamelCase(complex)}(${paramStr.join(', ')}): [${G.tools.bigCamelCase(table)}]\n`) resolvers.Query[`${G.tools.smallCamelCase(complex)}`] = async (_, args) => { let rs = await new BaseDao(table).retrieve(args) return rs.data }
typeDefObj['mutation'].push(` create${G.tools.bigCamelCase(table)}(${paramForMutation.slice(1).join(', ')}):ReviseResult update${G.tools.bigCamelCase(table)}(${paramForMutation.join(', ')}):ReviseResult delete${G.tools.bigCamelCase(table)}(${paramId}!):ReviseResult `) resolvers.Mutation[`create${G.tools.bigCamelCase(table)}`] = async (_, args) => { let rs = await new BaseDao(table).create(args) return rs } resolvers.Mutation[`update${G.tools.bigCamelCase(table)}`] = async (_, args) => { let rs = await new BaseDao(table).update(args) return rs } resolvers.Mutation[`delete${G.tools.bigCamelCase(table)}`] = async (_, { id }) => { let rs = await new BaseDao(table).delete({ id }) return rs }
https://github.com/zhoutk/gels
git clone https://github.com/zhoutk/gels cd gels yarn tsc -w nodemon dist/index.js
而後就能夠用瀏覽器打開連接:http://localhost:5000/graphql 查看效果了。
我只能把大概思路寫出來,讓你們有個總體的概念,若想很好的理解,得本身把項目跑起來,根據我提供的思想,慢慢的去理解。由於我在編寫的過程當中仍是遇到了很多的難點,這塊既要自動化,還要能方便的接受手動編寫的schema模塊,的確有點難度。