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

feat(criteria-to-mongo): ✨ add criteria to mongo converter #14

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
5 changes: 5 additions & 0 deletions .changeset/pink-tigers-drum.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@codelytv/criteria-to-mongo": major
---

add criteria to mongo converter
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ Create a Criteria from:
Convert a Criteria to:
- [Elasticsearch (and esql)](./packages/criteria-to-elasticsearch)
- [MySql](./packages/criteria-to-mysql)
- [MongoDB](./packages/criteria-to-mongo)

You can also create your custom transformer.

Expand Down
23 changes: 23 additions & 0 deletions packages/criteria-to-mongo/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<p align="center">
<a href="https://codely.com">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://codely.com/logo/codely_logo-dark.svg">
<source media="(prefers-color-scheme: light)" srcset="https://codely.com/logo/codely_logo-light.svg">
<img alt="Codely logo" src="https://codely.com/logo/codely_logo.svg">
</picture>
</a>
</p>

<h1 align="center">
🎼 Criteria to MongoDB converter
</h1>

<p align="center">
<a href="https://github.com/CodelyTV"><img src="https://img.shields.io/badge/Codely-OS-green.svg?style=flat-square" alt="codely.com"/></a>
</p>

## 📥 Installation

```sh
npm i @codelytv/criteria-to-mongo
```
20 changes: 20 additions & 0 deletions packages/criteria-to-mongo/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "@codelytv/criteria-to-mongo",
"version": "1.0.0",
"description": "",
"keywords": [],
"author": "Codely (https://codely.com)",
"license": "MIT",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"scripts": {
"test": "node --import tsx --test test/*.test.ts",
"build": "tsc --build --verbose tsconfig.json"
},
"dependencies": {
"@codelytv/criteria": "workspace:^"
},
"devDependencies": {
"@codelytv/criteria-test-mother": "workspace:^"
}
}
108 changes: 108 additions & 0 deletions packages/criteria-to-mongo/src/CriteriaToMongoConverter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { Criteria, Filter, OrderTypes } from "@codelytv/criteria";

type MongoFilterOperator = "$eq" | "$ne" | "$gt" | "$gte" | "$lt" | "$lte" | "$regex";
type MongoFilterOperation = {
[operator in MongoFilterOperator]?: unknown;
};

type MongoFilter =
| {
[field: string]: MongoFilterOperation;
}
| {
[field: string]: { $not: MongoFilterOperation };
};

type MongoSortDirection = 1 | -1;

type MongoSort = {
[field: string]: MongoSortDirection;
};

export type MongoQuery = {
filter: MongoFilter;
sort?: MongoSort;
skip?: number;
limit?: number;
};

export class CriteriaToMongoConverter {
convert(criteria: Criteria): MongoQuery {
const query: MongoQuery = {
filter: {},
};

if (criteria.hasFilters()) {
query.filter = criteria.filters.value.reduce((acc, filter) => {
return { ...acc, ...this.generateMongoFilter(filter) };
}, {});
}

if (criteria.hasOrder()) {
query.sort = {
[criteria.order.orderBy.value]: criteria.order.orderType.value === OrderTypes.ASC ? 1 : -1,
};
}

if (criteria.pageSize !== null) {
query.limit = criteria.pageSize;
}

if (criteria.pageSize !== null && criteria.pageNumber !== null) {
query.skip = criteria.pageSize * (criteria.pageNumber - 1);
}

return query;
}

private generateMongoFilter(filter: Filter): MongoFilter {
const field = filter.field.value;
const value = filter.value.value;

if (filter.operator.isContains()) {
return {
[field]: { $regex: value },
};
}

if (filter.operator.isNotContains()) {
return {
[field]: { $not: { $regex: value } },
};
}

if (filter.operator.isGreaterThan()) {
return {
[field]: { $gt: value },
};
}

if (filter.operator.isGreaterThanOrEqual()) {
return {
[field]: { $gte: value },
};
}

if (filter.operator.isLowerThan()) {
return {
[field]: { $lt: value },
};
}

if (filter.operator.isLowerThanOrEqual()) {
return {
[field]: { $lte: value },
};
}

if (filter.operator.isNotEquals()) {
return {
[field]: { $ne: value },
};
}

return {
[field]: { $eq: value },
};
}
}
1 change: 1 addition & 0 deletions packages/criteria-to-mongo/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from "./CriteriaToMongoConverter";
183 changes: 183 additions & 0 deletions packages/criteria-to-mongo/test/CriteriaToMongoConverter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
import assert from "node:assert";
import { describe, it } from "node:test";

