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: improve the logic for setting options in readMany and search #592

Merged
merged 3 commits into from
Jul 7, 2024
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
4 changes: 0 additions & 4 deletions spec/search/search-cursor-pagination.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ describe('Search Cursor Pagination', () => {
],
order: { col1: 'DESC' },
take: 10,
withDeleted: false,
});

const { body: secondResponse } = await request(app.getHttpServer())
Expand All @@ -109,7 +108,6 @@ describe('Search Cursor Pagination', () => {
expect(nextLastEntity).toEqual({ col1: 'col1_1' });
expect(PaginationHelper.deserialize(nextPreCondition.where as string)).toEqual({
...searchRequestBody,
withDeleted: false,
});
});

Expand Down Expand Up @@ -160,7 +158,6 @@ describe('Search Cursor Pagination', () => {
],
order: { col1: 'DESC' },
take: 10,
withDeleted: false,
});

const { body: secondResponse } = await request(app.getHttpServer())
Expand All @@ -185,7 +182,6 @@ describe('Search Cursor Pagination', () => {
expect(nextLastEntity).toEqual({ col1: 'col1_1' });
expect(PaginationHelper.deserialize(nextPreCondition.where as string)).toEqual({
...searchRequestBody,
withDeleted: false,
});
});

Expand Down
14 changes: 8 additions & 6 deletions src/lib/interceptor/read-many-request.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ export function ReadManyRequestInterceptor(crudOptions: CrudOptions, factoryOpti

const pagination = PaginationHelper.getPaginationRequest(paginationType, req.query);

const withDeleted = _.isBoolean(customReadManyRequestOptions?.softDeleted)
? customReadManyRequestOptions.softDeleted
: crudOptions.routes?.[method]?.softDelete ?? CRUD_POLICY[method].default.softDeleted;

const query = await (async () => {
if (PaginationHelper.isNextPage(pagination)) {
const isQueryValid = pagination.setQuery(pagination.query);
Expand All @@ -55,18 +59,16 @@ export function ReadManyRequestInterceptor(crudOptions: CrudOptions, factoryOpti
const numberOfTake =
(pagination.type === 'cursor' ? readManyOptions.numberOfTake : pagination.limit ?? readManyOptions.numberOfTake) ??
CRUD_POLICY[method].default.numberOfTake;
const sort = readManyOptions.sort ? Sort[readManyOptions.sort] : CRUD_POLICY[method].default.sort;

const crudReadManyRequest: CrudReadManyRequest<typeof crudOptions.entity> = new CrudReadManyRequest<typeof crudOptions.entity>()
.setPaginationKeys(paginationKeys)
.setExcludeColumn(readManyOptions.exclude)
.setPagination(pagination)
.setWithDeleted(
_.isBoolean(customReadManyRequestOptions?.softDeleted)
? customReadManyRequestOptions.softDeleted
: crudOptions.routes?.[method]?.softDelete ?? CRUD_POLICY[method].default.softDeleted,
)
.setWithDeleted(withDeleted)
.setWhere(query)
.setTake(numberOfTake)
.setSort(readManyOptions.sort ? Sort[readManyOptions.sort] : CRUD_POLICY[method].default.sort)
.setSort(sort)
.setRelations(this.getRelations(customReadManyRequestOptions))
.setDeserialize(this.deserialize)
.generate();
Expand Down
10 changes: 1 addition & 9 deletions src/lib/interceptor/search-request.interceptor.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ describe('SearchRequestInterceptor', () => {
it('return search request dto when input is valid', async () => {
expect(await interceptor.validateBody({ select: ['col1', 'col2'] })).toEqual({
select: ['col1', 'col2'],
withDeleted: false,
});
});

Expand Down Expand Up @@ -95,7 +94,6 @@ describe('SearchRequestInterceptor', () => {
}),
).toEqual({
where: [{ col3: { operator: 'BETWEEN', operand: [0, 5] } }],
withDeleted: false,
});
});

Expand All @@ -106,7 +104,6 @@ describe('SearchRequestInterceptor', () => {
}),
).toEqual({
where: [{ col4: { operator: 'BETWEEN', operand: ['2000-01-01', '2000-02-01'] } }],
withDeleted: false,
});
});
});
Expand All @@ -117,14 +114,12 @@ describe('SearchRequestInterceptor', () => {
}),
).toEqual({
where: [{ col3: { operator: 'IN', operand: [0, 1, 2] } }],
withDeleted: false,
});
});

it('NULL', async () => {
expect(await interceptor.validateBody({ where: [{ col3: { operator: 'NULL' } }] })).toEqual({
where: [{ col3: { operator: 'NULL' } }],
withDeleted: false,
});
});

Expand All @@ -135,7 +130,6 @@ describe('SearchRequestInterceptor', () => {
}),
).toEqual({
where: [{ col2: { operator: '=', operand: 7 }, col3: { operator: '>', operand: 3 } }],
withDeleted: false,
});
});

