diff --git a/.chronus/changes/allow_int_string-2024-6-29-16-19-19.md b/.chronus/changes/allow_int_string-2024-6-29-16-19-19.md new file mode 100644 index 0000000000..487dbf5eee --- /dev/null +++ b/.chronus/changes/allow_int_string-2024-6-29-16-19-19.md @@ -0,0 +1,7 @@ +--- +changeKind: feature +packages: + - "@azure-tools/typespec-client-generator-core" +--- + +add support for encoding an int as a string diff --git a/docs/howtos/DataPlane Generation - DPG/06types.mdx b/docs/howtos/DataPlane Generation - DPG/06types.mdx index 9fdced5ecd..b9fe65644c 100644 --- a/docs/howtos/DataPlane Generation - DPG/06types.mdx +++ b/docs/howtos/DataPlane Generation - DPG/06types.mdx @@ -2251,3 +2251,125 @@ public enum Orientation { + +## Scalars + +### Encoding + +We will take the `@encode` decorator into account, determining how we serialize inputted scalars to send over the wire. + + + + +model Test { +@encode(DateTimeKnownEncoding.rfc3339) +prop: utcDateTime; +} + + + + +```json +{ + "kind": "property", + "name": "prop", + "type": { + "kind": "utcDateTime", + "encode": "rfc3339", + "wireType": { + "kind": "string" + } + } +} +``` + + + + +```python +serialized_prop = json.dumps(prop, cls=SdkJSONEncoder, format="rfc3339") +``` + + + + +```csharp +TODO +``` + + + + +```typescript +TODO; +``` + + + + +```java +// Internal implementation +jsonWriter.writeStringField("prop", + this.value == null ? null : DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(this.value)); +``` + + + + +When you specify an encoding type, say that you want to encode an integer as a string, that will also be represented in our generated SDKs. + + + + +model Test { +@encode(string) +prop: int64; +} + + + + +```json +{ + "kind": "property", + "name": "prop", + "type": { + "kind": "int64", + "encode": "string", + "wireType": { + "kind": "string" + } + } +} +``` + + + + +```python +serialized_prop = json.dumps(prop, cls=SdkJSONEncoder, format="string") +``` + + + + +```csharp +TODO +``` + + + + +```typescript +TODO; +``` + + + + +```java +TODO +``` + + + diff --git a/packages/typespec-client-generator-core/src/types.ts b/packages/typespec-client-generator-core/src/types.ts index 5f420d2140..0ed24c6da3 100644 --- a/packages/typespec-client-generator-core/src/types.ts +++ b/packages/typespec-client-generator-core/src/types.ts @@ -136,7 +136,15 @@ function getAnyType(context: TCGCContext, type: Type): [SdkBuiltInType, readonly function getEncodeHelper(context: TCGCContext, type: Type, kind: string): string { if (type.kind === "ModelProperty" || type.kind === "Scalar") { - return getEncode(context.program, type)?.encoding || kind; + const encode = getEncode(context.program, type); + if (encode?.encoding) { + return encode.encoding; + } + if (encode?.type) { + // if we specify the encoding type in the decorator, we set the `.encode` string + // to the kind of the encoding type + return getSdkBuiltInType(context, encode.type).kind; + } } return kind; }