stub.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { GraphQLObjectType, GraphQLInterfaceType, GraphQLInputObjectType, GraphQLString, GraphQLInt, GraphQLFloat, GraphQLBoolean, GraphQLID, Kind, GraphQLList, GraphQLNonNull, } from 'graphql';
  2. export function createNamedStub(name, type) {
  3. let constructor;
  4. if (type === 'object') {
  5. constructor = GraphQLObjectType;
  6. }
  7. else if (type === 'interface') {
  8. constructor = GraphQLInterfaceType;
  9. }
  10. else {
  11. constructor = GraphQLInputObjectType;
  12. }
  13. return new constructor({
  14. name,
  15. fields: {
  16. _fake: {
  17. type: GraphQLString,
  18. },
  19. },
  20. });
  21. }
  22. export function createStub(node, type) {
  23. switch (node.kind) {
  24. case Kind.LIST_TYPE:
  25. return new GraphQLList(createStub(node.type, type));
  26. case Kind.NON_NULL_TYPE:
  27. return new GraphQLNonNull(createStub(node.type, type));
  28. default:
  29. if (type === 'output') {
  30. return createNamedStub(node.name.value, 'object');
  31. }
  32. return createNamedStub(node.name.value, 'input');
  33. }
  34. }
  35. export function isNamedStub(type) {
  36. if ('getFields' in type) {
  37. const fields = type.getFields();
  38. // eslint-disable-next-line no-unreachable-loop
  39. for (const fieldName in fields) {
  40. const field = fields[fieldName];
  41. return field.name === '_fake';
  42. }
  43. }
  44. return false;
  45. }
  46. export function getBuiltInForStub(type) {
  47. switch (type.name) {
  48. case GraphQLInt.name:
  49. return GraphQLInt;
  50. case GraphQLFloat.name:
  51. return GraphQLFloat;
  52. case GraphQLString.name:
  53. return GraphQLString;
  54. case GraphQLBoolean.name:
  55. return GraphQLBoolean;
  56. case GraphQLID.name:
  57. return GraphQLID;
  58. default:
  59. return type;
  60. }
  61. }