Skip to content

Commit

Permalink
Merge pull request #248 from stillalivx/master
Browse files Browse the repository at this point in the history
  • Loading branch information
eveningkid authored Apr 29, 2021
2 parents 9a19bdb + 2b591a4 commit eb3830b
Showing 1 changed file with 23 additions and 10 deletions.
33 changes: 23 additions & 10 deletions lib/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,6 +265,27 @@ export class Model {
return this._formatField(this._fieldMatching.toClient, field, camelCase);
}

/* Wraps values with defaults. */
private static _wrapValuesWithDefaults(values: Values): Values {
for (const field of Object.keys(this.fields)) {
if (values.hasOwnProperty(field)) {
continue;
}

if (this.defaults.hasOwnProperty(field)) {
const defaultValue = this.defaults[field];

if (typeof defaultValue === "function") {
values[field] = defaultValue();
} else {
values[field] = defaultValue;
}
}
}

return values;
}

/** Add an event listener for a specific operation/hook.
*
* Flight.on('created', (model) => console.log('New model:', model));
Expand Down Expand Up @@ -428,7 +449,7 @@ export class Model {
const results = await this._runQuery(
this._currentQuery.table(this.table).create(
insertions.map((field) =>
this.formatFieldToDatabase(field)
this.formatFieldToDatabase(this._wrapValuesWithDefaults(field))
) as Values[],
).toDescription(),
);
Expand Down Expand Up @@ -944,19 +965,11 @@ export class Model {
*/
async save() {
const model = this.constructor as ModelSchema;

const values: Values = {};

for (const field of Object.keys(model.fields)) {
if (this.hasOwnProperty(field)) {
values[field] = (this as any)[field];
} else if (model.defaults.hasOwnProperty(field)) {
const defaultValue = model.defaults[field];

if (typeof defaultValue === "function") {
values[field] = defaultValue();
} else {
values[field] = defaultValue;
}
}
}

Expand Down

0 comments on commit eb3830b

Please sign in to comment.