Skip to content

Commit 23263cd

Browse files
author
Tate
committed
add map type
1 parent 1db68fa commit 23263cd

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

Diff for: src/autogenerate/index.ts

+5
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,11 @@ function writeTypes(types: ProtoTypes[]): string {
2020
}
2121
if (node.type === "enum") {
2222
result += `export type ${name} = typeof ${node.content.fullyQualifiedName}[keyof typeof ${node.content.fullyQualifiedName}];\n\n`;
23+
} else if (node.type === "message" && node.content.isMap) {
24+
result += `export type ${name} = Record<
25+
${node.content.fields[0].tsType},
26+
${node.content.fields[1].tsType} | undefined>;`;
27+
result += `\n\n`;
2328
} else {
2429
result += `export interface ${name} {\n`;
2530
node.content.fields.forEach(

Diff for: src/utils.ts

+26-3
Original file line numberDiff line numberDiff line change
@@ -46,8 +46,8 @@ export function commandIsInPath(cmd: string): boolean {
4646
}
4747
}
4848

49-
type ReaderMethod = keyof BinaryReader;
50-
type WriterMethod = keyof BinaryWriter;
49+
type ReaderMethod = keyof BinaryReader | "map";
50+
type WriterMethod = keyof BinaryWriter | "map";
5151

5252
interface Descriptor {
5353
defaultValue: string;
@@ -183,6 +183,21 @@ export function getDescriptor(
183183
identifierTable,
184184
fileDescriptorProto
185185
);
186+
// Hack until better option:
187+
// https://github.com/protocolbuffers/protobuf/issues/9369
188+
const isMap =
189+
_type.endsWith("Entry") && !field.toArray()[0].endsWith("Entry");
190+
191+
if (isMap) {
192+
return {
193+
defaultValue: "{}",
194+
optional,
195+
read: "map",
196+
repeated: false,
197+
tsType: name.slice(0, name.lastIndexOf("Entry")),
198+
write: "map",
199+
};
200+
}
186201

187202
return {
188203
defaultValue: "undefined",
@@ -445,6 +460,7 @@ interface MessageOpts {
445460
fullyQualifiedName: string;
446461
fields: Field[];
447462
comments?: Comments;
463+
isMap: boolean;
448464
}
449465

450466
type EnumType = { type: "enum"; content: EnumOpts };
@@ -627,15 +643,22 @@ export function processTypes(
627643
}
628644

629645
function getMessage(namespacing: string, node: DescriptorProto): MessageOpts {
630-
const name = node.getName();
646+
let name = node.getName();
631647
if (!name) {
632648
throw new Error(`Expected name for ${node}`);
633649
}
650+
651+
// Hack until better option:
652+
// https://github.com/protocolbuffers/protobuf/issues/9369
653+
const isMap = name.endsWith("Entry") && node.getFieldList().length == 2;
654+
name = isMap ? name.slice(0, name.lastIndexOf("Entry")) : name;
655+
634656
const opts: MessageOpts = {
635657
name,
636658
fullyQualifiedName: applyNamespace(namespacing, name, {
637659
removeLeadingPeriod: true,
638660
}),
661+
isMap,
639662
fields: node
640663
.getFieldList()
641664
.map((value) => {

0 commit comments

Comments
 (0)