Skip to content

Commit f1f8909

Browse files
committed
Add struct helper and TypeScript configuration for value construction
1 parent 53dfaca commit f1f8909

3 files changed

Lines changed: 50 additions & 0 deletions

File tree

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
import {Value} from "../pb/shared.struct_pb.js";
2+
3+
type AllowedValue = null | number | string | boolean | Array<AllowedValue> | object;
4+
5+
export function constructValue(value: AllowedValue): Value {
6+
if (value === null) {
7+
return {kind: {oneofKind: "nullValue", nullValue: 0}};
8+
}
9+
if (typeof value === "number") {
10+
return {kind: {oneofKind: "numberValue", numberValue: value}};
11+
}
12+
if (typeof value === "string") {
13+
return {kind: {oneofKind: "stringValue", stringValue: value}};
14+
}
15+
if (typeof value === "boolean") {
16+
return {kind: {oneofKind: "boolValue", boolValue: value}};
17+
}
18+
if (Array.isArray(value)) {
19+
const listValues = value.map(v => constructValue(v));
20+
return {
21+
kind: {
22+
oneofKind: "listValue",
23+
listValue: {values: listValues}
24+
}
25+
};
26+
}
27+
if (typeof value === "object") {
28+
const structFields: {[key: string]: Value} = {};
29+
for (const [k, v] of Object.entries(value)) {
30+
structFields[k] = constructValue(v);
31+
}
32+
return {
33+
kind: {
34+
oneofKind: "structValue",
35+
structValue: {fields: structFields}
36+
}
37+
};
38+
}
39+
throw new Error(`Unsupported value type: ${typeof value}`);
40+
}

build/ts/package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525
"protoc": "^33.0.0"
2626
},
2727
"files": [
28+
"helpers/*.ts",
29+
"helpers/*.js",
2830
"pb/*.ts",
2931
"pb/*.js",
3032
"index.js",

build/ts/tsconfig.json

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
{
2+
"compilerOptions": {
3+
"target": "ES2017",
4+
"lib": ["ES2017", "DOM"],
5+
"module": "commonjs",
6+
"strict": true
7+
}
8+
}

0 commit comments

Comments
 (0)