Skip to content
New issue

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

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

Already on GitHub? # to your account

fix(JSONObject): Throw proper error if literal is not an object #2284

Merged
merged 2 commits into from
Mar 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
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"],
]
`;