Created
October 27, 2022 13:41
-
-
Save timostamm/9bafd4133e886978cf6647b4fa0b26c1 to your computer and use it in GitHub Desktop.
Using exports and imports in @bufbuild/protoplugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {localName, GeneratedFile, ImportSymbol, Schema} from "@bufbuild/protoplugin/ecmascript"; | |
import type {DescMessage} from "@bufbuild/protobuf"; | |
export function generateTs(schema: Schema) { | |
const map = new Map<DescMessage, ImportSymbol>(); | |
function getFunctionName(f: GeneratedFile, message: DescMessage): ImportSymbol { | |
let s = map.get(message); | |
if (!s) { | |
s = f.export(`validate${localName(message)}`); | |
map.set(message, s); | |
} | |
return s; | |
} | |
function generateMessage(f: GeneratedFile, message: DescMessage) { | |
f.print("export function ", getFunctionName(f, message), "() {"); | |
for (const field of message.fields) { | |
if (field.fieldKind === "message") { | |
f.print(" ", getFunctionName(f, field.message), "();"); | |
} | |
} | |
f.print("}"); | |
for (const nestedMessage of message.nestedMessages) { | |
generateMessage(f, nestedMessage); | |
} | |
} | |
for (const file of schema.files) { | |
const f = schema.generateFile(file.name + "_validate.ts"); | |
for (const message of file.messages) { | |
generateMessage(f, message); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
But quite frankly, this is pretty awkward 🙈
Your
f.import(name, ...
above seems much more straight forward!Thanks for shaking this out ❤️