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

Support collection format in modular #1983

Merged
merged 17 commits into from
Aug 22, 2023
Merged
Show file tree
Hide file tree
Changes from 8 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
2 changes: 1 addition & 1 deletion packages/rlc-common/src/helpers/nameUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ export const ReservedModelNames: ReservedName[] = [
{ name: "else", reservedFor: [NameType.Parameter] },
{ name: "enum", reservedFor: [NameType.Parameter] },
{ name: "error", reservedFor: [NameType.Parameter, ...Newable] },
{ name: "export", reservedFor: [NameType.Parameter] },
{ name: "export", reservedFor: [NameType.Parameter, NameType.Operation] },
{ name: "extends", reservedFor: [NameType.Parameter] },
{ name: "false", reservedFor: [NameType.Parameter] },
{ name: "finally", reservedFor: [NameType.Parameter] },
Expand Down
22 changes: 17 additions & 5 deletions packages/typespec-ts/src/modular/buildClassicalClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,24 +151,30 @@ function buildClientOperationGroups(
clientClass: ClassDeclaration,
subfolder: string
) {
const operationMap = new Map<
OptionalKind<FunctionDeclarationStructure>,
string | undefined
>();
for (const operationGroup of client.operationGroups) {
const operationGroupName = toCamelCase(operationGroup.propertyName);
let clientType = "Client";
if (subfolder && subfolder !== "") {
clientType = `Client.${clientClass.getName()}`;
}
const operationDeclarations: OptionalKind<FunctionDeclarationStructure>[] =
operationGroup.operations.map((operation) =>
getOperationFunction(operation, clientType)
);
operationGroup.operations.map((operation) => {
const declarations = getOperationFunction(operation, clientType);
operationMap.set(declarations, operation.oriName);
return declarations;
});

if (operationGroupName && operationGroupName !== "") {
clientClass.addProperty({
name: operationGroupName,
initializer: `
{
${operationDeclarations.map((d) => {
return `${d.name}: (${d.parameters
return `${getClassicalMethodName(d)}: (${d.parameters
?.filter((p) => p.name !== "context")
.map(
(p) => p.name + (p.name === "options" ? "?" : "") + ": " + p.type
Expand All @@ -186,7 +192,7 @@ function buildClientOperationGroups(
operationDeclarations.map((d) => {
const method: MethodDeclarationStructure = {
docs: d.docs,
name: d.name ?? "FIXME",
name: getClassicalMethodName(d),
kind: StructureKind.Method,
returnType: d.returnType,
parameters: d.parameters?.filter((p) => p.name !== "context"),
Expand All @@ -203,4 +209,10 @@ function buildClientOperationGroups(
);
}
}

function getClassicalMethodName(
declaration: OptionalKind<FunctionDeclarationStructure>
) {
return operationMap.get(declaration) ?? declaration.name ?? "FIXME";
}
}
32 changes: 31 additions & 1 deletion packages/typespec-ts/src/modular/buildCodeModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,8 @@ function emitParameter(
location: parameter.type,
type: type,
implementation: implementation,
skipUrlEncoding: parameter.type === "endpointPath"
skipUrlEncoding: parameter.type === "endpointPath",
format: (parameter as any).format
};

if (paramMap.type.type === "constant") {
Expand Down Expand Up @@ -1318,9 +1319,38 @@ function emitOperationGroups(
operations: clientOperations
});
}
resolveConflictIfExist(operationGroups);
return operationGroups;
}

function resolveConflictIfExist(operationGroups: OperationGroup[]) {
MaryGao marked this conversation as resolved.
Show resolved Hide resolved
if (operationGroups.length < 2) {
return;
}

const nameSet = new Set<string>();
const hasConflict = operationGroups.some((g) =>
g.operations.some((op) => {
if (nameSet.has(op.name)) {
return true;
} else {
nameSet.add(op.name);
return false;
}
})
);
if (!hasConflict) {
return;
}
// Append operation group prefix
operationGroups.forEach((g) =>
g.operations.forEach((op) => {
op.oriName = op.name;
op.name = `${g.propertyName}_${op.name}`;
})
);
}

function getServerHelper(
program: Program,
namespace: Namespace
Expand Down
49 changes: 35 additions & 14 deletions packages/typespec-ts/src/modular/helpers/operationHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ import {
getFixmeForMultilineDocs,
getDocsFromDescription
} from "./docsHelpers.js";
import {
getCollectionFormatHelper,
hasCollectionFormatInfo
} from "../../utils/operationUtil.js";

function getRLCResponseType(rlcResponse?: OperationResponse) {
if (!rlcResponse?.responses) {
Expand Down Expand Up @@ -260,10 +264,12 @@ export function getOperationFunction(
};
}

export function getOperationOptionsName(operation: Operation) {
const optionName = `${toPascalCase(operation.groupName)}${toPascalCase(
operation.name
)}Options`;
export function getOperationOptionsName(
operation: Operation,
includeGroupName = false
) {
const prefix = includeGroupName ? toPascalCase(operation.groupName) : "";
const optionName = `${prefix}${toPascalCase(operation.name)}Options`;
if (operation.bodyParameter?.type.name === optionName) {
return optionName.replace(/Options$/, "RequestOptions");
}
Expand Down Expand Up @@ -313,9 +319,9 @@ function getRequestParameters(
}

if (parametersImplementation.header.length) {
paramStr = `${paramStr}\nheaders: {${
parametersImplementation.header.join(",\n") + ","
},`;
paramStr = `${paramStr}\nheaders: {${parametersImplementation.header.join(
",\n"
)}},`;
}

if (parametersImplementation.query.length) {
Expand Down Expand Up @@ -395,6 +401,10 @@ function getParameterMap(
return getConstantValue(param);
}

if (hasCollectionFormatInfo((param as any).location, (param as any).format)) {
return getCollectionFormat(param as Parameter);
}

// if the parameter or property is optional, we don't need to handle the default value
if (isOptional(param)) {
return getOptional(param, importSet);
Expand All @@ -407,6 +417,22 @@ function getParameterMap(
throw new Error(`Parameter ${param.clientName} is not supported`);
}

function getCollectionFormat(param: Parameter) {
MaryGao marked this conversation as resolved.
Show resolved Hide resolved
const collectionInfo = getCollectionFormatHelper(
param.location,
param.format ?? ""
);
if (!collectionInfo) {
throw "Has collection format info but without helper function detected";
}
const isMulti = (param.format ?? "").toLowerCase() === "multi";
const additionalParam = isMulti ? `, "${param.restApiName}"` : "";
if (!param.optional) {
return `"${param.restApiName}": ${collectionInfo}(${param.clientName}${additionalParam})`;
}
return `"${param.restApiName}": options?.${param.clientName} !== undefined ? ${collectionInfo}(options?.${param.clientName}${additionalParam}): undefined`;
}

function isContentType(param: Parameter): boolean {
return (
param.location === "header" &&
Expand Down Expand Up @@ -477,16 +503,11 @@ type OptionalType = (Parameter | Property) & {
type: { optional: true };
};

function isOptional(
param: Parameter | Property
): param is OptionalType {
function isOptional(param: Parameter | Property): param is OptionalType {
return Boolean(param.optional);
}

function getOptional(
param: OptionalType,
importSet: Map<string, Set<string>>
) {
function getOptional(param: OptionalType, importSet: Map<string, Set<string>>) {
if (param.type.type === "model") {
return `"${param.restApiName}": {${getRequestModelMapping(
param.type,
Expand Down
2 changes: 2 additions & 0 deletions packages/typespec-ts/src/modular/modularCodeModel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ export interface Parameter {
inDocstring?: boolean;
inOverriden?: boolean;
isApiVersion?: boolean;
format?: string;
}

export interface Response {
Expand All @@ -136,6 +137,7 @@ export interface Response {

export interface Operation {
name: string;
oriName?: string;
description: string;
summary: string;
url: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import { getHttpOperation, HttpOperation } from "@typespec/http";
import {
hasPagingOperations,
extractPagedMetadataNested,
hasPollingOperations
hasPollingOperations,
getSpecialSerializeInfo
} from "../utils/operationUtil.js";
import { getSpecialSerializeInfo } from "./transformParameters.js";
import { SdkContext } from "../utils/interfaces.js";

export function transformHelperFunctionDetails(
Expand Down Expand Up @@ -199,7 +199,10 @@ function extractSpecialSerializeInfo(
for (const op of operations) {
const route = ignoreDiagnostics(getHttpOperation(program, op));
route.parameters.parameters.forEach((parameter) => {
const serializeInfo = getSpecialSerializeInfo(parameter);
const serializeInfo = getSpecialSerializeInfo(
parameter.type,
(parameter as any).format
);
hasMultiCollection = hasMultiCollection
? hasMultiCollection
: serializeInfo.hasMultiCollection;
Expand All @@ -222,7 +225,10 @@ function extractSpecialSerializeInfo(
for (const clientOp of clientOperations) {
const route = ignoreDiagnostics(getHttpOperation(program, clientOp));
route.parameters.parameters.forEach((parameter) => {
const serializeInfo = getSpecialSerializeInfo(parameter);
const serializeInfo = getSpecialSerializeInfo(
parameter.type,
(parameter as any).format
);
hasMultiCollection = hasMultiCollection
? hasMultiCollection
: serializeInfo.hasMultiCollection;
Expand Down
62 changes: 6 additions & 56 deletions packages/typespec-ts/src/transform/transformParameters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
import {
getOperationGroupName,
getOperationName,
getSpecialSerializeInfo,
isBinaryPayload
} from "../utils/operationUtil.js";
import {
Expand Down Expand Up @@ -140,7 +141,7 @@ function getParameterMetadata(
type === "number[]" ||
type === "Array<number>"
) {
const serializeInfo = getSpecialSerializeInfo(parameter);
const serializeInfo = getSpecialSerializeInfo(parameter.type, (parameter as any).format);
if (
serializeInfo.hasMultiCollection ||
serializeInfo.hasPipeCollection ||
Expand All @@ -153,11 +154,10 @@ function getParameterMetadata(
", "
)} collection, we provide ${serializeInfo.descriptions.join(
", "
)} from serializeHelper.ts to help${
serializeInfo.hasMultiCollection
? ", you will probably need to set skipUrlEncoding as true when sending the request"
: ""
}`;
)} from serializeHelper.ts to help${serializeInfo.hasMultiCollection
? ", you will probably need to set skipUrlEncoding as true when sending the request"
: ""
}`;
}
}
return {
Expand Down Expand Up @@ -470,53 +470,3 @@ function extractDescriptionsFromBody(
);
return description ? [description] : [];
}

export function getSpecialSerializeInfo(parameter: HttpOperationParameter) {
let hasMultiCollection = false;
let hasPipeCollection = false;
let hasSsvCollection = false;
let hasTsvCollection = false;
let hasCsvCollection = false;
const descriptions = [];
const collectionInfo = [];
if (
(parameter.type === "query" || parameter.type === "header") &&
(parameter as any).format === "multi"
) {
hasMultiCollection = true;
descriptions.push("buildMultiCollection");
collectionInfo.push("multi");
}
if (parameter.type === "query" && (parameter as any).format === "ssv") {
hasSsvCollection = true;
descriptions.push("buildSsvCollection");
collectionInfo.push("ssv");
}

if (parameter.type === "query" && (parameter as any).format === "tsv") {
hasTsvCollection = true;
descriptions.push("buildTsvCollection");
collectionInfo.push("tsv");
}

if (parameter.type === "query" && (parameter as any).format === "pipes") {
hasPipeCollection = true;
descriptions.push("buildPipeCollection");
collectionInfo.push("pipe");
}

if (parameter.type === "header" && (parameter as any).format === "csv") {
hasCsvCollection = true;
descriptions.push("buildCsvCollection");
collectionInfo.push("csv");
}
return {
hasMultiCollection,
hasPipeCollection,
hasSsvCollection,
hasTsvCollection,
hasCsvCollection,
descriptions,
collectionInfo
};
}
Loading
Loading