Skip to content

Commit

Permalink
feat: add ability to check if model has been saved (#347)
Browse files Browse the repository at this point in the history
  • Loading branch information
zacharygolba authored Aug 29, 2016
1 parent 6474d51 commit d9e0062
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 2 deletions.
3 changes: 3 additions & 0 deletions src/packages/database/constants.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
// @flow
import type { Model } from './index';

export const NEW_RECORDS: WeakSet<Model> = new WeakSet();
export const UNIQUE_CONSTRAINT = /UNIQUE\sCONSTRAINT/ig;

export const VALID_DRIVERS = [
Expand Down
16 changes: 15 additions & 1 deletion src/packages/database/model/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// @flow
import { pluralize } from 'inflection';

import { NEW_RECORDS } from '../constants';

import Query from '../query';
import { sql } from '../../logger';
import { saveRelationships } from '../relationship';
Expand Down Expand Up @@ -138,7 +140,7 @@ class Model {
*/
static relationshipNames: Array<string>;

constructor(attrs: {} = {}, initialize: boolean = true) {
constructor(attrs: Object = {}, initialize: boolean = true) {
const { constructor: { attributeNames, relationshipNames } } = this;

Object.defineProperties(this, {
Expand Down Expand Up @@ -185,13 +187,23 @@ class Model {
Object.freeze(this);
}

NEW_RECORDS.add(this);

return this;
}

get isNew(): boolean {
return NEW_RECORDS.has(this);
}

get isDirty(): boolean {
return Boolean(this.dirtyAttributes.size);
}

get persisted(): boolean {
return !this.isNew && !this.isDirty;
}

static get hasOne(): Object {
return Object.freeze({});
}
Expand Down Expand Up @@ -354,6 +366,7 @@ class Model {
await query;
}

NEW_RECORDS.delete(this);
this.dirtyAttributes.clear();

if (typeof afterUpdate === 'function') {
Expand Down Expand Up @@ -498,6 +511,7 @@ class Model {
});

Object.freeze(instance);
NEW_RECORDS.delete(instance);

if (typeof afterCreate === 'function') {
await afterCreate(instance);
Expand Down
7 changes: 6 additions & 1 deletion src/packages/database/query/utils/build-results.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// @flow
import { camelize, singularize } from 'inflection';

import { NEW_RECORDS } from '../../constants';

import Model from '../../model';

import entries from '../../../../utils/entries';
Expand Down Expand Up @@ -124,6 +126,9 @@ export default async function buildResults<T: Model>({
};
}, {});

return Reflect.construct(model, [record]);
const instance = Reflect.construct(model, [record]);

NEW_RECORDS.delete(instance);
return instance;
});
}

0 comments on commit d9e0062

Please sign in to comment.