Skip to content
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

support custom scalar type when using fast-json-stringify serializer #236

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@
"eslint": "^8.49.0",
"eslint-config-prettier": "^9.0.0",
"graphql": "^16.8.0",
"graphql-scalars": "^1.22.4",
"jest": "^29.7.0",
"lint-staged": "^14.0.1",
"prettier": "^3.0.3",
Expand Down
9 changes: 9 additions & 0 deletions src/__tests__/__snapshots__/json.test.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,15 @@ exports[`json schema creator json schema creation 1`] = `
"author": {
"nullable": false,
"properties": {
"email": {
"nullable": true,
"type": "string",
},
"extra": {
"additionalProperties": true,
"nullable": true,
"type": "object",
},
"id": {
"nullable": false,
"type": "string",
Expand Down
29 changes: 25 additions & 4 deletions src/__tests__/json.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ import {
GraphQLString,
parse,
GraphQLInt,
versionInfo
versionInfo,
GraphQLScalarType
} from "graphql";
import { GraphQLEmailAddress, GraphQLJSONObject } from "graphql-scalars";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In GraphQL Scalars, most of the scalars have jsonSchema defined in the extensions;
https://github.com/Urigo/graphql-scalars/blob/master/src/scalars/EmailAddress.ts#L46
This might be helpful for you.

import { buildExecutionContext } from "graphql/execution/execute";
import { compileQuery } from "../index";
import { queryToJSONSchema } from "../json";
Expand All @@ -36,6 +38,12 @@ describe("json schema creator", () => {
},
recentArticle: {
type: BlogArticle
},
email: {
type: GraphQLEmailAddress
},
extra: {
type: GraphQLJSONObject
}
})
});
Expand Down Expand Up @@ -83,7 +91,11 @@ describe("json schema creator", () => {
isPublished: true,
author: {
id: 123,
name: "John Smith"
name: "John Smith",
email: "[email protected]",
extra: {
foo: "bar"
}
},
title: "My Article " + id,
body: "This is a post",
Expand All @@ -106,6 +118,8 @@ describe("json schema creator", () => {
author {
id
name
email
extra
pic(width: 640, height: 480) {
url
width
Expand Down Expand Up @@ -137,7 +151,10 @@ describe("json schema creator", () => {
})
: (buildExecutionContext as any)(blogSchema, document);
context.options = {};
const jsonSchema = queryToJSONSchema(context);
const jsonSchema = queryToJSONSchema(context, {
EmailAddress: "string",
JSONObject: "object"
});
test("json schema creation", () => {
expect(jsonSchema).toMatchSnapshot();
});
Expand All @@ -148,7 +165,11 @@ describe("json schema creator", () => {
});
test("valid response serialization", async () => {
const prepared: any = compileQuery(blogSchema, document, "", {
customJSONSerializer: true
customJSONSerializer: true,
customJSONSerializerScalarTypes: {
EmailAddress: "string",
JSONObject: "object"
}
});
const response = await prepared.query(undefined, undefined, {});
expect(prepared.stringify).not.toBe(JSON.stringify);
Expand Down
10 changes: 8 additions & 2 deletions src/execution.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ import {
} from "./ast";
import { GraphQLError as GraphqlJitError } from "./error";
import createInspect from "./inspect";
import { queryToJSONSchema } from "./json";
import { CustomScalarTypes, queryToJSONSchema } from "./json";
import { createNullTrimmer, NullTrimmer } from "./non-null";
import {
createResolveInfoThunk,
Expand All @@ -70,6 +70,9 @@ const inspect = createInspect();
export interface CompilerOptions {
customJSONSerializer: boolean;

// To support serializing custom scalar type using fast-json-stringify
customJSONSerializerScalarTypes?: CustomScalarTypes;

// Disable builtin scalars and enum serialization
// which is responsible for coercion,
// only safe for use if the output is completely correct.
Expand Down Expand Up @@ -254,7 +257,10 @@ export function compileQuery<

let stringify: (v: any) => string;
if (options.customJSONSerializer) {
const jsonSchema = queryToJSONSchema(context);
const jsonSchema = queryToJSONSchema(
context,
options.customJSONSerializerScalarTypes
);
stringify = fastJson(jsonSchema);
} else {
stringify = JSON.stringify;
Expand Down
53 changes: 44 additions & 9 deletions src/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,14 +40,24 @@ const PRIMITIVES: {
ID: "string"
};

export type CustomScalarTypes = {
[key: string]:
| IntegerSchema["type"]
| NumberSchema["type"]
| StringSchema["type"]
| BooleanSchema["type"]
| ObjectSchema["type"];
};

/**
* GQL -> JSON Schema transform
*
* @param compilationContext
* @return {object} A plain JavaScript object which conforms to JSON Schema
*/
export function queryToJSONSchema(
compilationContext: CompilationContext
compilationContext: CompilationContext,
customScalarTypes?: CustomScalarTypes
): Schema {
const type = getOperationRootType(
compilationContext.schema,
Expand Down Expand Up @@ -75,7 +85,8 @@ export function queryToJSONSchema(
fieldProperties[responseName] = transformNode(
compilationContext,
fields[responseName],
fieldType.type
fieldType.type,
customScalarTypes
);
}
return {
Expand Down Expand Up @@ -125,7 +136,8 @@ export function queryToJSONSchema(
function transformNode(
compilationContext: CompilationContext,
fieldNodes: FieldNode[],
type: GraphQLType
type: GraphQLType,
customScalarTypes?: CustomScalarTypes
): Exclude<Schema, RefSchema> {
if (isObjectType(type)) {
const subfields = collectSubfields(compilationContext, type, fieldNodes);
Expand All @@ -144,7 +156,8 @@ function transformNode(
properties[responseName] = transformNode(
compilationContext,
subfields[responseName],
fieldType.type
fieldType.type,
customScalarTypes
);
}
return {
Expand All @@ -156,12 +169,22 @@ function transformNode(
if (isListType(type)) {
return {
type: "array",
items: transformNode(compilationContext, fieldNodes, type.ofType),
items: transformNode(
compilationContext,
fieldNodes,
type.ofType,
customScalarTypes
),
nullable: true
};
}
if (isNonNullType(type)) {
const nullable = transformNode(compilationContext, fieldNodes, type.ofType);
const nullable = transformNode(
compilationContext,
fieldNodes,
type.ofType,
customScalarTypes
);
nullable.nullable = false;
return nullable;
}
Expand All @@ -172,19 +195,31 @@ function transformNode(
};
}
if (isScalarType(type)) {
const jsonSchemaType = PRIMITIVES[type.name];
const jsonSchemaType =
PRIMITIVES[type.name] ?? customScalarTypes?.[type.name];
if (!jsonSchemaType) {
throw new Error(`Got unexpected PRIMITIVES type: ${type.name}`);
}

const additionalProperties =
jsonSchemaType.toString() === "object"
? { additionalProperties: true }
: undefined;
return {
type: jsonSchemaType,
nullable: true
nullable: true,
...additionalProperties
};
}
if (isAbstractType(type)) {
return compilationContext.schema.getPossibleTypes(type).reduce(
(res, t) => {
const jsonSchema = transformNode(compilationContext, fieldNodes, t);
const jsonSchema = transformNode(
compilationContext,
fieldNodes,
t,
customScalarTypes
);
(res as ObjectSchema).properties = {
...(res as ObjectSchema).properties,
...(jsonSchema as ObjectSchema).properties
Expand Down
7 changes: 7 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2843,6 +2843,13 @@ graphemer@^1.4.0:
resolved "https://registry.yarnpkg.com/graphemer/-/graphemer-1.4.0.tgz#fb2f1d55e0e3a1849aeffc90c4fa0dd53a0e66c6"
integrity sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==

graphql-scalars@^1.22.4:
version "1.22.4"
resolved "https://registry.yarnpkg.com/graphql-scalars/-/graphql-scalars-1.22.4.tgz#af092b142bcfd5c1f8c53cb70ee1955ecd4ddb03"
integrity sha512-ILnv7jq5VKHLUyoaTFX7lgYrjCd6vTee9i8/B+D4zJKJT5TguOl0KkpPEbXHjmeor8AZYrVsrYUHdqRBMX1pjA==
dependencies:
tslib "^2.5.0"

graphql@^16.8.0:
version "16.8.1"
resolved "https://registry.yarnpkg.com/graphql/-/graphql-16.8.1.tgz#1930a965bef1170603702acdb68aedd3f3cf6f07"
Expand Down
Loading