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

Generate types for new MFD design #2455

Merged
merged 22 commits into from
Apr 26, 2024
Merged
Show file tree
Hide file tree
Changes from 4 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
26 changes: 0 additions & 26 deletions packages/rlc-common/src/buildIndexFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { Project, SourceFile } from "ts-morph";
import { NameType, normalizeName } from "./helpers/nameUtils.js";
import {
hasCsvCollection,
needsFilePolyfil,
hasInputModels,
hasMultiCollection,
hasOutputModels,
Expand All @@ -19,7 +18,6 @@ import {
import { RLCModel } from "./interfaces.js";
import * as path from "path";
import { getImportModuleName } from "./helpers/nameConstructors.js";
import { getImportSpecifier } from "./helpers/importsUtil.js";

export function buildIndexFile(model: RLCModel) {
const multiClient = Boolean(model.options?.multiClient),
Expand Down Expand Up @@ -167,8 +165,6 @@ function generateRLCIndexForMultiClient(file: SourceFile, model: RLCModel) {
exports.push("SerializeHelper");
}

reExportFileHelperFromCore(file, model);

file.addExportDeclarations([
{
moduleSpecifier: getImportModuleName(
Expand Down Expand Up @@ -331,30 +327,8 @@ function generateRLCIndex(file: SourceFile, model: RLCModel) {
]);
}

reExportFileHelperFromCore(file, model);

file.addExportAssignment({
expression: createClientFuncName,
isExportEquals: false
});
}

// re-export file helpers from core
function reExportFileHelperFromCore(file: SourceFile, model: RLCModel) {
if (needsFilePolyfil(model)) {
file.addExportDeclarations([
{
moduleSpecifier: getImportSpecifier(
"restPipeline",
model.importInfo.runtimeImports
),
namedExports: [
"createFile",
"createFileFromStream",
"type CreateFileOptions",
"type CreateFileFromStreamOptions"
]
}
]);
}
}
176 changes: 145 additions & 31 deletions packages/rlc-common/src/buildObjectTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,22 @@

import {
InterfaceDeclarationStructure,
OptionalKind,
PropertySignatureStructure,
StructureKind,
TypeAliasDeclarationStructure
} from "ts-morph";
import { NameType, normalizeName } from "./helpers/nameUtils.js";
import { NameType, normalizeName, pascalCase } from "./helpers/nameUtils.js";
import { isDictionarySchema, isObjectSchema } from "./helpers/schemaHelpers.js";
import {
ObjectSchema,
Parameter,
Property,
RLCModel,
Schema,
SchemaContext
} from "./interfaces.js";
import { getMultipartPartTypeName } from "./helpers/nameConstructors.js";

/**
* Generates interfaces for ObjectSchemas
Expand All @@ -40,6 +43,18 @@ export function buildObjectInterfaces(
) {
continue;
}

if (objectSchema.isMultipartBody) {
objectInterfaces.push(
...buildMultipartPartDefinitions(
objectSchema,
importedModels,
schemaUsage
)
);
continue;
}

const baseName = getObjectBaseName(objectSchema, schemaUsage);
const interfaceDeclaration = getObjectInterfaceDeclaration(
model,
Expand All @@ -54,6 +69,66 @@ export function buildObjectInterfaces(
return objectInterfaces;
}

const MULTIPART_FILE_UPLOAD_MIME_PROPERTIES: OptionalKind<PropertySignatureStructure>[] =
[
{
name: "filename",
hasQuestionToken: true,
type: "string"
},
{
name: "contentType",
hasQuestionToken: true,
type: "string"
}
];

function buildMultipartPartDefinitions(
Copy link
Member

Choose a reason for hiding this comment

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

Do we consider the case for A extends B?

Copy link
Member Author

Choose a reason for hiding this comment

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

Not currently but we can revisit if this becomes a requirement

schema: ObjectSchema,
importedModels: Set<string>,
schemaUsage: SchemaContext[]
): InterfaceDeclarationStructure[] {
if (!schema.isMultipartBody) {
return [];
}

// Transform property signatures into individual models
const propertySignatures = getPropertySignatures(
schema.properties ?? {},
schemaUsage,
importedModels,
{ flattenArrays: true }
);

const structures: InterfaceDeclarationStructure[] = [];

for (const signature of propertySignatures) {
const name = signature.name;
const typeName = getMultipartPartTypeName(schema.name, name);

const isFileUpload = signature.type?.toString().includes("File") ?? false;

structures.push({
kind: StructureKind.Interface,
isExported: true,
name: typeName,
properties: [
{
name: "name",
type: name
},
{
name: "body",
type: signature.type
},
...(isFileUpload ? MULTIPART_FILE_UPLOAD_MIME_PROPERTIES : [])
]
});
}

return structures;
}

export function buildObjectAliases(
model: RLCModel,
importedModels: Set<string>,
Expand All @@ -67,6 +142,29 @@ export function buildObjectAliases(
const objectAliases: TypeAliasDeclarationStructure[] = [];

for (const objectSchema of objectSchemas) {
if (objectSchema.isMultipartBody) {
const propertySignatures = getPropertySignatures(
objectSchema.properties ?? {},
schemaUsage,
importedModels,
{ flattenArrays: true }
);

const objectTypeNames = propertySignatures.map((sig) =>
getMultipartPartTypeName(objectSchema.name, sig.name)
);

objectAliases.push({
kind: StructureKind.TypeAlias,
...(objectSchema.description && {
docs: [{ description: objectSchema.description }]
}),
name: objectSchema.typeName!,
type: `FormData | Array<${objectTypeNames.join("|") || "unknown"}>`,
isExported: true
});
}

if (objectSchema.alias || objectSchema.outputAlias) {
const description = objectSchema.description;
const modelName = schemaUsage.includes(SchemaContext.Input)
Expand Down Expand Up @@ -424,10 +522,15 @@ export function getImmediateParentsNames(
return [...parents, ...extendFrom];
}

interface GetPropertySignatureOptions {
flattenArrays?: boolean;
}

function getPropertySignatures(
properties: { [key: string]: Property },
schemaUsage: SchemaContext[],
importedModels: Set<string>
importedModels: Set<string>,
options: GetPropertySignatureOptions = {}
) {
let validProperties = Object.keys(properties);
const readOnlyFilter = (name: string) =>
Expand All @@ -438,63 +541,74 @@ function getPropertySignatures(
getPropertySignature(
{ ...properties[p], name: p },
schemaUsage,
importedModels
importedModels,
options
)
);
}

/**
* Builds a Typescript property or parameter signature
* @param property - Property or parameter to get the Typescript signature for
* @param schema - Property or parameter to get the Typescript signature for
* @param importedModels - Set to track the models that need to be imported
* @returns a PropertySignatureStructure for the property.
*/
export function getPropertySignature(
property: Property | Parameter,
schemaUsage: SchemaContext[],
importedModels: Set<string>
importedModels: Set<string>,
options: GetPropertySignatureOptions = {}
): PropertySignatureStructure {
const propertyName = property.name;
const description = property.description;
let schema: Schema;
if (options.flattenArrays && property.type === "array") {
schema = {
...((property as any).items ?? property),
name: property.name
};
} else {
schema = property;
}

const propertyName = schema.name;
const description = schema.description;
let type;
const hasCoreInArray =
property.type === "array" &&
(property as any).items &&
(property as any).items.fromCore;
schema.type === "array" &&
(schema as any).items &&
(schema as any).items.fromCore;
const hasCoreInRecord =
property.type === "dictionary" &&
(property as any).additionalProperties &&
(property as any).additionalProperties.fromCore;
if (hasCoreInArray && property.typeName) {
type = property.typeName;
schema.type === "dictionary" &&
(schema as any).additionalProperties &&
(schema as any).additionalProperties.fromCore;
if (hasCoreInArray && schema.typeName) {
type = schema.typeName;
importedModels.add(
(property as any).items.typeName ?? (property as any).items.name
(schema as any).items.typeName ?? (schema as any).items.name
);
} else if (hasCoreInRecord && property.typeName) {
type = property.typeName;
} else if (hasCoreInRecord && schema.typeName) {
type = schema.typeName;
importedModels.add(
(property as any).additionalProperties.typeName ??
(property as any).additionalProperties.name
(schema as any).additionalProperties.typeName ??
(schema as any).additionalProperties.name
);
} else {
type =
generateForOutput(schemaUsage, property.usage) && property.outputTypeName
? property.outputTypeName
: property.typeName
? property.typeName
: property.type;
if (property.typeName && property.fromCore) {
importedModels.add(property.typeName);
type = property.typeName;
generateForOutput(schemaUsage, schema.usage) && schema.outputTypeName
? schema.outputTypeName
: schema.typeName
? schema.typeName
: schema.type;
if (schema.typeName && schema.fromCore) {
importedModels.add(schema.typeName);
type = schema.typeName;
}
}

return {
name: propertyName,
...(description && { docs: [{ description }] }),
hasQuestionToken: !property.required,
isReadonly:
generateForOutput(schemaUsage, property.usage) && property.readOnly,
hasQuestionToken: !schema.required,
isReadonly: generateForOutput(schemaUsage, schema.usage) && schema.readOnly,
type,
kind: StructureKind.PropertySignature
};
Expand Down
1 change: 1 addition & 0 deletions packages/rlc-common/src/buildParameterTypes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ export function buildParameterTypes(model: RLCModel) {
}

// Add interfaces for body and query parameters

parametersFile.addInterfaces([
...(bodyParameterDefinition ?? []),
...(queryParameterDefinitions ?? []),
Expand Down
2 changes: 1 addition & 1 deletion packages/rlc-common/src/helpers/importsUtil.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export function buildRuntimeImports(flavor?: PackageFlavor): Imports {
restClient: {
type: "restClient",
specifier: "@azure-rest/core-client",
version: "^1.4.0"
version: "/home/timov/src/azure-sdk-for-js/sdk/core/core-client-rest"
},
coreAuth: {
type: "coreAuth",
Expand Down
10 changes: 10 additions & 0 deletions packages/rlc-common/src/helpers/nameConstructors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,3 +134,13 @@ export function getClientName(model: RLCModel) {

return clientInterfaceName;
}

export function getMultipartPartTypeName(schemaName: string, partName: string) {
const name = normalizeName(partName, NameType.Interface);
const bodyParamName = normalizeName(schemaName, NameType.Interface);

return normalizeName(
`${bodyParamName}_${name}_PartDescriptor`,
NameType.Interface
);
}
8 changes: 0 additions & 8 deletions packages/rlc-common/src/helpers/operationHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import {
import {
Methods,
ObjectSchema,
OperationParameter,
PathParameter,
RLCModel,
SchemaContext
Expand Down Expand Up @@ -122,10 +121,3 @@ function hasSchemaContextObject(model: RLCModel, schemaUsage: SchemaContext[]) {

return objectSchemas.length > 0;
}

export function needsFilePolyfil(model: RLCModel) {
return model.parameters?.some(
(p: OperationParameter) =>
p.parameters?.some((p) => p.body?.needsFilePolyfil)
);
}
7 changes: 7 additions & 0 deletions packages/rlc-common/src/helpers/schemaHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
// Licensed under the MIT License.

import {
ArraySchema,
ObjectSchema,
RLCModel,
Schema,
Expand All @@ -12,6 +13,12 @@ export interface IsDictionaryOptions {
filterEmpty?: boolean;
}

export function isArraySchema(schema: Schema): schema is ArraySchema {
return (
schema.type === "array" || typeof (schema as any).items !== "undefined"
);
}

export function isDictionarySchema(
schema: Schema,
options: IsDictionaryOptions = {}
Expand Down
Loading
Loading