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

make subscirption id optional if there're tenant level operations #1869

Merged
merged 5 commits into from
May 26, 2023
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
100 changes: 92 additions & 8 deletions packages/autorest.typescript/src/generators/clientFileGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,7 +220,7 @@ export function generateClient(clientDetails: ClientDetails, project: Project) {
apiVersionParams && apiVersionParams.length === 1
? apiVersionParams[0]
: undefined;
writeClassProperties(clientClass, clientParams, importedModels);
writeClassProperties(clientClass, clientParams, importedModels, clientDetails.hasTenantLevelOperation);
writeConstructor(clientDetails, clientClass, importedModels, apiVersionParam);
if (useCoreV2 && apiVersionParam) {
writeCustomApiVersion(clientClass);
Expand All @@ -246,14 +246,22 @@ export function generateClient(clientDetails: ClientDetails, project: Project) {
function writeClassProperties(
clientClass: ClassDeclaration,
clientParams: ParameterDetails[],
importedModels: Set<string>
importedModels: Set<string>,
hasTenantLevelOperation: boolean = false
) {
const params = clientParams.filter(p => !p.isSynthetic);
params.forEach(({ typeDetails }) =>
typeDetails.usedModels.forEach(model => importedModels.add(model))
);
clientClass.addProperties(
params.map(param => {
if (param.name === "subscriptionId" && hasTenantLevelOperation) {
return {
name: param.name,
type: param.typeDetails.typeName,
hasQuestionToken: true
} as PropertyDeclarationStructure;
}
return {
name: param.name,
type: param.typeDetails.typeName,
Expand Down Expand Up @@ -327,7 +335,7 @@ function writeConstructor(
typeDetails.usedModels.forEach(model => importedModels.add(model))
);

const clientConstructor = classDeclaration.addConstructor({
const clientConstructorInitial = {
docs: [docs],
parameters: [
...requiredParams.map(p => ({
Expand All @@ -341,7 +349,55 @@ function writeConstructor(
type: optionsParameterType
}
]
});
}

let clientConstructor;
if (clientDetails.hasTenantLevelOperation) {
clientConstructor = classDeclaration.addConstructor({
parameters: [
...requiredParams
.filter(param => {
return param.name !== "subscriptionId";
})
.map(p => ({
name: p.name,
hasQuestionToken: !p.required,
type: p.typeDetails.typeName
})),
{
name: "subscriptionIdOrOptions",
hasQuestionToken: true,
type: optionsParameterType + "| string"
},
{
name: "options",
hasQuestionToken: true,
type: optionsParameterType
}
]
});
clientConstructor.addOverload(clientConstructorInitial)
clientConstructor.addOverload({
parameters: [
...requiredParams
.filter(param => {
return param.name !== "subscriptionId";
})
.map(p => ({
name: p.name,
hasQuestionToken: !p.required,
type: p.typeDetails.typeName
})),
{
name: "options",
hasQuestionToken: true,
type: optionsParameterType
}
]
});
} else {
clientConstructor = classDeclaration.addConstructor(clientConstructorInitial);
}

const { useCoreV2 } = getAutorestOptions();
const hasLro = clientDetails.operationGroups.some(og =>
Expand Down Expand Up @@ -372,7 +428,13 @@ function writeConstructor(
};

clientConstructor.addStatements([
writeStatements(getRequiredParamChecks(requiredParams), addBlankLine),
writeStatements(
getRequiredParamChecks(
requiredParams,
clientDetails.hasTenantLevelOperation
),
addBlankLine
),
writeStatement(
writeDefaultOptions(
clientParams.some(p => p.name === "credentials"),
Expand Down Expand Up @@ -517,8 +579,17 @@ function writeClientOperations(
);
}

function getRequiredParamChecks(requiredParameters: ParameterDetails[]) {
return requiredParameters.map(
function getRequiredParamChecks(
requiredParameters: ParameterDetails[],
hasTenantLevelOperation?: boolean
) {
let requiredParams = requiredParameters;
if (hasTenantLevelOperation) {
requiredParams = requiredParameters.filter(param => {
return param.name !== "subscriptionId";
});
}
return requiredParams.map(
({ name }) => `if(${name} === undefined) {
throw new Error("'${name}' cannot be null");
}`
Expand Down Expand Up @@ -582,7 +653,20 @@ function getTrack2DefaultContent(
addCredentials
} = getAutorestOptions();

const defaultContent = `// Initializing default values for options
const overloadDefaults = `
let subscriptionId: string | undefined;

if (!subscriptionIdOrOptions !== undefined) {
if (typeof subscriptionIdOrOptions === "string") {
subscriptionId = subscriptionIdOrOptions;
} else if (typeof subscriptionIdOrOptions === "object") {
options = subscriptionIdOrOptions;
}
}
`;

const defaultContent = `${clientDetails.hasTenantLevelOperation ? overloadDefaults: ""}
// Initializing default values for options
if (!options) {
options = {};
}
Expand Down
3 changes: 2 additions & 1 deletion packages/autorest.typescript/src/models/clientDetails.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,5 +41,6 @@ export interface ClientDetails {
endpoint: EndpointDetails;
samples?: SampleGroup[];
allTypes: string[];
security: Security
security: Security,
hasTenantLevelOperation?: boolean
}
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ export interface OperationDetails {
lroOptions?: { "final-state-via": string };
scope?: Scope;
namePrefix?: string;
isTenantLevel?: boolean;
MaryGao marked this conversation as resolved.
Show resolved Hide resolved
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -437,6 +437,8 @@ export async function transformOperation(

const mediaTypes = await getOperationMediaTypes(requests, responses);

const isTenantLevel = isOperationTenantLevel(operation);

return {
name,
typeDetails,
Expand All @@ -451,7 +453,8 @@ export async function transformOperation(
mediaTypes,
pagination,
isLro,
lroOptions
lroOptions,
isTenantLevel
};
}

Expand Down Expand Up @@ -607,3 +610,21 @@ function getMapperForSchema(
})
);
}

function isOperationTenantLevel(operation: Operation) {
Copy link
Member

@MaryGao MaryGao May 25, 2023

Choose a reason for hiding this comment

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

Is my understanding correct?

If one operation has method-level subid defined, the isOperationTenantLevel would return true?

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 exactly, an operation is tenant level if there are no client level subscriptionId parameter in the operation, that doesn't mean they need to have method level subscriptionId parameter, because they can even don't have subscriptionId as a parameter at all. The tenant level operation is the condition of adding this overloads to make the subscriptionId optional, but if the whole RP doesn't have any operation that contains the client level subscriptionId parameter, then subscriptionId doesn't even belongs to client constructor signature, then there is not need to add this overloads either.

const subscriptionIdParameter = operation.parameters?.find(param => {
return (
param.protocol.http?.in === ParameterLocation.Path &&
param.language.default.name.toLowerCase() === "subscriptionid" &&
param.implementation === "Client"
);
});
if (
subscriptionIdParameter ||
operation.operationId === "Operations_List" ||
MaryGao marked this conversation as resolved.
Show resolved Hide resolved
operation.language.default.name.toLowerCase().startsWith("checkname")
) {
return false;
}
return true;
}
Original file line number Diff line number Diff line change
Expand Up @@ -162,12 +162,15 @@ export async function getAllExamples(
clientParameterNames.push(parameterName);
}

handleSubscriptionIdParameter(
subscriptionIdValue,
clientParameterNames,
sample.clientParamAssignments,
requiredParams
);
if (!opDetails.isTenantLevel) {
MaryGao marked this conversation as resolved.
Show resolved Hide resolved
handleSubscriptionIdParameter(
subscriptionIdValue,
clientParameterNames,
sample.clientParamAssignments,
requiredParams
);
}

if (clientParameterNames.length > 0) {
sample.clientParameterNames = clientParameterNames.join(", ");
}
Expand Down
49 changes: 47 additions & 2 deletions packages/autorest.typescript/src/transforms/transforms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import {
SealedChoiceSchema,
SchemaType,
OAuth2SecurityScheme,
KeySecurityScheme
KeySecurityScheme,
ParameterLocation
} from "@autorest/codemodel";
import { normalizeName, NameType } from "../utils/nameUtils";
import { getStringForValue } from "../utils/valueHelpers";
Expand All @@ -26,6 +27,7 @@ import { normalizeModelWithExtensions } from "./extensions";
import { transformGroups } from "./groupTransforms";
import { getSchemaParents } from "../utils/schemaHelpers";
import { sortObjectSchemasHierarchically } from "../utils/sortObjectSchemasHierarchically";
import { OperationGroupDetails } from "../models/operationDetails";

export async function transformChoices(codeModel: CodeModel) {
const choices = [
Expand Down Expand Up @@ -127,7 +129,8 @@ export async function transformCodeModel(
options,
endpoint: baseUrl,
allTypes: [],
security: codeModel.security
security: codeModel.security,
hasTenantLevelOperation: transformHasTenantLevel(operationGroups)
};
}

Expand Down Expand Up @@ -157,3 +160,45 @@ async function getUberParents(codeModel: CodeModel): Promise<ObjectDetails[]> {

return uberParents;
}

function transformHasTenantLevel(
operationGroups: OperationGroupDetails[]
): boolean {
let hasTenantLevelOperation: boolean = false;
let hasClientLevelSubscription = false;
operationGroups.forEach(opGroup => {
opGroup.operations.forEach(op => {
const subscriptionIdParam = op.parameters.find(p => {
return (
p.language.default.name.toLowerCase() === "subscriptionid" &&
p.protocol.http?.in === ParameterLocation.Path &&
p.implementation === "Client"
);
});
if (subscriptionIdParam) {
hasClientLevelSubscription = true;
return;
MaryGao marked this conversation as resolved.
Show resolved Hide resolved
}
if (hasClientLevelSubscription) {
return;
}
});
if (hasClientLevelSubscription) {
return;
}
});
operationGroups.forEach(opGroup => {
opGroup.operations.forEach(op => {
if (op.isTenantLevel) {
hasTenantLevelOperation = true;
}
if (hasTenantLevelOperation) {
return;
MaryGao marked this conversation as resolved.
Show resolved Hide resolved
}
});
if (hasTenantLevelOperation) {
return;
}
});
return hasTenantLevelOperation && hasClientLevelSubscription;
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import { AzureSpecialPropertiesClientOptionalParams } from "./models";

export class AzureSpecialPropertiesClient extends coreClient.ServiceClient {
$host: string;
subscriptionId: string;
subscriptionId?: string;
apiVersion: string;

/**
Expand All @@ -51,12 +51,30 @@ export class AzureSpecialPropertiesClient extends coreClient.ServiceClient {
credentials: coreAuth.TokenCredential,
subscriptionId: string,
options?: AzureSpecialPropertiesClientOptionalParams
);
constructor(
credentials: coreAuth.TokenCredential,
options?: AzureSpecialPropertiesClientOptionalParams
);
constructor(
credentials: coreAuth.TokenCredential,
subscriptionIdOrOptions?:
| AzureSpecialPropertiesClientOptionalParams
| string,
options?: AzureSpecialPropertiesClientOptionalParams
) {
if (credentials === undefined) {
throw new Error("'credentials' cannot be null");
}
if (subscriptionId === undefined) {
throw new Error("'subscriptionId' cannot be null");

let subscriptionId: string | undefined;

if (!subscriptionIdOrOptions !== undefined) {
MaryGao marked this conversation as resolved.
Show resolved Hide resolved
if (typeof subscriptionIdOrOptions === "string") {
subscriptionId = subscriptionIdOrOptions;
} else if (typeof subscriptionIdOrOptions === "object") {
options = subscriptionIdOrOptions;
}
}
MaryGao marked this conversation as resolved.
Show resolved Hide resolved

// Initializing default values for options
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { DomainServicesClientOptionalParams } from "./models";
export class DomainServicesClient extends coreClient.ServiceClient {
$host: string;
apiVersion: string;
subscriptionId: string;
subscriptionId?: string;

/**
* Initializes a new instance of the DomainServicesClient class.
Expand All @@ -32,9 +32,20 @@ export class DomainServicesClient extends coreClient.ServiceClient {
constructor(
subscriptionId: string,
options?: DomainServicesClientOptionalParams
);
constructor(options?: DomainServicesClientOptionalParams);
constructor(
subscriptionIdOrOptions?: DomainServicesClientOptionalParams | string,
options?: DomainServicesClientOptionalParams
) {
if (subscriptionId === undefined) {
throw new Error("'subscriptionId' cannot be null");
let subscriptionId: string | undefined;

if (!subscriptionIdOrOptions !== undefined) {
if (typeof subscriptionIdOrOptions === "string") {
subscriptionId = subscriptionIdOrOptions;
} else if (typeof subscriptionIdOrOptions === "object") {
options = subscriptionIdOrOptions;
}
}

// Initializing default values for options
Expand Down
Loading