Skip to content

Commit acd67f6

Browse files
authored
fixed class and creation fields optionality (#546)
In TypeScript, no longer make fields optional just because they have a defaultValue. Fields must be nullable to be optional. Fields with defaultValue are optional in CreationAttributes, but not in class definition.
1 parent 67742d0 commit acd67f6

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

src/auto-generator.ts

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,13 @@ export class AutoGenerator {
111111
if (primaryKeys.length) {
112112
str += `export type #TABLE#Pk = ${primaryKeys.map((k) => `"${recase(this.options.caseProp, k)}"`).join(' | ')};\n`;
113113
str += `export type #TABLE#Id = #TABLE#[#TABLE#Pk];\n`;
114-
str += "export type #TABLE#CreationAttributes = Optional<#TABLE#Attributes, #TABLE#Pk>;\n\n";
114+
}
115+
116+
const creationOptionalFields = this.getTypeScriptCreationOptionalFields(table);
117+
118+
if (creationOptionalFields.length) {
119+
str += `export type #TABLE#OptionalAttributes = ${creationOptionalFields.map((k) => `"${recase(this.options.caseProp, k)}"`).join(' | ')};\n`;
120+
str += "export type #TABLE#CreationAttributes = Optional<#TABLE#Attributes, #TABLE#OptionalAttributes>;\n\n";
115121
} else {
116122
str += "export type #TABLE#CreationAttributes = #TABLE#Attributes;\n\n";
117123
}
@@ -528,6 +534,14 @@ export class AutoGenerator {
528534
});
529535
}
530536

537+
private getTypeScriptCreationOptionalFields(table: string): Array<string> {
538+
const fields = _.keys(this.tables[table]);
539+
return fields.filter((field): boolean => {
540+
const fieldObj = this.tables[table][field];
541+
return fieldObj.allowNull || (!!fieldObj.defaultValue || fieldObj.defaultValue === "") || fieldObj.primaryKey;
542+
});
543+
}
544+
531545
/** Add schema to table so it will match the relation data. Fixes mysql problem. */
532546
private addSchemaForRelations(table: string) {
533547
if (!table.includes('.') && !this.relations.some(rel => rel.childTable === table)) {
@@ -647,7 +661,7 @@ export class AutoGenerator {
647661

648662
private getTypeScriptFieldOptional(table: string, field: string) {
649663
const fieldObj = this.tables[table][field];
650-
return fieldObj.allowNull || (fieldObj.defaultValue || fieldObj.defaultValue === "");
664+
return fieldObj.allowNull;
651665
}
652666

653667
private getTypeScriptType(table: string, field: string) {

0 commit comments

Comments
 (0)