Skip to content

Instantly share code, notes, and snippets.

@virtuallyunknown
Last active April 25, 2023 02:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save virtuallyunknown/bdb68925ab2a40c0e4e07ba8ca30741e to your computer and use it in GitHub Desktop.
Save virtuallyunknown/bdb68925ab2a40c0e4e07ba8ca30741e to your computer and use it in GitHub Desktop.
Generate runtime types from .ts file generated by kysely-codegen.
import { readFile, writeFile } from "node:fs/promises";
import { normalize } from "node:path";
import { inspect } from "node:util";
import { Project } from "ts-morph";
async function tryReadFile(path) {
try {
return await readFile(path, { encoding: "utf-8" });
} catch {
return null;
}
}
/**
* Generate runtime types from kysely-codegen file and write them to an output file.
* @param {object} options
* @param {string} options.srcFile - The path to the kysely-codegen file containing type definitions to generate runtime types for.
* @param {string} options.outFile - The path to write the generated runtime types to.
* @param {string} options.typesImport - The path to import types from, relative to outFile.
*/
export async function kyselyRuntimeTypes({ srcFile, outFile, typesImport }) {
if (normalize(srcFile) === normalize(outFile)) {
throw new Error(`Attempting to overwrite source file at "${srcFile}".\n`);
}
const banner = `/** Generated by ts-morph script do not edit. */\n\n`;
const file = await tryReadFile(outFile);
if (file && !file.startsWith(banner)) {
throw new Error(`Attempting to overwrite non-generated file at "${outFile}".\n`);
}
const dbJs = {};
const project = new Project().addSourceFileAtPath(srcFile);
const dbType = project.getInterfaceOrThrow("DB");
for (const prop of dbType.getProperties()) {
const propName = prop.getName();
dbJs[propName] = project
.getInterfaceOrThrow(prop.getFirstChildByKindOrThrow(180).getText())
.getProperties()
.map((prop) => prop.getName());
}
let output = `${banner}`;
output += `import type { DB } from '${typesImport}';\n\n`;
output += "type DBDummy = {\n";
output += " readonly [K in keyof DB]: ReadonlyArray<keyof DB[K]>;\n";
output += "}\n\n";
output += `export const dbDummy: DBDummy = ${inspect(dbJs, { showHidden: false, compact: false })} as const;`;
await writeFile(outFile, output, { encoding: "utf-8" });
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment