Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
Copy Markdown
Member

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
Copy Markdown
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) => {
Comment thread
qiaozha marked this conversation as resolved.
properties.push(...getAllProperties(p));
});
properties.push(...(type.properties ?? []));
return properties;
}
9 changes: 7 additions & 2 deletions packages/typespec-ts/src/modular/helpers/typeHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,10 @@ export function getType(type: Type, format?: string): TypeMetadata {
throw new Error("Unable to process Array with no elementType");
}
return {
name: getNullableType(getType(type.elementType, type.elementType.format).name, type),
name: getNullableType(
getType(type.elementType, type.elementType.format).name,
type
),
modifier: "Array",
originModule:
type.elementType?.type === "model" ? "models.js" : undefined
Expand Down Expand Up @@ -97,7 +100,9 @@ export function getType(type: Type, format?: string): TypeMetadata {
throw new Error("Unable to process dict without elemetType info");
}
return {
name: `Record<string, ${getTypeName(getType(type.elementType, type.elementType.format))}>`
name: `Record<string, ${getTypeName(
getType(type.elementType, type.elementType.format)
)}>`
};
case "any":
return {
Expand Down
242 changes: 242 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,246 @@ describe("inheritance & polymorphism", () => {
}`
);
});

it("should handle inheritance model in operations", async () => {
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);
}
`);
});

it("should handle multi level inheritance model in operations", async () => {
const tspContent = `
model Animal {
name: string;
}
model Pet extends Animal {
weight?: float32;
}
model Cat extends Pet {
kind: "cat";
meow: int32;
}
op read(): { @body body: Cat };
`;
const modelFile = await emitModularModelsFromTypeSpec(tspContent);
assert.ok(modelFile);
assertEqualContent(
modelFile?.getFullText()!,
`
export interface Animal {
name: string;
}

export interface Pet extends Animal {
weight?: number;
}

export interface Cat extends Pet {
kind: "cat";
meow: number;
}
`
);
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);
}
`);
});

/**
* TODO: This test is skipped because typespec has some issues. https://github.com/microsoft/typespec/issues/2411
*/
it.skip("should handle multiple parents inheritance model in operations", async () => {
const tspContent = `
model Creature {
life: int64;
}
model Animal {
name: string;
}
model Pet extends Animal, Creature {
weight?: float32;
}
model Cat extends Pet {
kind: "cat";
meow: int32;
}
op read(): { @body body: Cat };
`;
const modelFile = await emitModularModelsFromTypeSpec(tspContent);
assert.ok(modelFile);
assertEqualContent(
modelFile?.getFullText()!,
`
export interface Creature {
life: number;
}

export interface Animal {
name: string;
}

export interface Pet extends Animal, Creature {
weight?: number;
}

export interface Cat extends Pet {
kind: "cat";
meow: number;
}
`
);
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 {
life: result.body["life"],
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);
}
`);
});
});