feat: 用户增加extra字段用于存储额外信息

pull/64/head
moonrailgun 2 years ago
parent 167e7b6b8e
commit b5cc18fbe1

@ -100,6 +100,12 @@ export class User extends TimeStamps implements Base {
})
type: UserType;
/**
*
*/
@prop()
extra?: object;
/**
*
*/

@ -45,10 +45,12 @@ class UserService extends TcService {
'_id',
'username',
'email',
'avatar',
'nickname',
'discriminator',
'temporary',
'avatar',
'type',
'extra',
'createdAt',
]);
@ -157,6 +159,12 @@ class UserService extends TcService {
fieldValue: 'any',
},
});
this.registerAction('updateUserExtra', this.updateUserExtra, {
params: {
fieldName: 'string',
fieldValue: 'any',
},
});
this.registerAction('getUserSettings', this.getUserSettings);
this.registerAction('setUserSettings', this.setUserSettings, {
params: {
@ -546,6 +554,9 @@ class UserService extends TcService {
return list;
}
/**
*
*/
async updateUserField(
ctx: TcContext<{ fieldName: string; fieldValue: string }>
) {
@ -553,7 +564,8 @@ class UserService extends TcService {
const t = ctx.meta.t;
const userId = ctx.meta.userId;
if (!['nickname', 'avatar'].includes(fieldName)) {
throw new EntityError(t('该数据不允许修改'));
// 只允许修改以上字段
throw new EntityError(`${t('该数据不允许修改')}: ${fieldName}`);
}
const doc = await this.adapter.model
@ -575,6 +587,34 @@ class UserService extends TcService {
return await this.transformDocuments(ctx, {}, doc);
}
/**
*
*/
async updateUserExtra(
ctx: TcContext<{ fieldName: string; fieldValue: string }>
) {
const { fieldName, fieldValue } = ctx.params;
const userId = ctx.meta.userId;
const doc = await this.adapter.model
.findOneAndUpdate(
{
_id: new Types.ObjectId(userId),
},
{
[`extra.${fieldName}`]: fieldValue,
},
{
new: true,
}
)
.exec();
this.cleanCurrentUserCache(ctx);
return await this.transformDocuments(ctx, {}, doc);
}
/**
*
*/

@ -103,6 +103,48 @@ describe('Test "user" service', () => {
expect(res).not.toHaveProperty('password');
});
test('Test "user.updateUserExtra"', async () => {
const testUser = await insertTestData(createTestUser());
const res = await broker.call(
'user.updateUserExtra',
{
fieldName: 'foo',
fieldValue: 'bar',
},
{
meta: {
userId: String(testUser._id),
},
}
);
expect(res).toMatchObject({
extra: {
foo: 'bar',
},
});
const res2 = await broker.call(
'user.updateUserExtra',
{
fieldName: 'foo',
fieldValue: 'baz',
},
{
meta: {
userId: String(testUser._id),
},
}
);
expect(res2).toMatchObject({
extra: {
foo: 'baz',
},
});
});
test('Test "user.setUserSettings"', async () => {
const testUser = await insertTestData(createTestUser());

Loading…
Cancel
Save