expand.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  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. let newValue;
  88. if (newValue = checker(value)) obj[key] = newValue;
  89. else if (newValue && typeof newValue === 'object'){
  90. obj[key] = walker(value)
  91. }
  92. }
  93. return obj
  94. }
  95. return walker(query)
  96. }
  97. const find = {
  98. type: GraphQLList(_typeMap[outputTypeName]),
  99. args: {query: {type: GraphQLString}},
  100. async resolve(root, args, context, info){
  101. //console.log(root, args, context, info)
  102. const Savable = context.models.SlicedSavable || context.models.Savable
  103. args = JSON.parse(args.query)
  104. queryUpdater(args[0])
  105. console.log(args)
  106. let results = []
  107. for (let result of Savable.m[outputTypeName].find(...args)){
  108. try {result = await result} catch (e) { break }
  109. results.push(result)
  110. }
  111. return results;
  112. }
  113. }
  114. queryFields[`${outputTypeName}Find`] = find
  115. const count = {
  116. type: GraphQLInt,
  117. args: {query: {type: GraphQLString}},
  118. async resolve(root, args, context, info){
  119. const Savable = context.models.SlicedSavable || context.models.Savable
  120. args = JSON.parse(args.query)
  121. return await Savable.m[outputTypeName].count(...args)
  122. }
  123. }
  124. queryFields[`${outputTypeName}Count`] = count
  125. const findOne = {
  126. type: _typeMap[outputTypeName],
  127. args: {query: {type: GraphQLString}},
  128. async resolve(root, args, context, info){
  129. //console.log(root, args, context, info)
  130. const Savable = context.models.SlicedSavable || context.models.Savable
  131. args = JSON.parse(args.query)
  132. let [query] = args
  133. if (query._id && typeof query._id === 'string'){
  134. query._id = ObjectID(query._id)
  135. }
  136. let record = Savable.m[outputTypeName].findOne(query, ...args.slice(1))
  137. return record;
  138. }
  139. }
  140. queryFields[`${outputTypeName}FindOne`] = findOne
  141. const lowerCaseName = outputTypeName[0].toLowerCase() + outputTypeName.slice(1)
  142. const del = {
  143. type: _typeMap[outputTypeName],
  144. args: {[lowerCaseName]: {type: _typeMap[typeName]}},
  145. async resolve(root, args, context, info){
  146. //console.log(root, args, context, info)
  147. const Savable = context.models.SlicedSavable || context.models.Savable
  148. const arg = args[lowerCaseName]
  149. if (! ('_id' in arg)){
  150. return null;
  151. }
  152. let entity = await Savable.m[outputTypeName].findOne({_id: ObjectID(arg._id)})
  153. if (entity){
  154. let copy = {...entity}
  155. await entity.delete()
  156. return copy;
  157. }
  158. return entity;
  159. }
  160. }
  161. mutationFields[`${outputTypeName}Delete`] = del
  162. const upsert = {
  163. type: _typeMap[outputTypeName],
  164. args: {[lowerCaseName]: {type: _typeMap[typeName]}},
  165. async resolve(root, args, context, info){
  166. //console.log(root, args, context, info)
  167. const Savable = context.models.SlicedSavable || context.models.Savable
  168. const arg = args[lowerCaseName]
  169. const entity = argToSavables(args[lowerCaseName], outputTypeName, Savable)
  170. return entity;
  171. }
  172. }
  173. mutationFields[`${outputTypeName}Upsert`] = upsert
  174. }
  175. }
  176. }
  177. let newQuery = new GraphQLObjectType({name: 'Query', fields: queryFields})
  178. let newMutation = new GraphQLObjectType({name: 'Mutation', fields: mutationFields})
  179. let newSchema = new GraphQLSchema({query: newQuery, mutation: newMutation})
  180. return newSchema;
  181. }
  182. module.exports = mmExpandSchema