index.get.ts
2.75 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import is from '@sindresorhus/is'
import { destr } from 'destr'
import { db } from '@/server/fake-db/apps/users/index'
export default defineEventHandler(async event => {
const { q = '', role = null, plan = null, status = null, sortBy, itemsPerPage = 10, page = 1, orderBy } = getQuery(event)
const searchQuery = is.string(q) ? q : undefined
const queryLower = (searchQuery ?? '').toString().toLowerCase()
const parsedSortBy = destr(sortBy)
const sortByLocal = is.string(parsedSortBy) ? parsedSortBy : ''
const parsedOrderBy = destr(orderBy)
const orderByLocal = is.string(parsedOrderBy) ? parsedOrderBy : ''
const parsedItemsPerPage = destr(itemsPerPage)
const parsedPage = destr(page)
const itemsPerPageLocal = is.number(parsedItemsPerPage) ? parsedItemsPerPage : 10
const pageLocal = is.number(parsedPage) ? parsedPage : 1
// filter users
let filteredUsers = db.users.filter(user => ((user.fullName.toLowerCase().includes(queryLower) || user.email.toLowerCase().includes(queryLower)) && user.role === (role || user.role) && user.currentPlan === (plan || user.currentPlan) && user.status === (status || user.status))).reverse()
// sort users
if (sortByLocal) {
if (sortByLocal === 'user') {
filteredUsers = filteredUsers.sort((a, b) => {
if (orderByLocal === 'asc')
return a.fullName.localeCompare(b.fullName)
else
return b.fullName.localeCompare(a.fullName)
})
}
if (sortByLocal === 'email') {
filteredUsers = filteredUsers.sort((a, b) => {
if (orderByLocal === 'asc')
return a.email.localeCompare(b.email)
else
return b.email.localeCompare(a.email)
})
}
if (sortByLocal === 'role') {
filteredUsers = filteredUsers.sort((a, b) => {
if (orderByLocal === 'asc')
return a.role.localeCompare(b.role)
else
return b.role.localeCompare(a.role)
})
}
if (sortByLocal === 'plan') {
filteredUsers = filteredUsers.sort((a, b) => {
if (orderByLocal === 'asc')
return a.currentPlan.localeCompare(b.currentPlan)
else
return b.currentPlan.localeCompare(a.currentPlan)
})
}
if (sortByLocal === 'status') {
filteredUsers = filteredUsers.sort((a, b) => {
if (orderByLocal === 'asc')
return a.status.localeCompare(b.status)
else
return b.status.localeCompare(a.status)
})
}
}
const totalUsers = filteredUsers.length
// total pages
const totalPages = Math.ceil(totalUsers / itemsPerPageLocal)
setResponseStatus(event, 200)
return { users: paginateArray(filteredUsers, itemsPerPageLocal, pageLocal), totalPages, totalUsers, page: pageLocal > Math.ceil(totalUsers / itemsPerPageLocal) ? 1 : page }
})