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

Jaybell/crud mongoose query params #509

Open
wants to merge 15 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
fix(mongoose): parse and format search, filter and or
- Implements most filter conditions with transform functions to mongoose
- Follows order of important when or and filter conditions exist together
- TODO: nested queries
  • Loading branch information
yharaskrik committed May 14, 2020
commit f6e2ce67fc9c5338f901255006ab5d4984c93dfc
2 changes: 1 addition & 1 deletion packages/crud-mongoose/package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "nest-crud-mongoose",
"name": "@nestjsx/crud-mongoose",
"description": "NestJs CRUD for RESTful APIs - Mongoose",
"version": "0.0.5",
"license": "MIT",
Expand Down
86 changes: 76 additions & 10 deletions packages/crud-mongoose/src/mongoose-crud.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,13 +18,15 @@ import {
isArrayFull,
isNil,
isObject,
isObjectFull,
isUndefined,
objKeys,
} from '@nestjsx/util';
/**
* mongoose imports
*/
import { Document, DocumentQuery, Model, Schema, Types } from 'mongoose';
import { MONGOOSE_OPERATOR_MAP } from 'nest-crud-mongoose/mongoose-operator-map';
import { DeepPartial, ObjectLiteral } from 'typeorm';

/**
Expand Down Expand Up @@ -421,23 +423,87 @@ export class MongooseCrudService<T extends Document> extends CrudService<T> {
options: CrudRequestOptions,
parsed: ParsedRequestParams,
): any {
const filter = this.queryFilterToSearch(options.query.filter);
const paramsFilter = this.queryFilterToSearch(parsed.paramsFilter);

return { ...filter, ...paramsFilter };
const hasSearch = isObjectFull(parsed.search);

if (hasSearch) {
const search = this.queryFilterToSearch(parsed.search);
return {
...search,
...paramsFilter,
};
}

const filters = parsed.filter.filter(
(condition) => !!condition && isObjectFull(condition),
);
const ors = parsed.or.filter((condition) => !!condition && isObjectFull(condition));
const filter = this.buildIndividualFilter(filters);
const or = this.buildIndividualFilter(ors);

if (filters.length === 0 && ors.length === 0) {
return {
...paramsFilter,
};
} else if (filters.length === 1 && ors.length === 0) {
return {
$and: filters,
...paramsFilter,
};
} else if (ors.length === 1 && filters.length === 0) {
return {
$or: ors,
...paramsFilter,
};
} else if (filters.length === 1 && ors.length === 1) {
return {
$or: [...filter, ...or],
...paramsFilter,
};
} else {
return {
$or: [
{
$and: ors,
},
{
$and: filters,
},
],
...paramsFilter,
};
}
}

private buildIndividualFilter(filters: any[]): any[] {
return filters
.filter((filter) => !!MONGOOSE_OPERATOR_MAP[filter.operator])
.map((filter) => MONGOOSE_OPERATOR_MAP[filter.operator](filter.value));
}

private queryFilterToSearch(filter: any): any {
return isArrayFull(filter)
? filter.reduce(
(prev, item) => ({
...prev,
[item.field]: { [item.operator]: item.value },
}),
{},
)
: isObject(filter)
? filter
.filter((item) => !!MONGOOSE_OPERATOR_MAP[item.operator])
.reduce(
(prev, item) => ({
...prev,
[item.field]: MONGOOSE_OPERATOR_MAP[item.operator](item.value),
}),
{},
)
: isObject(filter)
? Object.keys(filter).reduce((prev, key) => {
const conditions = isArrayFull(filter[key])
? filter[key].filter((condition) => !!condition && isObjectFull(condition))
: [];

return {
...prev,
...(conditions.length > 0 ? { [key]: conditions } : {}),
};
}, {})
: {};
}

Expand Down
21 changes: 21 additions & 0 deletions packages/crud-mongoose/src/mongoose-operator-map.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
export const MONGOOSE_OPERATOR_MAP: { [key: string]: (value?: any) => any } = {
$eq: (value) => ({
$eq: value,
}),
$ne: (value) => ({
$ne: value,
}),
$gt: (value) => ({ $gt: value }),
$lt: (value) => ({ $lt: value }),
$gte: (value) => ({ $gte: value }),
$lte: (value) => ({ $lte: value }),
$in: (value) => ({ $in: value }),
$notin: (value) => ({ $nin: value }),
$isnull: () => ({ $eq: null }),
$notnull: () => ({ $ne: null }),
$between: (value: any[]) => ({ $gt: Math.min(...value), $lt: Math.max(...value) }),
$starts: (value) => ({ $regex: `/^${value}.*$/` }),
$end: (value) => ({ $regex: `/^.*${value}$/` }),
$cont: (value) => ({ $regex: `/^.*${value}.*$/` }),
$excl: (value) => ({ $regex: `/^((?!${value}).)*$/` }),
};
31 changes: 16 additions & 15 deletions packages/crud-mongoose/test/b.query-params.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
MONGO_URI,
} from '../../../integration/crud-mongoose/mongoose.config';
import {
Post,
PostDocument,
postSchema,
PostsService,
Expand Down Expand Up @@ -125,21 +126,21 @@ describe('#crud-typeorm', () => {
// });
// });
//
// describe('#query filter', () => {
// it('should return data with limit', (done) => {
// const query = qb.setLimit(4).query();
// return request(server)
// .get('/companies')
// .query(query)
// .end((_, res) => {
// expect(res.status).toBe(200);
// expect(res.body.length).toBe(4);
// res.body.forEach((e: Company) => {
// expect(e.id).not.toBe(1);
// });
// done();
// });
// });
describe('#query filter', () => {
it('should return one post', (done) => {
const query = qb
.setFilter({ field: 'name', operator: '$eq', value: 'john2' })
.query();
return request(server)
.get('/users')
.query(query)
.end((_, res) => {
expect(res.status).toBe(200);
expect(res.body.length).toBe(1);
done();
});
});
});
// it('should return with maxLimit', (done) => {
// const query = qb.setLimit(7).query();
// return request(server)
Expand Down