Expand All @@ -146,7 +140,6 @@ describe('SearchRequestInterceptor', () => {
}),
).toEqual({
where: [{ col2: { not: false, operand: 7, operator: '=' }, col3: { not: true, operand: 3, operator: '>' } }],
withDeleted: false,
});
});
});
Expand Down Expand Up @@ -254,7 +247,6 @@ describe('SearchRequestInterceptor', () => {
it('return search request dto when input is valid', async () => {
expect(await interceptor.validateBody({ order: { col2: Sort.ASC, col3: Sort.DESC } })).toEqual({
order: { col2: Sort.ASC, col3: Sort.DESC },
withDeleted: false,
});
});

Expand Down Expand Up @@ -298,7 +290,7 @@ describe('SearchRequestInterceptor', () => {
describe('body.take', () => {
describe('return search request dto when input is valid', () => {
test.each([1, 20, 100_000])('take(%p)', async (take) => {
expect(await interceptor.validateBody({ take })).toEqual({ take, withDeleted: false });
expect(await interceptor.validateBody({ take })).toEqual({ take });
});
});

Expand Down
21 changes: 11 additions & 10 deletions src/lib/interceptor/search-request.interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import type { OperatorUnion } from '../interface/query-operation.interface';
import type { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common';
import type { Request } from 'express';
import type { Observable } from 'rxjs';
import type { FindOptionsOrder, FindOptionsWhere, FindOperator } from 'typeorm';
import type { FindOptionsWhere, FindOperator } from 'typeorm';

const method = Method.SEARCH;
// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
Expand Down Expand Up @@ -82,7 +82,11 @@ export function SearchRequestInterceptor(crudOptions: CrudOptions, factoryOption
(pagination.type === 'cursor' ? requestSearchDto.take : pagination.limit) ??
searchOptions.numberOfTake ??
CRUD_POLICY[method].default.numberOfTake;
requestSearchDto.order ??= paginationKeys.reduce((acc, key) => ({ ...acc, [key]: CRUD_POLICY[method].default.sort }), {});
const order =
requestSearchDto.order ?? paginationKeys.reduce((acc, key) => ({ ...acc, [key]: CRUD_POLICY[method].default.sort }), {});

const withDeleted =
requestSearchDto.withDeleted ?? crudOptions.routes?.[method]?.softDelete ?? CRUD_POLICY[method].default.softDeleted;

const crudReadManyRequest: CrudReadManyRequest<typeof crudOptions.entity> = new CrudReadManyRequest<typeof crudOptions.entity>()
.setPaginationKeys(paginationKeys)
Expand All @@ -91,10 +95,8 @@ export function SearchRequestInterceptor(crudOptions: CrudOptions, factoryOption
.setExcludeColumn(searchOptions.exclude)
.setWhere(where)
.setTake(numberOfTake)
.setOrder(requestSearchDto.order as FindOptionsOrder<typeof crudOptions.entity>, CRUD_POLICY[method].default.sort)
.setWithDeleted(
requestSearchDto.withDeleted ?? crudOptions.routes?.[method]?.softDelete ?? CRUD_POLICY[method].default.softDeleted,
)
.setOrder(order)
.setWithDeleted(withDeleted)
.setRelations(this.getRelations(customSearchRequestOptions))
.setDeserialize(this.deserialize)
.generate();
Expand Down Expand Up @@ -128,8 +130,6 @@ export function SearchRequestInterceptor(crudOptions: CrudOptions, factoryOption

if ('withDeleted' in requestSearchDto) {
this.validateWithDeleted(requestSearchDto.withDeleted);
} else {
requestSearchDto.withDeleted = searchOptions.softDelete ?? CRUD_POLICY[method].default.softDeleted;
}

if ('take' in requestSearchDto) {
Expand Down Expand Up @@ -289,14 +289,15 @@ export function SearchRequestInterceptor(crudOptions: CrudOptions, factoryOption
return factoryOption.relations;
}

deserialize<T>({ pagination, findOptions, sort }: CrudReadManyRequest<T>): Array<FindOptionsWhere<T>> {
deserialize<T>({ pagination, findOptions }: CrudReadManyRequest<T>): Array<FindOptionsWhere<T>> {
const where = findOptions.where as Array<FindOptionsWhere<EntityType>>;
if (pagination.type === PaginationType.OFFSET) {
return where;
}
const lastObject: Record<string, unknown> = PaginationHelper.deserialize(pagination.nextCursor);

const operator = (key: keyof T) => ((findOptions.order?.[key] ?? sort) === Sort.DESC ? LessThan : MoreThan);
const operator = (key: keyof T) =>
(findOptions.order?.[key] ?? CRUD_POLICY[method].default.sort) === Sort.DESC ? LessThan : MoreThan;

const cursorCondition: Record<string, FindOperator<T>> = Object.entries(lastObject).reduce(
(queryFilter, [key, operand]) => ({
Expand Down
3 changes: 1 addition & 2 deletions src/lib/request/read-many.request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,8 +109,7 @@ export class CrudReadManyRequest<T> {
return this;
}

setOrder(order: FindOptionsOrder<T>, sort: Sort): this {
this._sort = sort;
setOrder(order: FindOptionsOrder<T>): this {
this._findOptions.order = order;
return this;
}
Expand Down
Loading