Skip to content

Commit

Permalink
Map output file and type name to custom string
Browse files Browse the repository at this point in the history
  • Loading branch information
mkubliniak committed Apr 7, 2021
1 parent e95ae4c commit 09781b6
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 5 deletions.
9 changes: 7 additions & 2 deletions src/analyseSchemaFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,17 @@ export function convertSchemaInternal(
exportedName?: string
): ConvertedType | undefined {
const details = joi.describe() as Describe;
const name = details?.flags?.label || exportedName;
const defaultName = details?.flags?.label || exportedName;

if (!name) {
if (!defaultName) {
throw new Error(`At least one "object" does not have a .label(). Details: ${JSON.stringify(details)}`);
}

const name = settings.mapTypeName(defaultName);
if (!name) {
throw new Error(`Resulting type name cannot be empty. Default name was: ${defaultName}`);
}

if (settings.debug && name.toLowerCase().endsWith('schema')) {
console.debug(
`It is recommended you update the Joi Schema '${name}' similar to: ${name} = Joi.object().label('${name.replace(
Expand Down
10 changes: 7 additions & 3 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ function defaultSettings(settings: Partial<Settings>): Settings {
sortPropertiesByName: true,
commentEverything: false,
ignoreFiles: [],
indentationChacters: ' '
indentationChacters: ' ',
mapTypeFileName: (name: string) => name,
mapTypeName: (name: string) => name
},
settings
) as Settings;
Expand All @@ -46,9 +48,11 @@ export function convertSchema(
}

export function getTypeFileNameFromSchema(schemaFileName: string, settings: Settings): string {
return schemaFileName.endsWith(`${settings.schemaFileSuffix}.ts`)
return settings.mapTypeFileName(
schemaFileName.endsWith(`${settings.schemaFileSuffix}.ts`)
? schemaFileName.substring(0, schemaFileName.length - `${settings.schemaFileSuffix}.ts`.length)
: schemaFileName.replace('.ts', '');
: schemaFileName.replace('.ts', '')
);
}

/**
Expand Down
12 changes: 12 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,18 @@ export interface Settings {
* @default ' ' (two spaces)
*/
readonly indentationChacters: string;

/**
* Can be used to customize the name of the generated file.
* @default (name: string) => name
*/
readonly mapTypeFileName: (name: string) => string;

/**
* Can be used to customize resulting type name.
* @default (name: string) => name
*/
readonly mapTypeName: (name: string) => string;
}

export interface ConvertedType {
Expand Down

0 comments on commit 09781b6

Please sign in to comment.