Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement distinct field option for select #11

Open
wants to merge 8 commits into
base: master
Choose a base branch
from
Open
12 changes: 12 additions & 0 deletions lib/controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,18 @@ class Controller extends DataService {
this.actions.select,
);

this.actions.distinct = _.merge(
{},
_.omit(this.actions.default, 'orderBy'),
{
method: ['get', 'head'],
handler: 'distinct',
name: 'distinct',
path: 'distinct/:distinctField'
},
this.actions.distinct
);

this.actions.count = _.merge(
{},
this.actions.select,
Expand Down
40 changes: 40 additions & 0 deletions lib/data-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,46 @@ class DataService {
.then(collection => this._handlePostForCollection(collection, scope));
}

distinct(scope) {
return Bb
.try(this._handlePre.bind(this, scope))
.then(() => {
// pick distinctField value to avoid filter affecting
scope.context.distinctField = scope.req.params.distinctField;
delete scope.req.params.distinctField;
})
.then(this.getFilter.bind(this, scope))
.then((filter) => {
// field list
scope.fieldList = this.extractFieldList(scope);
// q
const q = scope.getQ();
// orderBy
const orderBy = this.getOrderBy(scope);
const pagination = scope.pagination = this.getPagination(scope);
const distinctField = scope.context.distinctField;

return this.dataSource.find({
distinctField: distinctField,
filter: filter,
fields: scope.fieldList,
q: q,
qFields: this.qFields,
limit: pagination.limit,
skip: (pagination.page - 1) * pagination.limit,
queryPipe: this.queryPipe ? (query) => {
this.queryPipe(query, scope);
} : undefined
});
})
.then((collection) => {
return this._handleCollectionPost(collection, scope);
})
.then((collection) => {
return this._handlePostForCollection(collection, scope);
});
}

selectOne(scope) {
return this
.locateModel(scope, true, true)
Expand Down
7 changes: 6 additions & 1 deletion lib/scope.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

const ACTIONS = {
SELECT: 'select',
DISTINCT: 'distinct',
SELECT_ONE: 'selectOne',
INSERT: 'insert',
REPLACE: 'replace',
Expand Down Expand Up @@ -40,7 +41,11 @@ class RestifizerScope {
}

isSelect() {
return this.checkActionName(ACTIONS.SELECT, ACTIONS.SELECT_ONE, ACTIONS.COUNT);
return this.checkActionName(ACTIONS.SELECT, ACTIONS.SELECT_ONE, ACTIONS.COUNT, ACTIONS.DISTINCT);
}

isSelectDistinct() {
return this.checkActionName(ACTIONS.DISTINCT);
}

isChanging() {
Expand Down