Skip to content

feat(isValidGraphQLQuery): add validation for graphQl queries and test #2569

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ yarn.lock
/index.js
validator.js
validator.min.js
.idea

1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ Validator | Description
**isFQDN(str [, options])** | check if the string is a fully qualified domain name (e.g. domain.com).<br/><br/>`options` is an object which defaults to `{ require_tld: true, allow_underscores: false, allow_trailing_dot: false, allow_numeric_tld: false, allow_wildcard: false, ignore_max_length: false }`.<br/><br/>`require_tld` - If set to false the validator will not check if the domain includes a TLD.<br/>`allow_underscores` - if set to true, the validator will allow underscores in the domain.<br/>`allow_trailing_dot` - if set to true, the validator will allow the domain to end with a `.` character.<br/>`allow_numeric_tld` - if set to true, the validator will allow the TLD of the domain to be made up solely of numbers.<br />`allow_wildcard` - if set to true, the validator will allow domains starting with `*.` (e.g. `*.example.com` or `*.shop.example.com`).<br/>`ignore_max_length` - if set to true, the validator will not check for the standard max length of a domain.<br/>
**isFreightContainerID(str)** | alias for `isISO6346`, check if the string is a valid [ISO 6346](https://en.wikipedia.org/wiki/ISO_6346) shipping container identification.
**isFullWidth(str)** | check if the string contains any full-width chars.
**isValidGraphQLQuery(str)** | check if the string is valid graphql query (note: uses parse function from graphql package).
**isHalfWidth(str)** | check if the string contains any half-width chars.
**isHash(str, algorithm)** | check if the string is a hash of type algorithm.<br/><br/>Algorithm is one of `['crc32', 'crc32b', 'md4', 'md5', 'ripemd128', 'ripemd160', 'sha1', 'sha256', 'sha384', 'sha512', 'tiger128', 'tiger160', 'tiger192']`.
**isHexadecimal(str)** | check if the string is a hexadecimal number.
Expand Down
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,13 @@
"build:node": "babel src -d .",
"build": "run-p build:*",
"pretest": "npm run build && npm run lint",
"test": "nyc --reporter=cobertura --reporter=text-summary mocha --require @babel/register --reporter dot --recursive"
"test": "nyc --reporter=cobertura --reporter=text-summary mocha --require @babel/register --require ./test/setup.js --reporter dot --recursive"
},
"engines": {
"node": ">= 0.10"
},
"license": "MIT"
"license": "MIT",
"dependencies": {
"graphql": "^16.11.0"
}
}
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ import isLicensePlate from './lib/isLicensePlate';
import isStrongPassword from './lib/isStrongPassword';

import isVAT from './lib/isVAT';
import isValidGraphQLQuery from './lib/isValidGraphQLQuery';

const version = '13.15.15';

Expand Down Expand Up @@ -245,6 +246,7 @@ const validator = {
isLicensePlate,
isVAT,
ibanLocales,
isValidGraphQLQuery,
};

export default validator;
42 changes: 42 additions & 0 deletions src/lib/isValidGraphQLQuery.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import assertString from './util/assertString';

let isGraphQLAvailable = false;
let parseFunction = null;

// Attempt to load GraphQL parse function
/* istanbul ignore if */
if (typeof process === 'undefined' || !process.versions || !process.versions.node) {
// Skip initialization in non-Node environments
} else {
const nodeVersion = process.versions.node.split('.')[0];
/* istanbul ignore else */
if (parseInt(nodeVersion, 10) >= 10) {
try {
// eslint-disable-next-line global-require
const { parse } = require('graphql');
parseFunction = parse;
isGraphQLAvailable = true;
} catch (e) {
/* istanbul ignore next */
// GraphQL loading failed
isGraphQLAvailable = false;
}
}
}

export default function isValidGraphQLQuery(input) {
assertString(input);

/* istanbul ignore if */
if (!isGraphQLAvailable || !parseFunction) {
/* istanbul ignore next */
return false;
}

try {
const obj = parseFunction(input);
return (!!obj && typeof obj === 'object');
} catch (e) {
return false;
}
}
14 changes: 14 additions & 0 deletions test/setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Polyfill for globalThis (needed for Node < 12)
if (typeof globalThis === 'undefined') {
(function () {
if (typeof global !== 'undefined') {
global.globalThis = global;
} else if (typeof window !== 'undefined') {
window.globalThis = window;
} else if (typeof self !== 'undefined') {
self.globalThis = self;
} else {
throw new Error('Unable to locate global object');
}
}());
}
38 changes: 36 additions & 2 deletions test/validators.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -7140,8 +7140,15 @@ describe('Validators', () => {
it('should define the module using an AMD-compatible loader', () => {
let window = {
validator: null,
define(module) {
window.validator = module();
define(deps, factory) {
// Handle AMD define with dependencies
if (Array.isArray(deps) && typeof factory === 'function') {
// Mock the graphql dependency as null/undefined since it's optional
window.validator = factory(null);
} else if (typeof deps === 'function') {
// Handle define without dependencies
window.validator = deps();
}
},
};
window.define.amd = true;
Expand Down Expand Up @@ -15652,4 +15659,31 @@ describe('Validators', () => {
],
});
});
it('should validate graphQL', () => {
// Skip test on Node.js < 10 due to graphql module incompatibility
const nodeVersion = parseInt(process.version.match(/^v(\d+)/)[1], 10);
if (nodeVersion < 10) {
console.log(' ⚠️ Skipping GraphQL test on Node.js', process.version);
return;
}

test({
validator: 'isValidGraphQLQuery',
valid: [
'query StudentName {\n' +
' student {\n' +
' name\n' +
' }\n' +
' }',
],
invalid: [
'query StudentName {\n'
+ ' student {\n'
+ ' name\n'
+ ' }',
'null',
'2432',
],
});
});
});