Skip to content

Commit

Permalink
fix(JSONObject): Throw proper error if literal is not an object (#2284)
Browse files Browse the repository at this point in the history
* JSONObject: Throw proper error if literal is not an object

* Changeset

---------

Co-authored-by: Arda TANRIKULU <ardatanrikulu@gmail.com>
  • Loading branch information
tjenkinson and ardatan authored Mar 18, 2024
1 parent 854c05f commit fae46bb
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/hip-games-glow.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'graphql-scalars': patch
---

fix(JSONObject): Throw proper error if literal is not an object
15 changes: 13 additions & 2 deletions src/scalars/json/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Kind, ValueNode, ObjectValueNode } from 'graphql';
import { Kind, print, ValueNode } from 'graphql';
import { createGraphQLError } from '../../error.js';

export function identity<T>(value: T): T {
Expand All @@ -21,7 +21,18 @@ export function ensureObject(value: any, ast?: ValueNode): object {
return value;
}

export function parseObject(ast: ObjectValueNode, variables: any): any {
export function parseObject(ast: ValueNode, variables: any): any {
if (ast.kind !== Kind.OBJECT) {
throw createGraphQLError(
`JSONObject cannot represent non-object value: ${print(ast)}`,
ast
? {
nodes: ast,
}
: undefined,
);
}

const value = Object.create(null);
ast.fields.forEach(field => {
// eslint-disable-next-line no-use-before-define
Expand Down
1 change: 1 addition & 0 deletions tests/JSON.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@ describe('GraphQLJSONObject', () => {
}).then(({ data, errors }) => {
expect(data).toBeUndefined();
expect(errors).toBeDefined();
expect(errors).toMatchSnapshot();
}));

it('should reject array literal', () =>
Expand Down
7 changes: 7 additions & 0 deletions tests/__snapshots__/JSON.test.ts.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`GraphQLJSONObject parseLiteral should reject string literal 1`] = `
[
[GraphQLError: JSONObject cannot represent non-object value: "foo"],
]
`;

0 comments on commit fae46bb

Please sign in to comment.