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

refactor: create mixin to share helper functions across repos #597

Open
wants to merge 5 commits into
base: master
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
10 changes: 6 additions & 4 deletions src/controllers/organization.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,10 +83,12 @@ export class OrganizationController {

// create query to get all orgs and their planters
if (filter?.where) {
filter.where = await this.organizationRepository.applyOrganizationWhereClause(
filter.where,
organizationId.valueOf(),
);
filter.where =
await this.organizationRepository.applyOrganizationWhereClause(
filter.where,
organizationId.valueOf(),
'orgs',
);
}

const childOrgs = await this.organizationRepository.find(filter);
Expand Down
2 changes: 2 additions & 0 deletions src/controllers/planter.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export class PlanterController {
where = await this.planterRepository.applyOrganizationWhereClause(
whereWithoutOrganizationId,
organizationId,
'planter',
);
}
// console.log('get /planter/count where -->', where);
Expand Down Expand Up @@ -85,6 +86,7 @@ export class PlanterController {
filter.where = await this.planterRepository.applyOrganizationWhereClause(
whereWithoutOrganizationId,
organizationId,
'planter',
);
}

Expand Down
25 changes: 15 additions & 10 deletions src/controllers/planterOrganization.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,16 +62,16 @@ export class PlanterOrganizationController {
const filterOrgId = organizationId;

if (filterOrgId && filterOrgId !== orgId) {
const entityIds = await this.planterRepository.getEntityIdsByOrganizationId(
orgId,
);
const entityIds =
await this.planterRepository.getEntityIdsByOrganizationId(orgId);
orgId = entityIds.includes(filterOrgId) ? filterOrgId : orgId;
}

// Replace organizationId with full entity tree and planter query
where = await this.planterRepository.applyOrganizationWhereClause(
whereWithoutOrganizationId,
orgId,
'planter',
);
}

Expand Down Expand Up @@ -103,16 +103,16 @@ export class PlanterOrganizationController {
const filterOrgId = organizationId;

if (filterOrgId && filterOrgId !== orgId) {
const entityIds = await this.planterRepository.getEntityIdsByOrganizationId(
orgId,
);
const entityIds =
await this.planterRepository.getEntityIdsByOrganizationId(orgId);
orgId = entityIds.includes(filterOrgId) ? filterOrgId : orgId;
}

// Replace organizationId with full entity tree and planter query
filter.where = await this.planterRepository.applyOrganizationWhereClause(
whereWithoutOrganizationId,
orgId,
'planter',
);
}

Expand Down Expand Up @@ -140,11 +140,16 @@ export class PlanterOrganizationController {
): Promise<PlanterRegistration[]> {
// console.log('/organization/{organizationId}/planter-registration');

const sql = `SELECT * FROM planter_registrations
const sql = `SELECT *, devices.manufacturer FROM planter_registrations
JOIN devices ON devices.android_id=planter_registrations.device_identifier
LEFT JOIN (
SELECT region.name AS country, region.geom FROM region, region_type
WHERE region_type.type='country' AND region.type_id=region_type.id
) AS region ON ST_DWithin(region.geom, planter_registrations.geom, 0.01)`;
SELECT
region.name AS country,
region.geom FROM region, region_type
WHERE region_type.type='country'
AND region.type_id=region_type.id
) AS region
ON ST_DWithin(region.geom, planter_registrations.geom, 0.01)`;

const params = {
filter,
Expand Down
2 changes: 2 additions & 0 deletions src/controllers/trees.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ export class TreesController {
where = await this.treesRepository.applyOrganizationWhereClause(
whereWithoutOrganizationId,
organizationId,
'trees',
);
}

Expand Down Expand Up @@ -90,6 +91,7 @@ export class TreesController {
filter.where = await this.treesRepository.applyOrganizationWhereClause(
whereWithoutOrganizationId,
organizationId,
'trees',
);
}

Expand Down
2 changes: 2 additions & 0 deletions src/controllers/treesOrganization.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ export class TreesOrganizationController {
where = await this.treesRepository.applyOrganizationWhereClause(
whereWithoutOrganizationId,
orgId,
'trees',
);
}

Expand Down Expand Up @@ -100,6 +101,7 @@ export class TreesOrganizationController {
filter.where = await this.treesRepository.applyOrganizationWhereClause(
whereWithoutOrganizationId,
orgId,
'trees',
);
}

Expand Down
14 changes: 14 additions & 0 deletions src/js/buildFilterQuery.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,20 @@ export function buildFilterQuery(selectStmt, params) {

const whereObjClause = connector._buildWhere(modelName, safeWhere);

//add the modelName to each requested field to avoid ambiguity in more complex queries
console.log('whereObjClause.sql -------> ', whereObjClause.sql);

const tableName =
modelName.toLowerCase() === 'planterregistration'
? 'planter_registrations'
: modelName.toLowerCase();
const newQueryFields = whereObjClause.sql
.replace(/"/, `"${tableName}.`)
.replace(/AND "/gi, `AND "${tableName}.`)
.replace(/"/g, '');

whereObjClause.sql = newQueryFields;

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@nmcharlton
I added this regex to add the modelName back onto each field because our more complex cross-table queries were resulting in "ambiguous" field errors that I couldn't find any other way of resolving. Is there a better way to resolve those errors?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wonder whether the LoopBack query builders have a way of including the table name in the query.
This looks ok, but won't catch every WHERE clause construction.

if (whereObjClause.sql) {
const hasWhere = /WHERE(?![^(]*\))/i.test(selectStmt);
query.sql += ` ${hasWhere ? 'AND' : 'WHERE'} ${whereObjClause.sql}`;
Expand Down
120 changes: 120 additions & 0 deletions src/mixins/utils.repository-mixin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { MixinTarget } from '@loopback/core';
import { CrudRepository, Model } from '@loopback/repository';
import expect from 'expect-runtime';

// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
export function UtilsRepositoryMixin<
M extends Model,
R extends MixinTarget<CrudRepository<M>>,
>(superClass: R) {
return class extends superClass {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[x: string]: any;
// put the shared code here
async getEntityIdsByOrganizationId(
organizationId: number,
): Promise<Array<number>> {
expect(organizationId).number();
expect(this).property('execute').defined();
const result = await this.execute(
`select * from getEntityRelationshipChildren(${organizationId})`,
[],
);
return result.map((e) => e.entity_id);
}

async applyOrganizationWhereClause(
where: Object | undefined,
organizationId: number | undefined,
model: string,
): Promise<Object | undefined> {
if (!where || organizationId === undefined) {
return Promise.resolve(where);
}

// if planter or tree repository request
if (model === 'trees' || model === 'planter') {
const organizationWhereClause = await this.getOrganizationWhereClause(
organizationId,
model,
);
return {
and: [where, organizationWhereClause],
};
} else {
const entityIds = await this.getEntityIdsByOrganizationId(
organizationId,
);
return {
and: [where, { id: { inq: entityIds } }],
};
}
}

async getPlanterIdsByOrganizationId(
organizationId: number,
): Promise<Array<number>> {
expect(organizationId).number();
const result = await this.execute(
`select * from planter where organization_id in (select entity_id from getEntityRelationshipChildren(${organizationId}))`,
[],
);
expect(result).match([{ id: expect.any(Number) }]);
return result.map((e) => e.id);
}

async getNonOrganizationPlanterIds(): Promise<Array<number>> {
const result = await this.execute(
`select * from planter where organization_id isnull`,
[],
);
expect(result).match([{ id: expect.any(Number) }]);
return result.map((e) => e.id);
}

async getOrganizationWhereClause(
organizationId: number,
model: string,
): Promise<Object> {
if (organizationId === null) {
const planterIds = await this.getNonOrganizationPlanterIds();
// if planter repository request
if (model === 'planter') {
return { id: { inq: planterIds } };
} else {
// if trees or other repository request
return {
and: [
{ plantingOrganizationId: null },
{ planterId: { inq: planterIds } },
],
};
}
} else {
const planterIds = await this.getPlanterIdsByOrganizationId(
organizationId,
);
const entityIds = await this.getEntityIdsByOrganizationId(
organizationId,
);
// if planter repository request
if (model === 'planter') {
return {
or: [
{ organizationId: { inq: entityIds } },
{ 'planter.id': { inq: planterIds } },
],
};
} else {
// if trees or other repository request
return {
or: [
{ plantingOrganizationId: { inq: entityIds } },
{ planterId: { inq: planterIds } },
],
};
}
}
}
};
}
44 changes: 12 additions & 32 deletions src/repositories/organization.repository.ts
Original file line number Diff line number Diff line change
@@ -1,42 +1,22 @@
import { Constructor, inject } from '@loopback/core';
import { DefaultCrudRepository } from '@loopback/repository';
import { Organization, OrganizationRelations } from '../models';
import { TreetrackerDataSource } from '../datasources';
import { inject } from '@loopback/core';
import expect from 'expect-runtime';
import { UtilsRepositoryMixin } from '../mixins/utils.repository-mixin';
import { Organization, OrganizationRelations } from '../models';

export class OrganizationRepository extends DefaultCrudRepository<
export class OrganizationRepository extends UtilsRepositoryMixin<
Organization,
typeof Organization.prototype.id,
OrganizationRelations
> {
Constructor<
DefaultCrudRepository<
Organization,
typeof Organization.prototype.id,
OrganizationRelations
>
>
>(DefaultCrudRepository) {
constructor(
@inject('datasources.treetracker') dataSource: TreetrackerDataSource,
) {
super(Organization, dataSource);
}

async getEntityIdsByOrganizationId(
organizationId: number,
): Promise<Array<number>> {
expect(organizationId).number();
expect(this).property('execute').defined();
const result = await this.execute(
`select * from getEntityRelationshipChildren(${organizationId})`,
[],
);
return result.map((e) => e.entity_id);
}

async applyOrganizationWhereClause(
where: Object | undefined,
organizationId: number | undefined,
): Promise<Object | undefined> {
if (!where || organizationId === undefined) {
return Promise.resolve(where);
}
const entityIds = await this.getEntityIdsByOrganizationId(organizationId);
return {
and: [where, { id: { inq: entityIds } }],
};
}
}
Loading