import { CriteriaMother } from "@codelytv/criteria-test-mother";

import { CriteriaToMongoConverter } from "../src";

describe("CriteriaToMongoConverter should", () => {
const converter = new CriteriaToMongoConverter();

it("Generate simple select with an empty criteria", () => {
const actualQuery = converter.convert(CriteriaMother.empty());

assert.deepEqual(actualQuery, { filter: {} });
});

it("Generate select with order", () => {
const actualQuery = converter.convert(CriteriaMother.emptySorted("_id", "DESC"));

assert.deepEqual(actualQuery, {
filter: {},
sort: { _id: -1 },
});
});

it("Generate select with one filter", () => {
const actualQuery = converter.convert(CriteriaMother.withOneFilter("name", "EQUAL", "Javier"));

assert.deepEqual(actualQuery, {
filter: { name: { $eq: "Javier" } },
});
});

it("Generate select with one greater than filter", () => {
const actualQuery = converter.convert(
CriteriaMother.withOneFilter("age", "GREATER_THAN", "25"),
);

assert.deepEqual(actualQuery, {
filter: { age: { $gt: 25 } },
});
});

it("Generate select with one greater than or equal filter", () => {
const actualQuery = converter.convert(
CriteriaMother.withOneFilter("age", "GREATER_THAN_OR_EQUAL", "25"),
);

assert.deepEqual(actualQuery, {
filter: { age: { $gte: 25 } },
});
});

it("Generate select with one lower than filter", () => {
const actualQuery = converter.convert(CriteriaMother.withOneFilter("age", "LOWER_THAN", "18"));

assert.deepEqual(actualQuery, {
filter: { age: { $lt: 18 } },
});
});

it("Generate select with one lower than or equal filter", () => {
const actualQuery = converter.convert(
CriteriaMother.withOneFilter("age", "LOWER_THAN_OR_EQUAL", "18"),
);

assert.deepEqual(actualQuery, {
filter: { age: { $lte: 18 } },
});
});

it("Generate select with one filter sorted", () => {
const actualQuery = converter.convert(
CriteriaMother.withOneFilterSorted("name", "EQUAL", "Javier", "_id", "DESC"),
);

assert.deepEqual(actualQuery, {
filter: { name: { $eq: "Javier" } },
sort: { _id: -1 },
});
});

it("Generate select with multiples filters", () => {
const actualQuery = converter.convert(
CriteriaMother.create({
filters: [
{
field: "name",
operator: "EQUAL",
value: "Javier",
},
{
field: "email",
operator: "EQUAL",
value: "[email protected]",
},
],
orderBy: null,
orderType: null,
pageSize: null,
pageNumber: null,
}),
);

assert.deepEqual(actualQuery, {
filter: {
name: { $eq: "Javier" },
email: { $eq: "[email protected]" },
},
});
});

it("Generate select with multiples filters and sort", () => {
const actualQuery = converter.convert(
CriteriaMother.create({
filters: [
{
field: "name",
operator: "EQUAL",
value: "Javier",
},
{
field: "email",
operator: "EQUAL",
value: "[email protected]",
},
],
orderBy: "_id",
orderType: "DESC",
pageSize: null,
pageNumber: null,
}),
);

assert.deepEqual(actualQuery, {
filter: {
name: { $eq: "Javier" },
email: { $eq: "[email protected]" },
},
sort: { _id: -1 },
});
});

it("Generate select with one contains filter", () => {
const actualQuery = converter.convert(
CriteriaMother.withOneFilter("name", "CONTAINS", "Javier"),
);

assert.deepEqual(actualQuery, {
filter: { name: { $regex: "Javier" } },
});
});

it("Generate select with one not contains filter", () => {
const actualQuery = converter.convert(
CriteriaMother.withOneFilter("name", "NOT_CONTAINS", "Javier"),
);

assert.deepEqual(actualQuery, {
filter: { name: { $not: { $regex: "Javier" } } },
});
});

it("Generate simple select paginated", () => {
const actualQuery = converter.convert(CriteriaMother.emptyPaginated(10, 3));

assert.deepEqual(actualQuery, {
filter: {},
limit: 10,
skip: 20,
});
});

it("Generate select with not equal filter", () => {
const actualQuery = converter.convert(
CriteriaMother.withOneFilter("name", "NOT_EQUAL", "Javier"),
);

assert.deepEqual(actualQuery, {
filter: { name: { $ne: "Javier" } },
});
});
});
7 changes: 7 additions & 0 deletions packages/criteria-to-mongo/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "dist"
},
"include": ["src/**/*"]
}
10 changes: 10 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.