introspection.lua 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. local path = (...):gsub('%.[^%.]+$', '')
  2. local types = require(path .. '.types')
  3. local util = require(path .. '.util')
  4. local cjson = require 'cjson' -- needs to be cloned from here https://github.com/openresty/lua-cjson for cjson.empty_array feature
  5. local function isNullish(value)
  6. return value == nil
  7. end
  8. local function instanceof(t, s)
  9. return t.__type == s
  10. end
  11. local __Directive, __DirectiveLocation, __Type, __Field, __InputValue,__EnumValue, TypeKind, __TypeKind, SchemaMetaFieldDef, TypeMetaFieldDef, TypeNameMetaFieldDef, astFromValue, printAst, printers
  12. local __Schema = types.object({
  13. name = '__Schema',
  14. description = [[
  15. A GraphQL Schema defines the capabilities of a GraphQL server. It
  16. exposes all available types and directives on the server, as well as
  17. the entry points for query and mutation operations.
  18. ]],
  19. fields = function()
  20. return {
  21. types = {
  22. description = 'A list of all types supported by this server.',
  23. kind = types.nonNull(types.list(types.nonNull(__Type))),
  24. resolve = function(schema)
  25. return util.values(schema:getTypeMap())
  26. end
  27. },
  28. queryType = {
  29. description = 'The type that query operations will be rooted at.',
  30. kind = types.nonNull(__Type),
  31. resolve = function(schema)
  32. return schema:getQueryType()
  33. end
  34. },
  35. mutationType = {
  36. description = 'If this server supports mutation, the type that mutation operations will be rooted at.',
  37. kind = __Type,
  38. resolve = function(schema)
  39. return schema:getMutationType()
  40. end
  41. },
  42. directives = {
  43. description = 'A list of all directives supported by this server.',
  44. kind = types.nonNull(types.list(types.nonNull(__Directive))),
  45. resolve = function(schema)
  46. return schema.directives
  47. end
  48. }
  49. }
  50. end
  51. })
  52. __Directive = types.object({
  53. name = '__Directive',
  54. description = [[
  55. A Directive provides a way to describe alternate runtime execution and
  56. type validation behavior in a GraphQL document.
  57. \n\nIn some cases, you need to provide options to alter GraphQL’s
  58. execution behavior in ways field arguments will not suffice, such as
  59. conditionally including or skipping a field. Directives provide this by
  60. describing additional information to the executor.
  61. ]],
  62. fields = function()
  63. return {
  64. name = types.nonNull(types.string),
  65. description = types.string,
  66. locations = {
  67. kind = types.nonNull(types.list(types.nonNull(
  68. __DirectiveLocation
  69. )))
  70. },
  71. args = {
  72. kind = types.nonNull(types.list(types.nonNull(__InputValue))),
  73. resolve = function(field)
  74. local args = {}
  75. local transform = function(a, n)
  76. if a.__type then
  77. return { kind = a, name = n }
  78. else
  79. if a.name then return a end
  80. local r = { name = n }
  81. for k,v in pairs(a) do
  82. r[k] = v
  83. end
  84. return r
  85. end
  86. end
  87. for k, v in pairs(field.arguments or {}) do
  88. table.insert(args, transform(v, k))
  89. end
  90. if #args > 0 then
  91. return args
  92. else
  93. return cjson.empty_array
  94. end
  95. end
  96. }
  97. }
  98. end
  99. })
  100. __DirectiveLocation = types.enum({
  101. name = '__DirectiveLocation',
  102. description = [[
  103. A Directive can be adjacent to many parts of the GraphQL language, a
  104. __DirectiveLocation describes one such possible adjacencies.
  105. ]],
  106. values = {
  107. QUERY = {
  108. value = 'QUERY',
  109. description = 'Location adjacent to a query operation.'
  110. },
  111. MUTATION = {
  112. value = 'MUTATION',
  113. description = 'Location adjacent to a mutation operation.'
  114. },
  115. FIELD = {
  116. value = 'FIELD',
  117. description = 'Location adjacent to a field.'
  118. },
  119. FRAGMENT_DEFINITION = {
  120. value = 'FRAGMENT_DEFINITION',
  121. description = 'Location adjacent to a fragment definition.'
  122. },
  123. FRAGMENT_SPREAD = {
  124. value = 'FRAGMENT_SPREAD',
  125. description = 'Location adjacent to a fragment spread.'
  126. },
  127. INLINE_FRAGMENT = {
  128. value = 'INLINE_FRAGMENT',
  129. description = 'Location adjacent to an inline fragment.'
  130. }
  131. }
  132. })
  133. __Type = types.object({
  134. name = '__Type',
  135. description =
  136. 'The fundamental unit of any GraphQL Schema is the type. There are ' ..
  137. 'many kinds of types in GraphQL as represented by the `__TypeKind` enum.' ..
  138. '\n\nDepending on the kind of a type, certain fields describe ' ..
  139. 'information about that type. Scalar types provide no information ' ..
  140. 'beyond a name and description, while Enum types provide their values. ' ..
  141. 'Object and Interface types provide the fields they describe. Abstract ' ..
  142. 'types, Union and Interface, provide the Object types possible ' ..
  143. 'at runtime. List and NonNull types compose other types.',
  144. fields = function() return {
  145. kind = {
  146. kind = types.nonNull(__TypeKind),
  147. resolve = function (type)
  148. if instanceof(type, 'Scalar') then
  149. return TypeKind.SCALAR;
  150. elseif instanceof(type, 'Object') then
  151. return TypeKind.OBJECT;
  152. elseif instanceof(type, 'Interface') then
  153. return TypeKind.INTERFACE;
  154. elseif instanceof(type, 'Union') then
  155. return TypeKind.UNION;
  156. elseif instanceof(type, 'Enum') then
  157. return TypeKind.ENUM;
  158. elseif instanceof(type, 'InputObject') then
  159. return TypeKind.INPUT_OBJECT;
  160. elseif instanceof(type, 'List') then
  161. return TypeKind.LIST;
  162. elseif instanceof(type, 'NonNull') then
  163. return TypeKind.NON_NULL;
  164. end
  165. error('Unknown kind of kind = ' .. type);
  166. end
  167. },
  168. name = types.string,
  169. description = types.string,
  170. fields = {
  171. kind = types.list(types.nonNull(__Field)),
  172. arguments = {
  173. -- includeDeprecated = types.boolean
  174. includeDeprecated = { kind = types.boolean, defaultValue = false }
  175. },
  176. resolve = function(t, args)
  177. if instanceof(t, 'Object') or
  178. instanceof(t, 'Interface') then
  179. local fieldMap = t.fields;
  180. local fields = {}; for k,v in pairs(fieldMap) do table.insert(fields, fieldMap[k]) end
  181. if not args.includeDeprecated then
  182. fields = util.filter(fields, function(field) return not field.deprecationReason end);
  183. end
  184. if #fields > 0 then return fields else return cjson.empty_array end
  185. end
  186. return nil;
  187. end
  188. },
  189. interfaces = {
  190. kind = types.list(types.nonNull(__Type)),
  191. resolve = function(type)
  192. if instanceof(type, 'Object') then
  193. return type.interfaces and type.interfaces or cjson.empty_array;
  194. end
  195. end
  196. },
  197. possibleTypes = {
  198. kind = types.list(types.nonNull(__Type)),
  199. resolve = function(type, args, context, obj)
  200. if instanceof(type, 'Interface') or
  201. instanceof(type, 'Union') then
  202. return context.schema:getPossibleTypes(type);
  203. end
  204. end
  205. },
  206. enumValues = {
  207. kind = types.list(types.nonNull(__EnumValue)),
  208. arguments = {
  209. -- includeDeprecated = types.boolean
  210. includeDeprecated = { kind = types.boolean, defaultValue = false }
  211. },
  212. resolve = function(type, args)
  213. if instanceof(type, 'Enum') then
  214. local values = type.values;
  215. if not args.includeDeprecated then
  216. values = util.filter(values, function(value) return not value.deprecationReason end)
  217. end
  218. return util.values(values)
  219. end
  220. end
  221. },
  222. inputFields = {
  223. kind = types.list(types.nonNull(__InputValue)),
  224. resolve = function(type)
  225. if instanceof(type, 'InputObject') then
  226. local fieldMap = type.fields;
  227. local fields = {}
  228. for k, v in pairs(fieldMap) do
  229. table.insert(fields, fieldMap[k])
  230. end
  231. return fields
  232. end
  233. end
  234. },
  235. ofType = {
  236. kind = __Type
  237. }
  238. } end
  239. })
  240. __Field = types.object({
  241. name = '__Field',
  242. description =
  243. 'Object and Interface types are described by a list of Fields, each of ' ..
  244. 'which has a name, potentially a list of arguments, and a return type.',
  245. fields = function() return {
  246. name = types.nonNull(types.string),
  247. description = types.string,
  248. args = {
  249. -- kind = types.list(__InputValue),
  250. kind = types.nonNull(types.list(types.nonNull(__InputValue))),
  251. resolve = function(field)
  252. local args = {}
  253. local transform = function(a, n)
  254. if a.__type then
  255. return {kind = a, name = n}
  256. else
  257. if not a.name then
  258. local r = {name = n}
  259. for k,v in pairs(a) do
  260. r[k] = v
  261. end
  262. return r
  263. else
  264. return a
  265. end
  266. end
  267. end
  268. for k, v in pairs(field.arguments or {}) do table.insert(args, transform(v, k)) end
  269. -- return args
  270. if #args > 0 then return args else return cjson.empty_array end
  271. end
  272. },
  273. type = { kind = types.nonNull(__Type), resolve = function(field) return field.kind end },
  274. isDeprecated = {
  275. kind = types.nonNull(types.boolean),
  276. resolve = function(field) return not isNullish(field.deprecationReason) end
  277. },
  278. deprecationReason = types.string
  279. } end
  280. });
  281. __InputValue = types.object({
  282. name = '__InputValue',
  283. description =
  284. 'Arguments provided to Fields or Directives and the input fields of an ' ..
  285. 'InputObject are represented as Input Values which describe their type ' ..
  286. 'and optionally a default value.',
  287. fields = function() return {
  288. name = types.nonNull(types.string),
  289. description = types.string,
  290. type = { kind = types.nonNull(__Type), resolve = function(field) return field.kind end },
  291. defaultValue = {
  292. kind = types.string,
  293. description =
  294. 'A GraphQL-formatted string representing the default value for this ' ..
  295. 'input value.',
  296. resolve = function(inputVal) if isNullish(inputVal.defaultValue)
  297. then return nil
  298. else return printAst(astFromValue(inputVal.defaultValue, inputVal)) end end
  299. }
  300. } end
  301. });
  302. __EnumValue = types.object({
  303. name = '__EnumValue',
  304. description =
  305. 'One possible value for a given Enum. Enum values are unique values, not ' ..
  306. 'a placeholder for a string or numeric value. However an Enum value is ' ..
  307. 'returned in a JSON response as a string.',
  308. fields = function() return {
  309. name = types.nonNull(types.string),
  310. description = types.string,
  311. isDeprecated = {
  312. kind = types.nonNull(types.boolean),
  313. resolve = function(enumValue) return not isNullish(enumValue.deprecationReason) end
  314. },
  315. deprecationReason =
  316. types.string
  317. } end
  318. });
  319. TypeKind = {
  320. SCALAR = 'SCALAR',
  321. OBJECT = 'OBJECT',
  322. INTERFACE = 'INTERFACE',
  323. UNION = 'UNION',
  324. ENUM = 'ENUM',
  325. INPUT_OBJECT = 'INPUT_OBJECT',
  326. LIST = 'LIST',
  327. NON_NULL = 'NON_NULL'
  328. };
  329. __TypeKind = types.enum({
  330. name = '__TypeKind',
  331. description = 'An enum describing what kind of type a given `__Type` is.',
  332. values = {
  333. SCALAR = {
  334. value = TypeKind.SCALAR,
  335. description = 'Indicates this type is a scalar.'
  336. },
  337. OBJECT = {
  338. value = TypeKind.OBJECT,
  339. description = 'Indicates this type is an object. ' ..
  340. '`fields` and `interfaces` are valid fields.'
  341. },
  342. INTERFACE = {
  343. value = TypeKind.INTERFACE,
  344. description = 'Indicates this type is an interface. ' ..
  345. '`fields` and `possibleTypes` are valid fields.'
  346. },
  347. UNION = {
  348. value = TypeKind.UNION,
  349. description = 'Indicates this type is a union. ' ..
  350. '`possibleTypes` is a valid field.'
  351. },
  352. ENUM = {
  353. value = TypeKind.ENUM,
  354. description = 'Indicates this type is an enum. ' ..
  355. '`enumValues` is a valid field.'
  356. },
  357. INPUT_OBJECT = {
  358. value = TypeKind.INPUT_OBJECT,
  359. description = 'Indicates this type is an input object. ' ..
  360. '`inputFields` is a valid field.'
  361. },
  362. LIST = {
  363. value = TypeKind.LIST,
  364. description = 'Indicates this type is a list. ' ..
  365. '`ofType` is a valid field.'
  366. },
  367. NON_NULL = {
  368. value = TypeKind.NON_NULL,
  369. description = 'Indicates this type is a non-null. ' ..
  370. '`ofType` is a valid field.'
  371. }
  372. }
  373. });
  374. --
  375. -- Note that these are GraphQLFieldDefinition and not GraphQLFieldConfig,
  376. -- so the format for args is different.
  377. --
  378. SchemaMetaFieldDef = {
  379. name = '__schema',
  380. kind = types.nonNull(__Schema),
  381. description = 'Access the current type schema of this server.',
  382. arguments = {},
  383. resolve = function(source, args, context, obj) return context.schema end
  384. }
  385. TypeMetaFieldDef = {
  386. name = '__type',
  387. kind = __Type,
  388. description = 'Request the type information of a single type.',
  389. arguments = {
  390. name = types.nonNull(types.string)
  391. }
  392. --,resolve = function(source, { name } = { name = string }, context, { schema })
  393. -- return schema.getType(name) end
  394. };
  395. TypeNameMetaFieldDef = {
  396. name = '__typename',
  397. kind = types.nonNull(types.string),
  398. description = 'The name of the current Object type at runtime.',
  399. arguments = {},
  400. resolve = function(source, args, context, obj) return obj.parentType.name end
  401. };
  402. -- Produces a GraphQL Value AST given a lua value.
  403. -- Optionally, a GraphQL type may be provided, which will be used to
  404. -- disambiguate between value primitives.
  405. -- | JSON Value | GraphQL Value |
  406. -- | ------------- | -------------------- |
  407. -- | Object | Input Object |
  408. -- | Array | List |
  409. -- | Boolean | Boolean |
  410. -- | String | String / Enum Value |
  411. -- | Number | Int / Float |
  412. local Kind = {
  413. LIST = 'ListValue',
  414. BOOLEAN = 'BooleanValue',
  415. FLOAT = 'FloatValue',
  416. INT = 'IntValue',
  417. FLOAT = 'FloatValue',
  418. ENUM = 'EnumValue',
  419. STRING = 'StringValue',
  420. OBJECT_FIELD = 'ObjectField',
  421. NAME = 'Name',
  422. OBJECT = 'ObjectValue'
  423. }
  424. printers = {
  425. IntValue = function(v) return v.value end,
  426. FloatValue = function(v) return v.value end,
  427. StringValue = function(v) return cjson.encode(v.value) end,
  428. BooleanValue = function(v) return cjson.encode(v.value) end,
  429. EnumValue = function(v) return v.value end,
  430. ListValue = function(v) return '[' .. table.concat(util.map(v.values, printAst), ', ') .. ']' end,
  431. ObjectValue = function(v) return '{' .. table.concat(util.map(v.fields, printAst), ', ') .. '}' end,
  432. ObjectField = function(v) return v.name .. ': ' .. v.value end
  433. }
  434. printAst = function(v)
  435. return printers[v.kind](v)
  436. end
  437. astFromValue = function(value, tt)
  438. -- Ensure flow knows that we treat function params as const.
  439. local _value = value
  440. if instanceof(tt,'NonNull') then
  441. -- Note: we're not checking that the result is non-null.
  442. -- This function is not responsible for validating the input value.
  443. return astFromValue(_value, tt.ofType)
  444. end
  445. if isNullish(_value) then
  446. return nil
  447. end
  448. -- Convert JavaScript array to GraphQL list. If the GraphQLType is a list, but
  449. -- the value is not an array, convert the value using the list's item type.
  450. if type(_value) == 'table' and #_value > 0 then
  451. local itemType = instanceof(tt, 'List') and tt.ofType or nil
  452. return {
  453. kind = Kind.LIST,
  454. values = util.map(_value, function(item)
  455. local itemValue = astFromValue(item, itemType)
  456. assert(itemValue, 'Could not create AST item.')
  457. return itemValue
  458. end)
  459. }
  460. elseif instanceof(tt, 'List') then
  461. -- Because GraphQL will accept single values as a "list of one" when
  462. -- expecting a list, if there's a non-array value and an expected list type,
  463. -- create an AST using the list's item type.
  464. return astFromValue(_value, tt.ofType)
  465. end
  466. if type(_value) == 'boolean' then
  467. return { kind = Kind.BOOLEAN, value = _value }
  468. end
  469. -- JavaScript numbers can be Float or Int values. Use the GraphQLType to
  470. -- differentiate if available, otherwise prefer Int if the value is a
  471. -- valid Int.
  472. if type(_value) == 'number' then
  473. local stringNum = String(_value)
  474. local isIntValue = _value%1 == 0
  475. if isIntValue then
  476. if tt == types.float then
  477. return { kind = Kind.FLOAT, value = stringNum .. '.0' }
  478. end
  479. return { kind = Kind.INT, value = stringNum }
  480. end
  481. return { kind = Kind.FLOAT, value = stringNum }
  482. end
  483. -- JavaScript strings can be Enum values or String values. Use the
  484. -- GraphQLType to differentiate if possible.
  485. if type(_value) == 'string' then
  486. if instanceof(tt, 'Enum') and _value:match('/^[_a-zA-Z][_a-zA-Z0-9]*$/') then
  487. return { kind =Kind.ENUM, value = _value }
  488. end
  489. -- Use JSON stringify, which uses the same string encoding as GraphQL,
  490. -- then remove the quotes.
  491. return {
  492. kind = Kind.STRING,
  493. value = (cjson.encode(_value)):sub(1, -1)
  494. }
  495. end
  496. -- last remaining possible typeof
  497. assert(type(_value) == 'table')
  498. assert(_value ~= nil)
  499. -- Populate the fields of the input object by creating ASTs from each value
  500. -- in the JavaScript object.
  501. local fields = {}
  502. for fieldName,v in pairs(_value) do
  503. local fieldType
  504. if instanceof(tt, 'InputObject') then
  505. local fieldDef = tt.fields[fieldName];
  506. fieldType = fieldDef and fieldDef.kind;
  507. end
  508. local fieldValue = astFromValue(_value[fieldName], fieldType);
  509. if fieldValue then
  510. table.insert(fields, {
  511. kind = Kind.OBJECT_FIELD,
  512. name = { kind = Kind.NAME, value = fieldName },
  513. value = fieldValue
  514. })
  515. end
  516. end
  517. return { kind = Kind.OBJECT, fields = fields }
  518. end
  519. return {
  520. __Schema = __Schema,
  521. __Directive = __Directive,
  522. __DirectiveLocation = __DirectiveLocation,
  523. __Type = __Type,
  524. __Field = __Field,
  525. __EnumValue = __EnumValue,
  526. TypeKind = TypeKind,
  527. __TypeKind = __TypeKind,
  528. SchemaMetaFieldDef = SchemaMetaFieldDef,
  529. TypeMetaFieldDef = TypeMetaFieldDef,
  530. TypeNameMetaFieldDef = TypeNameMetaFieldDef
  531. }