schema.lua 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  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. generateTypeMap(interface)
  20. end
  21. end
  22. if node.__type == 'Object' or node.__type == 'Interface' or node.__type == 'Union' then
  23. for fieldName, field in pairs(node.fields) do
  24. if field.arguments then
  25. for _, argument in pairs(field.arguments) do
  26. generateTypeMap(argument)
  27. end
  28. end
  29. generateTypeMap(field.kind)
  30. end
  31. end
  32. end
  33. self.typeMap = {}
  34. generateTypeMap(self.query)
  35. return setmetatable(self, schema)
  36. end
  37. function schema:getType(name)
  38. return self.typeMap[name]
  39. end
  40. return schema