60 lines
2.1 KiB
JavaScript
60 lines
2.1 KiB
JavaScript
const fs = require("fs");
|
|
const path = require("path");
|
|
|
|
// This script reads prisma/schema.prisma and extracts model names, then
|
|
// generates src/types/db-client.d.ts similar to the JSON generator.
|
|
|
|
const schemaPath = path.resolve(process.cwd(), "prisma", "schema.prisma");
|
|
const outPath = path.resolve(process.cwd(), "src", "types", "db-client.d.ts");
|
|
|
|
if (!fs.existsSync(schemaPath)) {
|
|
console.error("prisma/schema.prisma not found");
|
|
process.exit(1);
|
|
}
|
|
|
|
const content = fs.readFileSync(schemaPath, "utf8");
|
|
|
|
// Very simple parser: find `model <Name> {` occurrences
|
|
const modelRegex = /model\s+(\w+)\s+\{/g;
|
|
let match;
|
|
const models = [];
|
|
while ((match = modelRegex.exec(content)) !== null) {
|
|
models.push(match[1]);
|
|
}
|
|
|
|
if (models.length === 0) {
|
|
console.warn(
|
|
"No models found in prisma/schema.prisma. Run `npx prisma db pull` first."
|
|
);
|
|
}
|
|
|
|
function toTableName(model) {
|
|
// Use the model name lowercased with no modifications so table names
|
|
// match the model names exactly (except for case).
|
|
return model.toLowerCase();
|
|
}
|
|
|
|
let out = `// GENERATED FILE — derived from prisma/schema.prisma (run scripts/prisma-to-dbtypes.js)\n\n`;
|
|
out += `type DBAction<TRequest = any, TResponse = any> = (payload?: TRequest) => Promise<TResponse>;\n\n`;
|
|
|
|
out += `interface DBTables {\n`;
|
|
for (const m of models) {
|
|
const t = toTableName(m);
|
|
out += ` ${t}: {\n`;
|
|
out += ` create: DBAction<{ data: any }, any>;\n`;
|
|
out += ` update: DBAction<{ where: any; data: any }, any>;\n`;
|
|
out += ` delete: DBAction<{ where: any }, any>;\n`;
|
|
out += ` findFirst: DBAction<{ where?: any; include?: any; select?: any }, any>;\n`;
|
|
out += ` findMany: DBAction<any, any[]>;\n`;
|
|
out += ` };\n`;
|
|
}
|
|
out += `}\n\n`;
|
|
|
|
out += `type DBClient = {\n [K in keyof DBTables]: DBTables[K];\n} & { [table: string]: { [action: string]: DBAction<any, any> } };\n\n`;
|
|
|
|
out += `declare module "@/lib/dbClient" {\n const db: DBClient;\n export default db;\n}\n`;
|
|
|
|
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
|
fs.writeFileSync(outPath, out, "utf8");
|
|
console.log("Wrote", outPath, "with models:", models.join(", "));
|