dohomi / storyblok-generate-ts

Generates TypeScript interface types based on Storyblok component file
MIT License
102 stars 33 forks source link

Return promise, resolve tsString output, skip write to file if path is set to null #25

Closed scmx closed 1 year ago

scmx commented 1 year ago

Hi 👋 ! Nice library. Been using it for a while. Here's some suggested changes:

1. Return promise from storyblokToTypescript node api

Otherwise the node api can't really be used when you can't know when it completes.

2. Change return Promise<string>[] resolve tsString

Change result Promise<void> into Promise<string[]>, returning the tsString output.

3. Skip write file if path null

Skip write the tsString to path location if empty string is passed in as path. Default value is a string so it will continue to save by default.


The first change is the most interesting one for me. I am currently working around all three things by:

  1. Shelling out to the CLI command instead of using node api
  2. Reading the file, doing some changes and writing the file again
scmx commented 1 year ago

FYI: Here's the patch I've doing to the resulting file Maybe some of this should end up in a pull request.

function fixTypesFileInconsistencies(typesFile: string) {
    const lines = fs.readFileSync(typesFile, 'utf-8').split('\n');

    const newLines = lines.flatMap((line) => {
        if (line === 'export interface AssetStoryblok {') {
            return [line, `\tfocus?: null;`, `\tfieldtype?: 'asset';`];
        }
        if (line === `\t_uid: string;`) {
            return [line, `\t_editable?: string;`];
        }
        if (line === `\t[k: string]: any;`) {
            return [];
        }
        return [line];
    });

    fs.writeFileSync(typesFile, newLines.join('\n'));
}
  1. Remove the [k: string]: any typing. This typing has caused many issues and we were very happy to get rid of it
  2. Add the missing _editable?: string typing for preview mode
  3. Add typing of focus and fieldtype. I think I added this because I got an error about these after removing the [k: string]: any