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

fix-get-parent-properties #2017

Merged
merged 6 commits into from
Sep 14, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
30 changes: 21 additions & 9 deletions packages/typespec-ts/src/modular/helpers/operationHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,11 +156,11 @@ export function getDeserializePrivateFunction(
response.type.format
)}`
);
} else if (response?.type?.properties) {
} else if (getAllProperties(response?.type).length > 0) {
statements.push(
`return {`,
getResponseMapping(
response.type.properties ?? [],
getAllProperties(response.type) ?? [],
"result.body",
importSet
).join(","),
Expand All @@ -187,7 +187,7 @@ function getOperationSignatureParameters(
OptionalKind<ParameterDeclarationStructure>
> = new Map();
if (operation.bodyParameter?.type.type === "model") {
(operation.bodyParameter?.type.properties ?? [])
(getAllProperties(operation.bodyParameter?.type) ?? [])
.filter((p) => !p.optional)
.filter((p) => !p.readonly)
.map((p) => buildType(p.clientName, p.type, p.format))
Expand Down Expand Up @@ -363,7 +363,7 @@ function buildBodyParameter(

if (bodyParameter.type.type === "model") {
const bodyParts: string[] = [];
for (const param of bodyParameter?.type.properties?.filter(
for (const param of getAllProperties(bodyParameter?.type).filter(
(p) => !p.readonly
) ?? []) {
if (param.type.type === "model" && isRequired(param)) {
Expand All @@ -379,7 +379,7 @@ function buildBodyParameter(
}
}

if (bodyParameter && bodyParameter.type.properties) {
if (bodyParameter && getAllProperties(bodyParameter.type).length > 0) {
return `\nbody: {${bodyParts.join(",\n")}},`;
}
}
Expand Down Expand Up @@ -631,11 +631,11 @@ function getRequestModelMapping(
propertyPath: string = "body",
importSet: Map<string, Set<string>>
) {
if (!modelPropertyType.properties || !modelPropertyType.properties) {
if (getAllProperties(modelPropertyType).length <= 0) {
return [];
}
const props: string[] = [];
const properties: Property[] = modelPropertyType.properties;
const properties: Property[] = getAllProperties(modelPropertyType) ?? [];
for (const property of properties) {
if (property.readonly) {
continue;
Expand Down Expand Up @@ -749,7 +749,7 @@ export function getResponseMapping(
)} ${
!property.optional ? "" : `!${propertyFullName} ? undefined :`
} {${getResponseMapping(
property.type.properties ?? [],
getAllProperties(property.type) ?? [],
`${propertyPath}.${property.restApiName}${
property.optional ? "?" : ""
}`,
Expand Down Expand Up @@ -816,7 +816,7 @@ function deserializeResponseValue(
case "list":
if (type.elementType?.type === "model") {
return `(${restValue} ?? []).map(p => ({${getResponseMapping(
type.elementType?.properties ?? [],
getAllProperties(type.elementType) ?? [],
"p",
importSet
)}}))`;
Expand Down Expand Up @@ -943,3 +943,15 @@ export function hasPagingOperation(codeModel: ModularCodeModel) {
)
);
}

function getAllProperties(type: Type): Property[] {
const properties: Property[] = [];
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: not sure this is caused the duplicated properties issues when discriminator property exists both parent and child model. see below cadl-ranch cases:

https://github.com/Azure/cadl-ranch/blob/main/packages/cadl-ranch-specs/http/type/model/inheritance/single-discriminator/main.tsp#L12-L25C1

Copy link
Member Author

Choose a reason for hiding this comment

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

Yeah, I found that, when I was trying to enable cadl ranch test cases for model inheritance in modular.

if (!type) {
return properties;
}
type.parents?.forEach((p) => {
qiaozha marked this conversation as resolved.
Show resolved Hide resolved
properties.push(...(p.properties ?? []));
});
properties.push(...(type.properties ?? []));
return properties;
}
79 changes: 79 additions & 0 deletions packages/typespec-ts/test/modularUnit/modelsGenerator.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -804,4 +804,83 @@ describe("inheritance & polymorphism", () => {
}`
);
});

it.only("should handle inheritance model in operations", async () => {
qiaozha marked this conversation as resolved.
Show resolved Hide resolved
const tspContent = `
model Pet {
name: string;
weight?: float32;
}
model Cat extends Pet {
kind: "cat";
meow: int32;
}
model Dog extends Pet {
kind: "dog";
bark: string;
}
op read(): { @body body: Cat };
`;
const modelFile = await emitModularModelsFromTypeSpec(tspContent);
assert.ok(modelFile);
assertEqualContent(
modelFile?.getFullText()!,
`
export interface Pet {
name: string;
weight?: number;
}

export interface Cat extends Pet {
kind: "cat";
meow: number;
}

export interface Dog extends Pet {
kind: "dog";
bark: string;
}`
);
const operationFiles = await emitModularOperationsFromTypeSpec(tspContent);
assert.ok(operationFiles);
assert.equal(operationFiles?.length, 1);
assertEqualContent(
operationFiles?.[0]?.getFullText()!,`
import { TestingContext as Client } from "../rest/index.js";
import {
StreamableMethod,
operationOptionsToRequestParameters,
} from "@azure-rest/core-client";

export function _readSend(
context: Client,
options: ReadOptions = { requestOptions: {} }
): StreamableMethod<Read200Response> {
return context
.path("/")
.get({ ...operationOptionsToRequestParameters(options) });
}

export async function _readDeserialize(result: Read200Response): Promise<Cat> {
if (result.status !== "200") {
throw result.body;
}

return {
name: result.body["name"],
weight: result.body["weight"],
kind: result.body["kind"],
meow: result.body["meow"],
};
}

export async function read(
context: Client,
options: ReadOptions = { requestOptions: {} }
): Promise<Cat> {
const result = await _readSend(context, options);
return _readDeserialize(result);
}
`);
});
});
Loading