Skip to content

Commit

Permalink
[MS-759] feat: Add unittest
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrgrundas committed Oct 8, 2024
1 parent 2aa7051 commit 84b50b2
Show file tree
Hide file tree
Showing 2 changed files with 280 additions and 4 deletions.
267 changes: 267 additions & 0 deletions src/lib/graphql/validate.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,267 @@
import { Kind, type SelectionSetNode } from "graphql";
import { describe, expect, it } from "vitest";

import {
extractFieldsFromAST,
validateDocumentAgainstData,
validatePayload,
ValidationError,
} from "./validate";

describe("extractFieldsFromAST", () => {
it("should extract scalar fields", () => {
// given
const selectionSet = {
kind: Kind.SELECTION_SET,
selections: [
{ kind: Kind.FIELD, name: { value: "id" } },
{ kind: Kind.FIELD, name: { value: "name" } },
],
} as any as SelectionSetNode;

// when
const fields = extractFieldsFromAST(selectionSet);

// then
expect(fields).toEqual({
id: { type: "scalar" },
name: { type: "scalar" },
});
});

it("should extract nested object fields", () => {
// given
const selectionSet = {
kind: Kind.SELECTION_SET,
selections: [
{
kind: Kind.FIELD,
name: { value: "user" },
selectionSet: {
kind: Kind.SELECTION_SET,
selections: [
{ kind: Kind.FIELD, name: { value: "id" } },
{ kind: Kind.FIELD, name: { value: "email" } },
],
},
},
],
} as any as SelectionSetNode;

// when
const fields = extractFieldsFromAST(selectionSet);

// then
expect(fields).toEqual({
user: {
type: "object",
selectionSet: {
id: { type: "scalar" },
email: { type: "scalar" },
},
},
});
});

it("should merge inline fragment fields", () => {
// given
const selectionSet = {
kind: Kind.SELECTION_SET,
selections: [
{
kind: Kind.INLINE_FRAGMENT,
selectionSet: {
kind: Kind.SELECTION_SET,
selections: [
{ kind: Kind.FIELD, name: { value: "id" } },
{ kind: Kind.FIELD, name: { value: "name" } },
],
},
},
],
} as any as SelectionSetNode;

// when
const fields = extractFieldsFromAST(selectionSet);

// then
expect(fields).toEqual({
id: { type: "scalar" },
name: { type: "scalar" },
});
});
});

describe("validatePayload", () => {
it("should validate payload with scalar fields", () => {
// given
const fields = {
id: { type: "scalar" },
name: { type: "scalar" },
};
const payload = { id: "123", name: "John" };

// when/then
expect(() => validatePayload(payload, fields)).not.toThrow();
});

it("should throw error for missing fields", () => {
// given
const fields = {
id: { type: "scalar" },
name: { type: "scalar" },
};
const payload = { id: "123" };

// when/then
expect(() => validatePayload(payload, fields)).toThrow(ValidationError);
});

it("should throw error for extra fields", () => {
// given
const fields = {
id: { type: "scalar" },
name: { type: "scalar" },
};
const payload = { id: "123", name: "John", age: 30 };

// when/then
expect(() => validatePayload(payload, fields)).toThrow(ValidationError);
});

it("should validate nested object fields", () => {
// given
const fields = {
user: {
type: "object",
selectionSet: {
id: { type: "scalar" },
email: { type: "scalar" },
},
},
};
const payload = { user: { id: "1", email: "test@example.com" } };

// when/then
expect(() => validatePayload(payload, fields)).not.toThrow();
});

it("should throw error for invalid nested fields", () => {
// given
const fields = {
user: {
type: "object",
selectionSet: {
id: { type: "scalar" },
email: { type: "scalar" },
},
},
};
const payload = { user: { id: "1" } };

// when/then
expect(() => validatePayload(payload, fields)).toThrow(ValidationError);
});
});

describe("validateDocumentAgainstData", () => {
const document = `
query TestSubscription {
event {
id
name
user {
id
email
}
}
}
`;

it("should validate matching data against the document", () => {
// given
const data = {
id: "1",
name: "Event",
user: {
id: "1",
email: "user@example.com",
},
};

// when
const result = validateDocumentAgainstData({
document,
data,
});

// then
expect(result.isValid).toBe(true);
expect(result.error).toBeNull();
});

it("should return error for missing fields", () => {
// given
const data = {
id: "1",
user: {
id: "1",
email: "user@example.com",
},
};

// when
const result = validateDocumentAgainstData({
document,
data,
});

// then
expect(result.isValid).toBe(false);
expect(result.error).toBe("Missing field: name.");
});

it("should return error for extra fields", () => {
// given
const data = {
id: "1",
name: "Event",
extraField: "extra",
user: {
id: "1",
email: "user@example.com",
},
};

// when
const result = validateDocumentAgainstData({
document,
data,
});

// then
expect(result.isValid).toBe(false);
expect(result.error).toBe("Invalid field: extraField.");
});

it("should return error if root field not found", () => {
// given
const documentWithoutRootField = `
query {
otherRoot {
id
}
}
`;

// when
const result = validateDocumentAgainstData({
document: documentWithoutRootField,
data: {},
});

// then
expect(result.isValid).toBe(false);
expect(result.error).toBe("Cannot find root field.");
});
});
17 changes: 13 additions & 4 deletions src/lib/graphql/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import {
import { BaseError } from "../errors";
import { type TypedDocumentTypeDecoration } from "./types";

export class ValidationError extends BaseError {}

type FieldInfo = {
selectionSet?: FieldMap;
type?: any;
Expand All @@ -18,7 +20,9 @@ type FieldMap = {
[key: string]: FieldInfo;
};

const extractFieldsFromAST = (selectionSet: SelectionSetNode): FieldMap => {
export const extractFieldsFromAST = (
selectionSet: SelectionSetNode
): FieldMap => {
const fields: FieldMap = {};

selectionSet.selections.forEach((selection) => {
Expand All @@ -43,9 +47,12 @@ const extractFieldsFromAST = (selectionSet: SelectionSetNode): FieldMap => {

return fields;
};
class ValidationError extends BaseError {}

const validatePayload = (payload: any, fields: FieldMap, path: string = "") => {
export const validatePayload = (
payload: any,
fields: FieldMap,
path: string = ""
) => {
// Ensure that the payload does not have any extra fields
for (const fieldName of Object.keys(payload)) {
// Skip __typename field
Expand All @@ -54,7 +61,9 @@ const validatePayload = (payload: any, fields: FieldMap, path: string = "") => {
}

if (!(fieldName in fields)) {
throw new ValidationError(`Invalid field: ${path}.${fieldName}.`);
const newPath = path ? `${path}.${fieldName}` : fieldName;

throw new ValidationError(`Invalid field: ${newPath}.`);
}
}

Expand Down

0 comments on commit 84b50b2

Please sign in to comment.