expand.js 10 KB

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