util.lua 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. local util = {}
  2. function util.map(t, fn)
  3. local res = {}
  4. for k, v in pairs(t) do res[k] = fn(v, k) end
  5. return res
  6. end
  7. function util.find(t, fn)
  8. local res = {}
  9. for k, v in pairs(t) do
  10. if fn(v, k) then return v end
  11. end
  12. end
  13. function util.compose(f, g)
  14. return function(...) return f(g(...)) end
  15. end
  16. function util.bind1(func, x)
  17. return function(y)
  18. return func(x, y)
  19. end
  20. end
  21. function util.getParentField(context, name, step_back)
  22. local obj = context.objects[#context.objects - step_back]
  23. if obj.__type == 'List' then
  24. return obj.ofType.fields[name]
  25. else
  26. return obj.fields[name]
  27. end
  28. end
  29. function util.coerceValue(node, schemaType, variables)
  30. variables = variables or {}
  31. if schemaType.__type == 'NonNull' then
  32. return util.coerceValue(node, schemaType.ofType, variables)
  33. end
  34. if not node then
  35. return nil
  36. end
  37. if node.kind == 'variable' then
  38. return variables[node.name.value]
  39. end
  40. if schemaType.__type == 'List' then
  41. if node.kind ~= 'list' then
  42. error('Expected a list')
  43. end
  44. return util.map(node.values, function(value)
  45. return util.coerceValue(node.values[i], schemaType.ofType, variables)
  46. end)
  47. end
  48. if schemaType.__type == 'InputObject' then
  49. if node.kind ~= 'inputObject' then
  50. error('Expected an input object')
  51. end
  52. return util.map(node.values, function(field)
  53. if not schemaType.fields[field.name] then
  54. error('Unknown input object field "' .. field.name .. '"')
  55. end
  56. return util.coerceValue(schemaType.fields[field.name].kind, field.value, variables)
  57. end)
  58. end
  59. if schemaType.__type == 'Enum' then
  60. if node.kind ~= 'enum' then
  61. error('Expected enum value, got ' .. node.kind)
  62. end
  63. if not schemaType.values[node.value] then
  64. error('Invalid enum value "' .. node.value .. '"')
  65. end
  66. return node.value
  67. end
  68. if schemaType.__type == 'Scalar' then
  69. if schemaType.parseLiteral(node) == nil then
  70. error('Could not coerce "' .. tostring(node.value) .. '" to "' .. schemaType.name .. '"')
  71. end
  72. return schemaType.parseLiteral(node)
  73. end
  74. end
  75. return util