- Updated pagination-response and read-write-controllers documentation to include `orderBy` and `orderType` parameters for sorting results. - Introduced new `order-clause` module to handle ordering logic, including validation for order types and columns. - Enhanced `PaginationQueryDto` to support ordering fields in API requests. - Updated various repository and service classes to implement ordering in database queries. - Added unit tests for new ordering functionality and ensured existing tests cover the updated behavior. - Refactored related DTOs to include user and code relations for better data representation in responses.
72 lines
2.1 KiB
TypeScript
72 lines
2.1 KiB
TypeScript
import { BadRequestException } from '@nestjs/common';
|
|
import { asc, desc } from 'drizzle-orm';
|
|
import { integer, pgTable } from 'drizzle-orm/pg-core';
|
|
import { toOrderClauses } from './order-clause';
|
|
|
|
const sample = pgTable('sample', {
|
|
code: integer('code'),
|
|
name: integer('name'),
|
|
createdAt: integer('created_at'),
|
|
});
|
|
|
|
const columns = {
|
|
code: sample.code,
|
|
name: sample.name,
|
|
createdAt: sample.createdAt,
|
|
};
|
|
|
|
describe('toOrderClauses', () => {
|
|
it('uses default columns when orderBy is omitted', () => {
|
|
expect(
|
|
toOrderClauses(columns, {}, [{ column: 'code', type: 'ASC' }]),
|
|
).toEqual([asc(sample.code)]);
|
|
});
|
|
|
|
it('applies multiple defaults when orderBy is omitted', () => {
|
|
expect(
|
|
toOrderClauses(columns, {}, [
|
|
{ column: 'createdAt', type: 'ASC' },
|
|
{ column: 'code', type: 'ASC' },
|
|
]),
|
|
).toEqual([asc(sample.createdAt), asc(sample.code)]);
|
|
});
|
|
|
|
it('uses a single client column and DESC', () => {
|
|
expect(
|
|
toOrderClauses(columns, { orderBy: 'name', orderType: 'DESC' }, [
|
|
{ column: 'code', type: 'ASC' },
|
|
]),
|
|
).toEqual([desc(sample.name)]);
|
|
});
|
|
|
|
it('applies orderType to defaults when orderBy is omitted', () => {
|
|
expect(
|
|
toOrderClauses(columns, { orderType: 'DESC' }, [
|
|
{ column: 'code', type: 'ASC' },
|
|
]),
|
|
).toEqual([desc(sample.code)]);
|
|
});
|
|
|
|
it('rejects unknown orderBy without echoing the raw value as SQL', () => {
|
|
expect(() =>
|
|
toOrderClauses(columns, { orderBy: 'drop table' }, [{ column: 'code' }]),
|
|
).toThrow(BadRequestException);
|
|
try {
|
|
toOrderClauses(columns, { orderBy: 'drop table' }, [{ column: 'code' }]);
|
|
} catch (error) {
|
|
expect((error as BadRequestException).message).toContain(
|
|
'code, name, createdAt',
|
|
);
|
|
expect((error as BadRequestException).message).not.toContain(
|
|
'drop table',
|
|
);
|
|
}
|
|
});
|
|
|
|
it('rejects invalid orderType', () => {
|
|
expect(() =>
|
|
toOrderClauses(columns, { orderType: 'SIDEWAYS' }, [{ column: 'code' }]),
|
|
).toThrow(BadRequestException);
|
|
});
|
|
});
|