UNPKG

2.02 kBJavaScriptView Raw
1import { parse } from 'graphql';
2export const asArray = (fns) => (Array.isArray(fns) ? fns : fns ? [fns] : []);
3const invalidDocRegex = /\.[a-z0-9]+$/i;
4export 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}
23const invalidPathRegex = /[‘“!%^<>`\n]/;
24/**
25 * Checkes whether the `str` contains any path illegal characters.
26 *
27 * A string may sometimes look like a path but is not (like an SDL of a simple
28 * GraphQL schema). To make sure we don't yield false-positives in such cases,
29 * we disallow new lines in paths (even though most Unix systems support new
30 * lines in file names).
31 */
32export function isValidPath(str) {
33 return typeof str === 'string' && !invalidPathRegex.test(str);
34}
35export function compareStrings(a, b) {
36 if (String(a) < String(b)) {
37 return -1;
38 }
39 if (String(a) > String(b)) {
40 return 1;
41 }
42 return 0;
43}
44export function nodeToString(a) {
45 let name;
46 if ('alias' in a) {
47 name = a.alias?.value;
48 }
49 if (name == null && 'name' in a) {
50 name = a.name?.value;
51 }
52 if (name == null) {
53 name = a.kind;
54 }
55 return name;
56}
57export function compareNodes(a, b, customFn) {
58 const aStr = nodeToString(a);
59 const bStr = nodeToString(b);
60 if (typeof customFn === 'function') {
61 return customFn(aStr, bStr);
62 }
63 return compareStrings(aStr, bStr);
64}
65export function isSome(input) {
66 return input != null;
67}
68export function assertSome(input, message = 'Value should be something') {
69 if (input == null) {
70 throw new Error(message);
71 }
72}