forked from FreeCodeCamp-Chengdu/HOP-service
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPlatformAdmin.ts
More file actions
108 lines (87 loc) · 2.68 KB
/
PlatformAdmin.ts
File metadata and controls
108 lines (87 loc) · 2.68 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
import {
Authorized,
Body,
CurrentUser,
Delete,
Get,
HttpCode,
JsonController,
NotFoundError,
OnUndefined,
Param,
Put,
QueryParams
} from 'routing-controllers';
import { ResponseSchema } from 'routing-controllers-openapi';
import {
BaseFilter,
PlatformAdmin,
PlatformAdminListChunk,
Role,
User,
dataSource
} from '../model';
import { searchConditionOf } from '../utility';
import { ActivityLogController } from './ActivityLog';
const store = dataSource.getRepository(PlatformAdmin),
userStore = dataSource.getRepository(User);
@JsonController('/platform/admin')
export class PlatformAdminController {
static async isAdmin(uid: number) {
const admin = await store.findOneBy({ user: { id: uid } });
return !!admin;
}
@Put('/:uid')
@Authorized(Role.Administrator)
@HttpCode(201)
@ResponseSchema(PlatformAdmin)
async createOne(
@CurrentUser() createdBy: User,
@Param('uid') uid: number,
@Body() { description }: PlatformAdmin
) {
const user = await userStore.findOneBy({ id: uid });
if (!user) throw new NotFoundError();
const admin = await store.findOneBy({ user: { id: uid } });
if (admin) return admin;
user.roles.push(Role.Administrator);
await userStore.save(user);
const saved = await store.save({ user, description, createdBy });
await ActivityLogController.logCreate(
createdBy,
'PlatformAdmin',
saved.id
);
return saved;
}
@Delete('/:uid')
@Authorized(Role.Administrator)
@OnUndefined(204)
async deleteOne(@CurrentUser() deletedBy: User, @Param('uid') uid: number) {
const user = await userStore.findOneBy({ id: uid });
if (!user) throw new NotFoundError();
const admin = await store.findOneBy({ user: { id: uid } });
if (!admin) return;
user.roles = user.roles.filter(role => role !== Role.Administrator);
await userStore.save(user);
await store.update(admin.id, { deletedBy });
await ActivityLogController.logDelete(
deletedBy,
'PlatformAdmin',
admin.id
);
}
@Get()
@ResponseSchema(PlatformAdminListChunk)
async getList(
@QueryParams() { keywords, pageSize, pageIndex }: BaseFilter
) {
const [list, count] = await store.findAndCount({
where: searchConditionOf<PlatformAdmin>(['description'], keywords),
relations: ['user', 'createdBy'],
skip: pageSize * (pageIndex - 1),
take: pageSize
});
return { list, count };
}
}