expand.js 10 KB

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