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. self.typeMap = {}
  10. local function generateTypeMap(node)
  11. if node.__type == 'NonNull' or node.__type == 'List' then
  12. return generateTypeMap(node.ofType)
  13. end
  14. if self.typeMap[node.name] and self.typeMap[node.name] ~= node then
  15. error('Encountered multiple types named "' .. node.name .. '"')
  16. end
  17. self.typeMap[node.name] = node
  18. if node.__type == 'Object' and node.interfaces then
  19. for _, interface in ipairs(node.interfaces) do
  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. 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