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

Support multiple match filters #3

Merged
merged 4 commits into from
Sep 15, 2023
Merged
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
55 changes: 54 additions & 1 deletion src/domain/services/query.service.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
ProductAdditivesTag,
ProductAminoAcidsTag,
ProductIngredientsTag,
ProductNucleotidesTag,
ProductOriginsTag,
} from '../entities/product-tags';
import { QueryService } from './query.service';
Expand Down Expand Up @@ -75,6 +76,19 @@ describe('count', () => {
}
});
});
it('should cope with more than two filters', async () => {
await createTestingModule([DomainModule], async (app) => {
const { originValue, aminoValue, neucleotideValue } =
await createTestTags(app);
const queryService = app.get(QueryService);
const response = await queryService.count({
origins_tags: originValue,
amino_acids_tags: aminoValue,
nucleotides_tags: neucleotideValue,
});
expect(response).toBe(1);
});
});
});

describe('aggregate', () => {
Expand Down Expand Up @@ -136,6 +150,26 @@ describe('aggregate', () => {
expect(parseInt(response['origins_tags'])).toBe(beforeCount + 1);
});
});

it('should cope with multiple filters', async () => {
await createTestingModule([DomainModule], async (app) => {
const { originValue, aminoValue, neucleotideValue } =
await createTestTags(app);
const queryService = app.get(QueryService);
const response = await queryService.aggregate([
{
$match: {
amino_acids_tags: aminoValue,
nucleotides_tags: neucleotideValue,
},
},
{ $group: { _id: '$origins_tags' } },
]);
const myTag = response.find((r) => r._id === originValue);
expect(myTag).toBeTruthy();
expect(parseInt(myTag.count)).toBe(1);
});
});
});

async function createTestTags(app) {
Expand All @@ -147,6 +181,14 @@ async function createTestTags(app) {
// Using origins and amino acids as they are smaller than most
const originValue = randomCode();
const aminoValue = randomCode();
const neucleotideValue = randomCode();

// Matrix for testing
// Product | Origin | AminoAcid | Neucleotide
// Product1 | x | x | x
// Product2 | x | x |
// Product3 | x | | x

em.create(ProductOriginsTag, {
product: product1,
value: originValue,
Expand All @@ -159,6 +201,7 @@ async function createTestTags(app) {
product: product3,
value: originValue,
});

em.create(ProductAminoAcidsTag, {
product: product1,
value: aminoValue,
Expand All @@ -167,6 +210,16 @@ async function createTestTags(app) {
product: product2,
value: aminoValue,
});

em.create(ProductNucleotidesTag, {
product: product1,
value: neucleotideValue,
});
em.create(ProductNucleotidesTag, {
product: product3,
value: neucleotideValue,
});

await em.flush();
return { originValue, aminoValue };
return { originValue, aminoValue, neucleotideValue };
}
73 changes: 32 additions & 41 deletions src/domain/services/query.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { EntityName } from '@mikro-orm/core';
import { EntityManager } from '@mikro-orm/postgresql';
import { EntityManager, QueryBuilder } from '@mikro-orm/postgresql';
import {
Injectable,
Logger,
Expand Down Expand Up @@ -35,23 +35,8 @@ export class QueryService {
}
qb.where('not pt.obsolete');

const matchTag = Object.keys(match)[0];
let matchValue = Object.values(match)[0];
const not = matchValue?.['$ne'];
if (matchTag) {
if (not) {
matchValue = not;
}
const { entity: matchEntity, column: matchColumn } =
this.getEntityAndColumn(matchTag);
const qbWhere = this.em
.createQueryBuilder(matchEntity, 'pt2')
.select('*')
.where(`pt2.product_id = pt.product_id and pt2.${matchColumn} = ?`, [
matchValue,
]);
qb.andWhere(`${not ? 'NOT ' : ''}EXISTS (${qbWhere.getKnexQuery()})`);
}
const whereLog = this.addMatches(match, qb);

if (count) {
qb = this.em.createQueryBuilder(qb, 'temp');
qb.select('count(*) count');
Expand All @@ -66,7 +51,7 @@ export class QueryService {
//this.logger.log(results);
this.logger.debug(
`Processed ${tag}${
matchTag ? ` where ${matchTag} ${not ? '!=' : '=='} ${matchValue}` : ''
whereLog.length ? ` where ${whereLog.join(' and ')}` : ''
} in ${Date.now() - start} ms. Returning ${results.length} records`,
);
if (count) {
Expand All @@ -78,6 +63,28 @@ export class QueryService {
return results;
}

private addMatches(match: any, qb: QueryBuilder<object>) {
const whereLog = [];
for (const [matchTag, matchValue] of Object.entries(match)) {
let whereValue = matchValue;
const not = matchValue?.['$ne'];
if (not) {
whereValue = not;
}
const { entity: matchEntity, column: matchColumn } =
this.getEntityAndColumn(matchTag);
const qbWhere = this.em
.createQueryBuilder(matchEntity, 'pt2')
.select('*')
.where(`pt2.product_id = pt.product_id and pt2.${matchColumn} = ?`, [
whereValue,
]);
qb.andWhere(`${not ? 'NOT ' : ''}EXISTS (${qbWhere.getKnexQuery()})`);
whereLog.push(`${matchTag} ${not ? '!=' : '=='} ${whereValue}`);
}
return whereLog;
}

async count(body: any) {
const start = Date.now();
this.logger.debug(body);
Expand All @@ -95,32 +102,16 @@ export class QueryService {
matchValue = not;
}
qb.andWhere(`${not ? 'NOT ' : ''}pt.${column} = ?`, [matchValue]);
const matchTag = tags[1];
let extraMatchLog = '';
if (matchTag) {
let matchValue = body[matchTag];
const not = matchValue?.['$ne'];
if (not) {
matchValue = not;
}
const { entity: matchEntity, column: matchColumn } =
this.getEntityAndColumn(matchTag);
const qbWhere = this.em
.createQueryBuilder(matchEntity, 'pt2')
.select('*')
.where(`pt2.product_id = pt.product_id and pt2.${matchColumn} = ?`, [
matchValue,
]);
qb.andWhere(`${not ? 'NOT ' : ''}EXISTS (${qbWhere.getKnexQuery()})`);
extraMatchLog += ` and ${matchTag} ${not ? '!=' : '=='} ${matchValue}`;
}
delete body[tag];
const whereLog = this.addMatches(body, qb);

this.logger.debug(qb.getFormattedQuery());
const results = await qb.execute();
const response = results[0].count;
this.logger.log(
`Processed ${tag} ${not ? '!=' : '=='} ${matchValue}${extraMatchLog} in ${
Date.now() - start
} ms. Count: ${response}`,
`Processed ${tag} ${not ? '!=' : '=='} ${matchValue}${
whereLog.length ? ` and ${whereLog.join(' and ')}` : ''
} in ${Date.now() - start} ms. Count: ${response}`,
);
return parseInt(response);
}
Expand Down
Loading