Skip to content

Commit cf48f65

Browse files
committed
feat: add update user api: PATCH /user/:address
1 parent 7a0b569 commit cf48f65

File tree

3 files changed

+35
-1
lines changed

3 files changed

+35
-1
lines changed

app/controller/user.js

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,17 @@ class UserController extends Controller {
1818
ctx.body = user;
1919
}
2020

21+
async updateUser() {
22+
const ctx = this.ctx;
23+
24+
const address = ctx.params.address;
25+
const updates = ctx.request.body;
26+
// TODO: 检查权限 只有本人 或者 管理员 才有权修改
27+
// ctx.throw(403, '无权限修改用户信息', { code: 'FORBIDDEN_UPDATE_USER', error: { address } });
28+
const user = await ctx.service.user.updateByAddress(address, updates);
29+
ctx.body = user;
30+
}
31+
2132
}
2233

2334
module.exports = UserController;

app/router.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ module.exports = app => {
3535

3636
router.get('/user', isUser, controller.user.current);
3737
router.get('/users/:address', controller.user.getUser);
38+
router.patch('/users/:address', controller.user.updateUser);
3839

3940
router.get('/likes', controller.like.list);
4041
router.post('/likes', isUser, controller.like.create);

app/service/user.js

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ class UserService extends Service {
99
}
1010

1111
async getByAddress(address) {
12-
// TODO: 检查address是否合法
12+
// TODO: address统一变小写,检查address是否合法
1313
// ctx.throw(400, '无效地址', { code: 'INVALID_ADDRESS', error: { address } });
1414

1515
// 从数据库里读取用户信息
@@ -30,6 +30,28 @@ class UserService extends Service {
3030
return { ...userInDB, ...userInChain };
3131
}
3232

33+
async updateByAddress(address, updates) {
34+
const ctx = this.ctx;
35+
// TODO: address统一变小写,检查address是否合法
36+
// ctx.throw(400, '无效地址', { code: 'INVALID_ADDRESS', error: { address } });
37+
38+
let user = await this.ctx.model.User.find({ where: { address } });
39+
if (!user) {
40+
ctx.throw(404, `地址(address: ${address})的用户不存在`, { code: 'USER_NOT_FOUND', errors: { address } })
41+
}
42+
43+
// 检查更新参数是否合法
44+
const illegal = Object.keys(updates).some((key) => {
45+
return !['nickname', 'bio', 'avatar_url'].includes(key);
46+
});
47+
if (illegal) {
48+
ctx.throw(400, `更新用户信息参数错误`, { code: 'ILLEGAL_UPDATE_USER_PRAM', errors: { address, updates } })
49+
}
50+
51+
await user.update(updates);
52+
return this.getByAddress(address);
53+
}
54+
3355
}
3456

3557
module.exports = UserService;

0 commit comments

Comments
 (0)