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

fix(typeorm): added alias to joinOption #287

Merged
merged 1 commit into from Oct 3, 2019
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 4 additions & 0 deletions integration/crud-typeorm/users/users.controller.ts
Expand Up @@ -31,6 +31,10 @@ import { UsersService } from './users.service';
company: {
exclude: ['description'],
},
'company.projects': {
alias: 'pr',
exclude: ['description'],
},
profile: {
eager: true,
exclude: ['updatedAt'],
Expand Down
44 changes: 4 additions & 40 deletions packages/crud-typeorm/src/typeorm-crud.service.ts
Expand Up @@ -466,41 +466,6 @@ export class TypeOrmCrudService<T> extends CrudService<T> {
return dto instanceof this.entityType ? dto : plainToClass(this.entityType, dto);
}

private hasColumn(column: string): boolean {
return this.entityColumnsHash[column];
}

private hasRelation(column: string): boolean {
return this.entityRelationsHash[column];
}

private validateHasColumn(column: string) {
if (column.indexOf('.') !== -1) {
const nests = column.split('.');
let relation;
column = nests[nests.length - 1];
relation = nests.slice(0, nests.length - 1).join('.');

if (!this.hasRelation(relation)) {
this.throwBadRequestException(`Invalid relation name '${relation}'`);
}

const noColumn = !(this.entityRelationsHash[relation].columns as string[]).find(
(o) => o === column,
);

if (noColumn) {
this.throwBadRequestException(
`Invalid column name '${column}' for relation '${relation}'`,
);
}
} else {
if (!this.hasColumn(column)) {
this.throwBadRequestException(`Invalid column name '${column}'`);
}
}
}

private getAllowedColumns(columns: string[], options: QueryOptions): string[] {
return (!options.exclude || !options.exclude.length) &&
(!options.allow || /* istanbul ignore next */ !options.allow.length)
Expand Down Expand Up @@ -575,6 +540,8 @@ export class TypeOrmCrudService<T> extends CrudService<T> {
return true;
}

const alias = options.alias ? options.alias : relation.name;

const columns =
!cond.select || !cond.select.length
? allowed
Expand All @@ -584,26 +551,24 @@ export class TypeOrmCrudService<T> extends CrudService<T> {
relation.referencedColumn,
...(options.persist && options.persist.length ? options.persist : []),
...columns,
].map((col) => `${relation.name}.${col}`);
].map((col) => `${alias}.${col}`);

const relationPath = relation.nestedRelation || `${this.alias}.${relation.name}`;
const relationType = options.required ? 'innerJoin' : 'leftJoin';

builder[relationType](relationPath, relation.name);
builder[relationType](relationPath, alias);
builder.addSelect(select);
}

return true;
}

private setAndWhere(cond: QueryFilter, i: any, builder: SelectQueryBuilder<T>) {
this.validateHasColumn(cond.field);
const { str, params } = this.mapOperatorsToQuery(cond, `andWhere${i}`);
builder.andWhere(str, params);
}

private setOrWhere(cond: QueryFilter, i: any, builder: SelectQueryBuilder<T>) {
this.validateHasColumn(cond.field);
const { str, params } = this.mapOperatorsToQuery(cond, `orWhere${i}`);
builder.orWhere(str, params);
}
Expand Down Expand Up @@ -886,7 +851,6 @@ export class TypeOrmCrudService<T> extends CrudService<T> {
const params: ObjectLiteral = {};

for (let i = 0; i < sort.length; i++) {
this.validateHasColumn(sort[i].field);
params[this.getFieldWithAlias(sort[i].field)] = sort[i].order;
}

Expand Down
3 changes: 1 addition & 2 deletions packages/crud-typeorm/test/a.params-options.spec.ts
Expand Up @@ -82,8 +82,7 @@ describe('#crud-typeorm', () => {
TypeOrmModule.forFeature([Company, Project, User, UserProfile]),
],
controllers: [UsersController1, UsersController2],
// providers: [{ provide: APP_FILTER, useClass: HttpExceptionFilter }, UsersService],
providers: [UsersService],
providers: [{ provide: APP_FILTER, useClass: HttpExceptionFilter }, UsersService],
}).compile();

app = fixture.createNestApplication();
Expand Down
42 changes: 37 additions & 5 deletions packages/crud-typeorm/test/b.query-params.spec.ts
Expand Up @@ -106,6 +106,22 @@ describe('#crud-typeorm', () => {
constructor(public service: UsersService) {}
}

@Crud({
model: { type: User },
query: {
join: {
company: {},
'company.projects': {
alias: 'pr',
},
},
},
})
@Controller('users2')
class UsersController2 {
constructor(public service: UsersService) {}
}

beforeAll(async () => {
const fixture = await Test.createTestingModule({
imports: [
Expand All @@ -119,6 +135,7 @@ describe('#crud-typeorm', () => {
ProjectsController3,
ProjectsController4,
UsersController,
UsersController2,
],
providers: [
{ provide: APP_FILTER, useClass: HttpExceptionFilter },
Expand Down Expand Up @@ -149,7 +166,7 @@ describe('#crud-typeorm', () => {
.get('/companies')
.query(query)
.end((_, res) => {
expect(res.status).toBe(400);
expect(res.status).toBe(500);
done();
});
});
Expand Down Expand Up @@ -319,7 +336,7 @@ describe('#crud-typeorm', () => {
.get('/users/1')
.query(query)
.end((_, res) => {
expect(res.status).toBe(400);
expect(res.status).toBe(500);
done();
});
});
Expand All @@ -337,7 +354,7 @@ describe('#crud-typeorm', () => {
.get('/users/1')
.query(query)
.end((_, res) => {
expect(res.status).toBe(400);
expect(res.status).toBe(500);
done();
});
});
Expand All @@ -355,7 +372,7 @@ describe('#crud-typeorm', () => {
.get('/users/1')
.query(query)
.end((_, res) => {
expect(res.status).toBe(400);
expect(res.status).toBe(500);
done();
});
});
Expand Down Expand Up @@ -388,7 +405,6 @@ describe('#crud-typeorm', () => {
done();
});
});

it('should return joined entity, 2', (done) => {
const query = qb
.setFilter({ field: 'company.projects.id', operator: 'notnull' })
Expand All @@ -405,6 +421,22 @@ describe('#crud-typeorm', () => {
done();
});
});
it('should return joined entity with alias', (done) => {
const query = qb
.setFilter({ field: 'pr.id', operator: 'notnull' })
.setJoin({ field: 'company' })
.setJoin({ field: 'company.projects' })
.query();
return request(server)
.get('/users2/1')
.query(query)
.end((_, res) => {
expect(res.status).toBe(200);
expect(res.body.company).toBeDefined();
expect(res.body.company.projects).toBeDefined();
done();
});
});
});

describe('#sort', () => {
Expand Down
1 change: 1 addition & 0 deletions packages/crud/src/interfaces/query-options.interface.ts
Expand Up @@ -27,4 +27,5 @@ export interface JoinOption {
persist?: QueryFields;
eager?: boolean;
required?: boolean;
alias?: string;
}