-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathfind-users.handler.ts
45 lines (43 loc) · 1.56 KB
/
find-users.handler.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import { userActionCreator } from '@/modules/user';
import { UserModel } from '@/modules/user/database/user.repository';
import { joinConditions } from '@/shared/db/postgres';
import { Paginated, PaginatedQueryParams } from '@/shared/db/repository.port';
import { paginatedQueryBase } from '@/shared/ddd/query.base';
export type FindUsersQueryResult = Promise<Paginated<UserModel>>;
export const findUsersQuery = userActionCreator<
Partial<PaginatedQueryParams> & {
country?: string;
postalCode?: string;
street?: string;
}
>('find-all-paginated');
export default function makeFindUsersQuery({ db, queryBus }: Dependencies) {
return {
async handler({
payload,
}: ReturnType<typeof findUsersQuery>): FindUsersQueryResult {
const query = paginatedQueryBase(payload);
const conditions = [
query.country && `country = ${query.country}`,
query.street && `street = ${query.street}`,
query.postalCode && `postalCode = ${query.postalCode}`,
];
const users: { rows: UserModel[]; count: number }[] = await db`
SELECT
(SELECT COUNT(*) FROM users ${joinConditions(conditions)}) as count,
(SELECT json_agg(t.*) FROM
(SELECT * FROM users ${joinConditions(conditions)} LIMIT ${query.limit} OFFSET ${query.offset})
AS t) AS rows
`;
return {
data: users[0].rows,
count: users[0].count,
limit: query.limit,
page: query.page,
};
},
init() {
queryBus.register(findUsersQuery.type, this.handler);
},
};
}