Skip to content

Commit

Permalink
refactor: move query proxy to initializer function
Browse files Browse the repository at this point in the history
  • Loading branch information
zacharygolba committed Jun 12, 2016
1 parent b53c58a commit b6700be
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 20 deletions.
24 changes: 4 additions & 20 deletions src/packages/database/query/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { camelize } from 'inflection';
import Model from '../model';
import { sql } from '../../logger';

import initialize from './initialize';

import entries from '../../../utils/entries';
import tryCatch from '../../../utils/try-catch';
import formatSelect from './utils/format-select';
Expand All @@ -11,7 +13,7 @@ import buildResults from './utils/build-results';
/**
* @private
*/
class Query extends Object {
class Query {
/**
* @private
*/
Expand All @@ -38,8 +40,6 @@ class Query extends Object {
relationships: Object;

constructor(model: typeof Model): Query {
super();

Object.defineProperties(this, {
model: {
value: model,
Expand Down Expand Up @@ -77,23 +77,7 @@ class Query extends Object {
}
});

return new Proxy(this, {
get(instance: Query, key: string, receiver: Proxy): ?mixed | void {
if (model.hasScope(key)) {
const scope = model.scopes[key];

return (...args) => {
let { snapshots } = scope.apply(model, args);
snapshots = snapshots.map(snapshot => [...snapshot, key]);

instance.snapshots.push(...snapshots);
return receiver;
};
} else {
return instance[key];
}
}
});
return initialize(this);
}

all(): Query {
Expand Down
26 changes: 26 additions & 0 deletions src/packages/database/query/initialize.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import type Query from './index';

const TRAPS = {
get(target: Query, key: string, receiver: Proxy): ?mixed | void {
if (target.model.hasScope(key)) {
const scope = target.model.scopes[key];

return (...args) => {
let { snapshots } = scope.apply(target.model, args);
snapshots = snapshots.map(snapshot => [...snapshot, key]);

target.snapshots.push(...snapshots);
return receiver;
};
} else {
return target[key];
}
}
};

/**
* @private
*/
export default function initialize(instance: Query): Query {
return new Proxy(instance, TRAPS);
}

0 comments on commit b6700be

Please sign in to comment.