expand.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. const { buildSchema, GraphQLObjectType, GraphQLString, GraphQLInt, GraphQLList, GraphQLSchema } = require('graphql');
  2. const ObjectID = require("mongodb").ObjectID;
  3. function mmExpandSchema(gqlSchema){
  4. const types = {}
  5. const _typeMap = gqlSchema.getTypeMap()
  6. const buildInTypes = ['Query', 'Mutation', 'ID', 'Float', "String", 'Int', 'Boolean',
  7. 'Query!', 'Mutation!', 'ID!', 'Float!', "String!", 'Int!', 'Boolean!' ]
  8. async function argToSavables(arg, outputTypeName, Savable){
  9. console.log('argToSavables', arg)
  10. const entity = arg._id ? await Savable.m[outputTypeName].findOne({_id: ObjectID(arg._id)}) :
  11. new Savable.classes[outputTypeName]({})
  12. const {_id, ...data} = arg;
  13. const type = _typeMap[outputTypeName + 'Input']
  14. const fields = type.getFields()
  15. let changed = !_id
  16. for(let [fieldName, value] of Object.entries(data)){
  17. let typeName = fields[fieldName].type.toString()
  18. if (!buildInTypes.includes(typeName)){
  19. console.log('recursive', arg[fieldName], typeName)
  20. changed = true
  21. if (typeName[0] === '['){
  22. const nestedTypeName = typeName.slice(1,-6)
  23. console.log('array',nestedTypeName)
  24. entity[fieldName] = []
  25. if (value) for (let nestedArg of value){
  26. const nestedEntity = await argToSavables(nestedArg, nestedTypeName, Savable)
  27. entity[fieldName].push(nestedEntity)
  28. }
  29. }
  30. else {
  31. const nestedTypeName = typeName.slice(0,-5)
  32. console.log('one', nestedTypeName)
  33. entity[fieldName] = await argToSavables(value, nestedTypeName, Savable)
  34. }
  35. }
  36. else {
  37. entity[fieldName] = value
  38. }
  39. }
  40. changed && await entity.save()
  41. return entity
  42. }
  43. let queryFields = _typeMap.Query ? _typeMap.Query.getFields() : {}
  44. let mutationFields = _typeMap.Mutation ? _typeMap.Mutation.getFields() : {}
  45. for (let [typeName, type] of Object.entries(_typeMap))
  46. if (!buildInTypes.includes(typeName) &&
  47. !typeName.startsWith('__')){
  48. if (typeName.endsWith('Input')){
  49. let outputTypeName = typeName.substr(0, typeName.length - 'Input'.length)
  50. if (outputTypeName in _typeMap){
  51. types[outputTypeName] = type
  52. const queryUpdater = query => {
  53. const checkers = [
  54. function objectID(val){
  55. if (val && typeof val === 'string' && val.length == 24){
  56. try {
  57. const id = ObjectID(val)
  58. if (id.toString() === val) return id
  59. }
  60. catch (e){
  61. return val
  62. }
  63. }
  64. return val
  65. },
  66. function regexp(val){
  67. if (val && typeof val === 'string' && val.startsWith('/') && val.endsWith('/')){
  68. try {
  69. return new RegExp(val.slice(1, -1))
  70. }
  71. catch (e){
  72. return val
  73. }
  74. }
  75. return val
  76. },
  77. ]
  78. const checker = val => {
  79. const originalVal = val
  80. for (let lambda of checkers){
  81. val = lambda(val)
  82. }
  83. return val !== originalVal && val
  84. }
  85. const walker = obj =>{
  86. for (let [key, value] of Object.entries(obj)){
  87. if (key === '___owner') continue;
  88. let newValue;
  89. if (newValue = checker(value)) obj[key] = newValue;
  90. else if (newValue && typeof newValue === 'object'){
  91. obj[key] = walker(value)
  92. }
  93. }
  94. return obj
  95. }
  96. return walker(query)
  97. }
  98. const find = {
  99. type: GraphQLList(_typeMap[outputTypeName]),
  100. args: {query: {type: GraphQLString}},
  101. async resolve(root, args, context, info){
  102. //console.log(root, args, context, info)
  103. const Savable = context.models.SlicedSavable || context.models.Savable
  104. args = JSON.parse(args.query)
  105. queryUpdater(args[0])
  106. //console.log(args)
  107. let results = []
  108. for (let result of Savable.m[outputTypeName].find(...args)){
  109. try {result = await result} catch (e) { break }
  110. results.push(result)
  111. }
  112. return results;
  113. }
  114. }
  115. queryFields[`${outputTypeName}Find`] = find
  116. const count = {
  117. type: GraphQLInt,
  118. args: {query: {type: GraphQLString}},
  119. async resolve(root, args, context, info){
  120. const Savable = context.models.SlicedSavable || context.models.Savable
  121. args = JSON.parse(args.query)
  122. queryUpdater(args[0])
  123. return await Savable.m[outputTypeName].count(...args)
  124. }
  125. }
  126. queryFields[`${outputTypeName}Count`] = count
  127. const findOne = {
  128. type: _typeMap[outputTypeName],
  129. args: {query: {type: GraphQLString}},
  130. async resolve(root, args, context, info){
  131. //console.log(root, args, context, info)
  132. const Savable = context.models.SlicedSavable || context.models.Savable
  133. args = JSON.parse(args.query)
  134. let [query] = args
  135. queryUpdater(query)
  136. console.log(query)
  137. let record = Savable.m[outputTypeName].findOne(query, ...args.slice(1))
  138. return record;
  139. }
  140. }
  141. queryFields[`${outputTypeName}FindOne`] = findOne
  142. const lowerCaseName = outputTypeName[0].toLowerCase() + outputTypeName.slice(1)
  143. const del = {
  144. type: _typeMap[outputTypeName],
  145. args: {[lowerCaseName]: {type: _typeMap[typeName]}},
  146. async resolve(root, args, context, info){
  147. //console.log(root, args, context, info)
  148. const Savable = context.models.SlicedSavable || context.models.Savable
  149. const arg = args[lowerCaseName]
  150. if (! ('_id' in arg)){
  151. return null;
  152. }
  153. let entity = await Savable.m[outputTypeName].findOne({_id: ObjectID(arg._id)})
  154. if (entity){
  155. let copy = {...entity}
  156. await entity.delete()
  157. return copy;
  158. }
  159. return entity;
  160. }
  161. }
  162. mutationFields[`${outputTypeName}Delete`] = del
  163. const upsert = {
  164. type: _typeMap[outputTypeName],
  165. args: {[lowerCaseName]: {type: _typeMap[typeName]}},
  166. async resolve(root, args, context, info){
  167. //console.log(root, args, context, info)
  168. const Savable = context.models.SlicedSavable || context.models.Savable
  169. const arg = args[lowerCaseName]
  170. const entity = argToSavables(args[lowerCaseName], outputTypeName, Savable)
  171. return entity;
  172. }
  173. }
  174. mutationFields[`${outputTypeName}Upsert`] = upsert
  175. }
  176. }
  177. }
  178. let newQuery = new GraphQLObjectType({name: 'Query', fields: queryFields})
  179. let newMutation = new GraphQLObjectType({name: 'Mutation', fields: mutationFields})
  180. let newSchema = new GraphQLSchema({query: newQuery, mutation: newMutation})
  181. return newSchema;
  182. }
  183. module.exports = mmExpandSchema