expand.js 9.8 KB

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