schema.lua 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. local schema = {}
  2. schema.__index = schema
  3. function schema.create(config)
  4. assert(type(config.query) == 'table', 'must provide query object')
  5. local self = {}
  6. for k, v in pairs(config) do
  7. self[k] = v
  8. end
  9. local function generateTypeMap(node)
  10. if node.__type == 'NonNull' or node.__type == 'List' then
  11. return generateTypeMap(node.ofType)
  12. end
  13. if self.typeMap[node.name] and self.typeMap[node.name] ~= node then
  14. error('Encountered multiple types named "' .. node.name .. '"')
  15. end
  16. self.typeMap[node.name] = node
  17. if node.__type == 'Object' and node.interfaces then
  18. for _, interface in ipairs(node.interfaces) do
  19. print(require('inspect')(interface))
  20. generateTypeMap(interface)
  21. end
  22. end
  23. if node.__type == 'Object' or node.__type == 'Interface' or node.__type == 'Union' then
  24. for fieldName, field in pairs(node.fields) do
  25. if field.arguments then
  26. for _, argument in pairs(field.arguments) do
  27. generateTypeMap(argument)
  28. end
  29. end
  30. generateTypeMap(field.kind)
  31. end
  32. end
  33. end
  34. self.typeMap = {}
  35. generateTypeMap(self.query)
  36. return setmetatable(self, schema)
  37. end
  38. function schema:getType(name)
  39. return self.typeMap[name]
  40. end
  41. return schema