Skip to content

Commit 3654bae

Browse files
committed
feat: add getValueFromTextNode util function to smithy-client
1 parent 3f1b45d commit 3654bae

File tree

3 files changed

+72
-0
lines changed

3 files changed

+72
-0
lines changed
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import { getValueFromTextNode } from "./get-value-from-text-node";
2+
3+
describe("getValueFromTextNode", () => {
4+
const valueInsideTextNode = "valueInsideTextNode";
5+
6+
it("doesn't modify object if #text is absent", () => {
7+
const input = {
8+
key: "value",
9+
keyObj: {
10+
keyInsideObj: "valueInsideObj"
11+
}
12+
};
13+
const output = getValueFromTextNode(input);
14+
expect(output).toBe(input);
15+
});
16+
17+
it("populates key with value in #text at first level", () => {
18+
const input = {
19+
key: "value",
20+
keyWithoutTextNode: {
21+
key: "value"
22+
},
23+
keyWithTextNode: {
24+
"#text": valueInsideTextNode
25+
}
26+
};
27+
const output = getValueFromTextNode(input);
28+
expect(output.key).toBe(input.key);
29+
expect(output.keyWithoutTextNode).toBe(input.keyWithoutTextNode);
30+
expect(output.keyWithTextNode).toBe(valueInsideTextNode);
31+
});
32+
33+
it("populates key with value in #text at second level", () => {
34+
const input = {
35+
key: "value",
36+
keyWithoutTextNodeAtAnyLevel: {
37+
keyObj: {
38+
key: "value"
39+
}
40+
},
41+
keyWithTextNodeAtLevel2: {
42+
keyWithTextNode: {
43+
"#text": valueInsideTextNode
44+
}
45+
}
46+
};
47+
const output = getValueFromTextNode(input);
48+
expect(output.key).toBe(input.key);
49+
expect(output.keyWithoutTextNodeAtAnyLevel).toBe(
50+
input.keyWithoutTextNodeAtAnyLevel
51+
);
52+
expect(output.keyWithTextNodeAtLevel2.keyWithTextNode).toBe(
53+
valueInsideTextNode
54+
);
55+
});
56+
});
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
/**
2+
* Recursively parses object and populates value is node from
3+
* "#text" key if it's available
4+
*/
5+
export const getValueFromTextNode = (obj: any) => {
6+
const textNodeName = "#text";
7+
for (const key in obj) {
8+
if (obj.hasOwnProperty(key) && obj[key][textNodeName] !== undefined) {
9+
obj[key] = obj[key][textNodeName];
10+
} else if (typeof obj[key] === "object" && obj[key] !== null) {
11+
obj[key] = getValueFromTextNode(obj[key]);
12+
}
13+
}
14+
return obj;
15+
};

packages/smithy-client/src/index.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ export * from "./document-type";
44
export * from "./exception";
55
export * from "./extended-encode-uri-component";
66
export * from "./get-array-if-single-item";
7+
export * from "./get-value-from-text-node";
78
export * from "./isa";
89
export * from "./lazy-json";
910
export * from "./date-utils";

0 commit comments

Comments
 (0)