generated from idea2app/NodeTS-LeanCloud
-
Notifications
You must be signed in to change notification settings - Fork 12
/
User.ts
88 lines (69 loc) · 2.32 KB
/
User.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
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
import {
JsonController,
Get,
Authorized,
Ctx,
QueryParam,
ForbiddenError,
Param,
Post,
OnUndefined,
Delete
} from 'routing-controllers';
import { User, Query, Object as LCObject, Role } from 'leanengine';
import { LCContext } from '../utility';
import { RoleController } from './Role';
@JsonController('/user')
export class UserController {
static async getUserWithRoles(user: User | string) {
if (typeof user === 'string') user = await new Query(User).get(user);
const roles = (await user.getRoles()).map(role => role.getName());
return { ...user.toJSON(), roles };
}
@Get()
@Authorized()
async getList(
@Ctx() { currentUser }: LCContext,
@QueryParam('phone') phone: string,
@QueryParam('pageSize') size = 10,
@QueryParam('pageIndex') index = 1
) {
if (!(await RoleController.isAdmin(currentUser)))
throw new ForbiddenError();
const query = new Query(User);
if (phone) query.equalTo('mobilePhoneNumber', phone);
const count = await query.count({ useMasterKey: true });
query.skip(size * --index).limit(size);
const list = await query.find({ useMasterKey: true }),
data = [];
for (const user of list)
data.push(await UserController.getUserWithRoles(user));
return { data, count };
}
@Get('/:id')
getOne(@Param('id') id: string) {
return UserController.getUserWithRoles(id);
}
@Post('/:id/role/:rid')
@OnUndefined(201)
async addRole(
@Ctx() { currentUser }: LCContext,
@Param('id') id: string,
@Param('rid') rid: string
) {
const role = await new Query(Role).get(rid);
role.getUsers().add(LCObject.createWithoutData('_User', id));
await role.save(null, { user: currentUser });
}
@Delete('/:id/role/:rid')
@OnUndefined(204)
async removeRole(
@Ctx() { currentUser }: LCContext,
@Param('id') id: string,
@Param('rid') rid: string
) {
const role = await new Query(Role).get(rid);
role.getUsers().remove(LCObject.createWithoutData('_User', id));
await role.save(null, { user: currentUser });
}
}