Skip to content

Commit 82cc41f

Browse files
committed
preserve LazyJsonString interface
1 parent 92b6cbb commit 82cc41f

File tree

7 files changed

+86
-45
lines changed

7 files changed

+86
-45
lines changed
Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,39 @@
11
import { describe, expect, test as it } from "vitest";
22

33
import { LazyJsonString } from "./lazy-json";
4+
45
describe("LazyJsonString", () => {
5-
it("returns identical values for toString(), valueOf(), and toJSON()", () => {
6-
const jsonValue = LazyJsonString.from({ foo: "bar" });
7-
expect(jsonValue.valueOf()).toBe(JSON.stringify({ foo: "bar" }));
8-
expect(jsonValue.toString()).toBe(JSON.stringify({ foo: "bar" }));
9-
expect(jsonValue.toJSON()).toBe(JSON.stringify({ foo: "bar" }));
6+
it("should have string methods", () => {
7+
const jsonValue = new LazyJsonString('"foo"');
8+
expect(jsonValue.length).toBe(5);
9+
expect(jsonValue.toString()).toBe('"foo"');
10+
});
11+
12+
it("should deserialize json properly", () => {
13+
const jsonValue = new LazyJsonString('"foo"');
14+
expect(jsonValue.deserializeJSON()).toBe("foo");
15+
const wrongJsonValue = new LazyJsonString("foo");
16+
expect(() => wrongJsonValue.deserializeJSON()).toThrow();
17+
});
18+
19+
it("should get JSON string properly", () => {
20+
const jsonValue = new LazyJsonString('{"foo", "bar"}');
21+
expect(jsonValue.toJSON()).toBe('{"foo", "bar"}');
1022
});
1123

1224
it("can instantiate from LazyJsonString class", () => {
13-
const original = LazyJsonString.from('"foo"');
14-
const newOne = LazyJsonString.from(original);
25+
const original = new LazyJsonString('"foo"');
26+
const newOne = LazyJsonString.fromObject(original);
1527
expect(newOne.toString()).toBe('"foo"');
1628
});
1729

1830
it("can instantiate from String class", () => {
19-
const jsonValue = LazyJsonString.from('"foo"');
31+
const jsonValue = LazyJsonString.fromObject(new String('"foo"'));
2032
expect(jsonValue.toString()).toBe('"foo"');
2133
});
2234

2335
it("can instantiate from object", () => {
24-
const jsonValue = LazyJsonString.from({ foo: "bar" });
36+
const jsonValue = LazyJsonString.fromObject({ foo: "bar" });
2537
expect(jsonValue.toString()).toBe('{"foo":"bar"}');
2638
});
2739
});
Lines changed: 58 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1,39 +1,68 @@
11
/**
2-
* @internal
2+
* @public
33
*
4-
* This class allows the usage of data objects in fields that expect
5-
* JSON strings. It serializes the data object into JSON
6-
* if needed during the request serialization step.
4+
* A model field with this type means that you may provide a JavaScript
5+
* object in lieu of a JSON string, and it will be serialized to JSON
6+
* automatically before being sent in a request.
77
*
8+
* For responses, you will receive a "LazyJsonString", which is a boxed String object
9+
* with additional mixin methods.
10+
* To get the string value, call `.toString()`, or to get the JSON object value,
11+
* call `.deserializeJSON()` or parse it yourself.
812
*/
9-
export class LazyJsonString {
10-
private constructor(private value: string) {}
11-
12-
public toString(): string {
13-
return this.value;
14-
}
13+
export type AutomaticJsonStringConversion = Parameters<typeof JSON.stringify>[0] | LazyJsonString;
1514

16-
public valueOf(): string {
17-
return this.value;
18-
}
19-
20-
public toJSON(): string {
21-
return this.value;
22-
}
15+
/**
16+
* @internal
17+
*
18+
*/
19+
export interface LazyJsonString extends String {
20+
new (s: string): typeof LazyJsonString;
2321

24-
public static from(object: any): LazyJsonString {
25-
if (object instanceof LazyJsonString) {
26-
return object;
27-
} else if (typeof object === "string") {
28-
return new LazyJsonString(object);
29-
}
30-
return new LazyJsonString(JSON.stringify(object));
31-
}
22+
/**
23+
* @returns the JSON parsing of the string value.
24+
*/
25+
deserializeJSON(): any;
3226

3327
/**
34-
* @deprecated call from() instead.
28+
* @returns the original string value rather than a JSON.stringified value.
3529
*/
36-
public static fromObject(object: any): LazyJsonString {
37-
return LazyJsonString.from(object);
38-
}
30+
toJSON(): string;
3931
}
32+
33+
/**
34+
* @internal
35+
*
36+
* Extension of the native String class in the previous implementation
37+
* has negative global performance impact on method dispatch for strings,
38+
* and is generally discouraged.
39+
*
40+
* This current implementation may look strange, but is necessary to preserve the interface and
41+
* behavior of extending the String class.
42+
*/
43+
export function LazyJsonString(val: string): void {
44+
const str = Object.assign(new String(val), {
45+
deserializeJSON() {
46+
return JSON.parse(val);
47+
},
48+
49+
toString() {
50+
return val;
51+
},
52+
53+
toJSON() {
54+
return val;
55+
},
56+
});
57+
58+
return str as never;
59+
}
60+
61+
LazyJsonString.fromObject = (object: any): LazyJsonString => {
62+
if (object instanceof LazyJsonString) {
63+
return object as any;
64+
} else if (typeof object === "string" || object?.prototype === String.prototype) {
65+
return LazyJsonString(object as string) as any;
66+
}
67+
return LazyJsonString(JSON.stringify(object)) as any;
68+
};

smithy-typescript-codegen/src/main/java/software/amazon/smithy/typescript/codegen/SymbolVisitor.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -300,8 +300,8 @@ public Symbol stringShape(StringShape shape) {
300300
if (mediaTypeTrait.isPresent()) {
301301
String mediaType = mediaTypeTrait.get().getValue();
302302
if (CodegenUtils.isJsonMediaType(mediaType)) {
303-
Symbol.Builder builder = createSymbolBuilder(shape, "__LazyJsonString | string");
304-
return addSmithyUseImport(builder, "LazyJsonString", "__LazyJsonString").build();
303+
Symbol.Builder builder = createSymbolBuilder(shape, "__AutomaticJsonStringConversion | string");
304+
return addSmithyUseImport(builder, "AutomaticJsonStringConversion", "__AutomaticJsonStringConversion").build();
305305
} else {
306306
LOGGER.warning(() -> "Found unsupported mediatype " + mediaType + " on String shape: " + shape);
307307
}

smithy-typescript-codegen/src/main/java/software/amazon/smithy/typescript/codegen/integration/HttpProtocolGeneratorUtils.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ public static String getStringInputParam(GenerationContext context, Shape shape,
176176
if (CodegenUtils.isJsonMediaType(mediaType)) {
177177
TypeScriptWriter writer = context.getWriter();
178178
writer.addImport("LazyJsonString", "__LazyJsonString", TypeScriptDependency.AWS_SMITHY_CLIENT);
179-
return "__LazyJsonString.from(" + dataSource + ")";
179+
return "__LazyJsonString.fromObject(" + dataSource + ")";
180180
} else {
181181
LOGGER.warning(() -> "Found unsupported mediatype " + mediaType + " on String shape: " + shape);
182182
}
@@ -210,7 +210,7 @@ public static String getStringOutputParam(GenerationContext context,
210210
if (CodegenUtils.isJsonMediaType(mediaType)) {
211211
TypeScriptWriter writer = context.getWriter();
212212
writer.addImport("LazyJsonString", "__LazyJsonString", TypeScriptDependency.AWS_SMITHY_CLIENT);
213-
return "__LazyJsonString.from(" + dataSource + ")";
213+
return "new __LazyJsonString(" + dataSource + ")";
214214
} else {
215215
LOGGER.warning(() -> "Found unsupported mediatype " + mediaType + " on String shape: " + shape);
216216
}

smithy-typescript-codegen/src/test/java/software/amazon/smithy/typescript/codegen/SymbolProviderTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ public void usesLazyJsonStringForJsonMediaType() {
191191
SymbolProvider provider = new SymbolVisitor(model, settings);
192192
Symbol memberSymbol = provider.toSymbol(member);
193193

194-
assertThat(memberSymbol.getName(), equalTo("__LazyJsonString | string"));
194+
assertThat(memberSymbol.getName(), equalTo("__AutomaticJsonStringConversion | string"));
195195
}
196196

197197
@Test

smithy-typescript-codegen/src/test/java/software/amazon/smithy/typescript/codegen/integration/DocumentMemberDeserVisitorTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ public static Collection<Object[]> validMemberTargetTypes() {
9898
{StringShape.builder().id(id).build(), "__expectString(" + DATA_SOURCE + ")", source},
9999
{
100100
StringShape.builder().id(id).addTrait(new MediaTypeTrait("foo+json")).build(),
101-
"__LazyJsonString.from(" + DATA_SOURCE + ")",
101+
"new __LazyJsonString(" + DATA_SOURCE + ")",
102102
source
103103
},
104104
{BlobShape.builder().id(id).build(), "context.base64Decoder(" + DATA_SOURCE + ")", source},

smithy-typescript-codegen/src/test/java/software/amazon/smithy/typescript/codegen/integration/DocumentMemberSerVisitorTest.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,7 @@ public static Collection<Object[]> validMemberTargetTypes() {
8383
{StringShape.builder().id(id).build(), DATA_SOURCE},
8484
{
8585
StringShape.builder().id(id).addTrait(new MediaTypeTrait("foo+json")).build(),
86-
"__LazyJsonString.from(" + DATA_SOURCE + ")"
86+
"__LazyJsonString.fromObject(" + DATA_SOURCE + ")"
8787
},
8888
{BlobShape.builder().id(id).build(), "context.base64Encoder(" + DATA_SOURCE + ")"},
8989
{DocumentShape.builder().id(id).build(), delegate},

0 commit comments

Comments
 (0)