dyne / starters

📐 Projects template starters of Dyne.org
7 stars 1 forks source link

Generate enums from keys of generated pocketbase types #67

Closed bbtgnn closed 1 year ago

bbtgnn commented 1 year ago

Context

CRUD components ask for the names of collection fields to be displayed. It would be nice to have an enum or something similar that can store the names of the fields.

Proposed solution

An idea could be to parse $lib/pocketbase-types.ts and generate a file with the enums.

This is a sample code written by ChatGPT that could be checked and implemented:

import * as ts from 'typescript';
import { writeFileSync, readFileSync } from 'fs';

// Read the TypeScript file
const filePath = '../src/lib/pocketbase-types.ts';
const sourceCode = readFileSync(filePath, 'utf-8');

// Parse the TypeScript file
const sourceFile = ts.createSourceFile(filePath, sourceCode, ts.ScriptTarget.Latest, true);

// Type and interface visitor
const enumVisitor = {
    visitNode(node) {
        if (ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node)) {
            const typeName = node.name.text;
            const keys = node.members
                .filter(ts.isPropertySignature)
                .map((member) => member.name.getText());

            // Generate the enum code
            const enumCode = `enum ${typeName}Enum {${keys.join(',\n  ')}}`;

            // Write the enum code to a file
            const enumFilePath = `${typeName}.enum.ts`;
            writeFileSync(enumFilePath, enumCode);

            console.log(`Enum generated for ${typeName}: ${enumFilePath}`);
        }

        return ts.visitEachChild(node, this.visitNode, this);
    }
};

// Visit each node in the source file
ts.visitNode(sourceFile, enumVisitor);
bbtgnn commented 1 year ago

No need to do this, as #258 adds type safety to $lib/forms input fields