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

POC: nested input support #452

Closed
wants to merge 1 commit into from
Closed
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
99 changes: 99 additions & 0 deletions src/resolvers/convert-arg.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import { ArgParamMetadata, ClassMetadata } from "../metadata/definitions";
import { convertToType } from "../helpers/types";
import { ArgsDictionary } from "../interfaces";
import { ClassType } from "../interfaces/ClassType";
import { getMetadataStorage } from "../metadata/getMetadataStorage";

interface InputTypeField {
name: string;
fields?: InputTypeClass;
isArray?: boolean;
}

interface InputTypeClass {
target: ClassType;
fields: InputTypeField[];
}

const generatedTrees = new Map<ClassType, InputTypeClass | null>();

function getInputType(target: ClassType): ClassMetadata | undefined {
return getMetadataStorage().inputTypes.find(t => t.target === target);
}

function generateTree(param: ArgParamMetadata): InputTypeClass | null {
const target = param.getType() as ClassType;

if (generatedTrees.has(target)) {
return generatedTrees.get(target) as InputTypeClass;
}

const inputType = getInputType(target);

if (!inputType) {
generatedTrees.set(target, null);

return null;
}

const generate = (meta: ClassMetadata): InputTypeClass => {
const value: InputTypeClass = {
target: meta.target as ClassType,
fields: (meta.fields || []).map(field => {
const fieldInputType = getInputType(field.getType() as ClassType);

return {
name: field.name,
fields: fieldInputType ? generate(fieldInputType) : undefined,
isArray: field.typeOptions.array === true,
};
}),
};

const superPrototype = Object.getPrototypeOf(meta.target);
if (superPrototype) {
const superInputType = getInputType(superPrototype);
if (superInputType) {
value.fields = value.fields.concat(generate(superInputType).fields);
}
}

return value;
};

const tree = generate(inputType);

generatedTrees.set(target, tree);

return tree;
}

function convertToInput(tree: InputTypeClass, data?: any) {
const input = new tree.target();

tree.fields.forEach(field => {
if (typeof field.fields !== "undefined") {
const siblings = field.fields;

if (field.isArray) {
input[field.name] = (data[field.name] || []).map((value: any) =>
convertToInput(siblings, value),
);
} else {
input[field.name] = convertToInput(siblings, data[field.name]);
}
} else {
input[field.name] = data[field.name];
}
});

return input;
}

export function convertToArg(param: ArgParamMetadata, args: ArgsDictionary) {
const tree = generateTree(param);

return tree
? convertToInput(tree, args[param.name])
: convertToType(param.getType(), args[param.name]);
}
4 changes: 2 additions & 2 deletions src/resolvers/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { PubSubEngine } from "graphql-subscriptions";
import { ValidatorOptions } from "class-validator";

import { ParamMetadata } from "../metadata/definitions";
import { convertToType } from "../helpers/types";
import { validateArg } from "./validate-arg";
import { ResolverData, AuthChecker, AuthMode } from "../interfaces";
import { Middleware, MiddlewareFn, MiddlewareClass } from "../interfaces/Middleware";
import { IOCContainer } from "../utils/container";
import { AuthMiddleware } from "../helpers/auth-middleware";
import { convertToArg } from "./convert-arg";

export async function getParams(
params: ParamMetadata[],
Expand All @@ -28,7 +28,7 @@ export async function getParams(
);
case "arg":
return await validateArg(
convertToType(paramInfo.getType(), resolverData.args[paramInfo.name]),
convertToArg(paramInfo, resolverData.args),
globalValidate,
paramInfo.validate,
);
Expand Down
79 changes: 79 additions & 0 deletions tests/functional/resolvers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2053,4 +2053,83 @@ describe("Resolvers", () => {
expect(thisVar).toBeInstanceOf(childResolver);
});
});

it("nested inputs", async () => {
getMetadataStorage().clear();

@InputType()
class NestedBaseInput {
@Field()
nestedBaseInputField: string;
}

@InputType()
class SampleBaseInput {
@Field()
baseInputField: string;

@Field()
nestedBaseInputField: NestedBaseInput;

@Field(() => [NestedBaseInput])
nestedBaseInputFieldArray: NestedBaseInput[];
}

@InputType()
class NestedInput {
@Field()
inputField: string;
}

@InputType()
class SampleInput extends SampleBaseInput {
@Field()
nested: NestedInput;

@Field(() => [NestedInput])
nestedArray: NestedInput[];
}

let input: SampleInput | undefined;

@Resolver()
class SampleResolver {
@Query()
sampleQuery(@Arg("input") i: SampleInput): string {
input = i;

return "sampleQuery";
}
}

const schema = await buildSchema({ resolvers: [SampleResolver] });

const query = `query {
sampleQuery(input: {
baseInputField: "base input field"
nestedBaseInputField: { nestedBaseInputField: "nested base input field value" }
nestedBaseInputFieldArray: [{ nestedBaseInputField: "nested base input field value" }]
nested: { inputField: "value 1" }
nestedArray: [{ inputField: "value 2" }]
})
}`;

await graphql(schema, query);

expect(input).toBeInstanceOf(SampleInput);
expect((input as SampleInput).nested).toBeInstanceOf(NestedInput);
expect((input as SampleInput).baseInputField).toBe("base input field");
expect((input as SampleInput).nestedBaseInputField).toBeInstanceOf(NestedBaseInput);
expect((input as SampleInput).nestedBaseInputField.nestedBaseInputField).toBe(
"nested base input field value",
);
expect((input as SampleInput).nestedBaseInputFieldArray).toHaveLength(1);
expect((input as SampleInput).nestedBaseInputFieldArray[0]).toBeInstanceOf(NestedBaseInput);
expect((input as SampleInput).nestedBaseInputFieldArray[0].nestedBaseInputField).toBe(
"nested base input field value",
);
expect((input as SampleInput).nestedArray).toHaveLength(1);
expect((input as SampleInput).nestedArray[0]).toBeInstanceOf(NestedInput);
expect((input as SampleInput).nestedArray[0].inputField).toBe("value 2");
});
});