transformInputValue.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import { getNullableType, isLeafType, isListType, isInputObjectType } from 'graphql';
  2. export function transformInputValue(type, value, inputLeafValueTransformer = null, inputObjectValueTransformer = null) {
  3. if (value == null) {
  4. return value;
  5. }
  6. const nullableType = getNullableType(type);
  7. if (isLeafType(nullableType)) {
  8. return inputLeafValueTransformer != null ? inputLeafValueTransformer(nullableType, value) : value;
  9. }
  10. else if (isListType(nullableType)) {
  11. return value.map((listMember) => transformInputValue(nullableType.ofType, listMember, inputLeafValueTransformer, inputObjectValueTransformer));
  12. }
  13. else if (isInputObjectType(nullableType)) {
  14. const fields = nullableType.getFields();
  15. const newValue = {};
  16. for (const key in value) {
  17. const field = fields[key];
  18. if (field != null) {
  19. newValue[key] = transformInputValue(field.type, value[key], inputLeafValueTransformer, inputObjectValueTransformer);
  20. }
  21. }
  22. return inputObjectValueTransformer != null ? inputObjectValueTransformer(nullableType, newValue) : newValue;
  23. }
  24. // unreachable, no other possible return value
  25. }
  26. export function serializeInputValue(type, value) {
  27. return transformInputValue(type, value, (t, v) => {
  28. try {
  29. return t.serialize(v);
  30. }
  31. catch (_a) {
  32. return v;
  33. }
  34. });
  35. }
  36. export function parseInputValue(type, value) {
  37. return transformInputValue(type, value, (t, v) => {
  38. try {
  39. return t.parseValue(v);
  40. }
  41. catch (_a) {
  42. return v;
  43. }
  44. });
  45. }
  46. export function parseInputValueLiteral(type, value) {
  47. return transformInputValue(type, value, (t, v) => t.parseLiteral(v, {}));
  48. }