helpers.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import { parse } from 'graphql';
  2. export const asArray = (fns) => (Array.isArray(fns) ? fns : fns ? [fns] : []);
  3. const invalidDocRegex = /\.[a-z0-9]+$/i;
  4. export function isDocumentString(str) {
  5. if (typeof str !== 'string') {
  6. return false;
  7. }
  8. // XXX: is-valid-path or is-glob treat SDL as a valid path
  9. // (`scalar Date` for example)
  10. // this why checking the extension is fast enough
  11. // and prevent from parsing the string in order to find out
  12. // if the string is a SDL
  13. if (invalidDocRegex.test(str)) {
  14. return false;
  15. }
  16. try {
  17. parse(str);
  18. return true;
  19. }
  20. catch (e) { }
  21. return false;
  22. }
  23. const invalidPathRegex = /[‘“!%^<=>`]/;
  24. export function isValidPath(str) {
  25. return typeof str === 'string' && !invalidPathRegex.test(str);
  26. }
  27. export function compareStrings(a, b) {
  28. if (String(a) < String(b)) {
  29. return -1;
  30. }
  31. if (String(a) > String(b)) {
  32. return 1;
  33. }
  34. return 0;
  35. }
  36. export function nodeToString(a) {
  37. var _a, _b;
  38. let name;
  39. if ('alias' in a) {
  40. name = (_a = a.alias) === null || _a === void 0 ? void 0 : _a.value;
  41. }
  42. if (name == null && 'name' in a) {
  43. name = (_b = a.name) === null || _b === void 0 ? void 0 : _b.value;
  44. }
  45. if (name == null) {
  46. name = a.kind;
  47. }
  48. return name;
  49. }
  50. export function compareNodes(a, b, customFn) {
  51. const aStr = nodeToString(a);
  52. const bStr = nodeToString(b);
  53. if (typeof customFn === 'function') {
  54. return customFn(aStr, bStr);
  55. }
  56. return compareStrings(aStr, bStr);
  57. }
  58. export function isSome(input) {
  59. return input != null;
  60. }
  61. export function assertSome(input, message = 'Value should be something') {
  62. if (input == null) {
  63. throw new Error(message);
  64. }
  65. }