Skip to content

Commit

Permalink
fix: update user and update avatar at the same time
Browse files Browse the repository at this point in the history
  • Loading branch information
SolidZORO committed Jun 5, 2020
1 parent 7a810fe commit 298ccfa
Show file tree
Hide file tree
Showing 15 changed files with 123 additions and 169 deletions.
4 changes: 3 additions & 1 deletion packages/_leaa-common/src/dtos/user/user.create-one.req.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ export class UserCreateOneReq {
@Length(6, 64)
password!: string;

@IsOptional()
avatar_url?: string | null;

status?: number;
is_admin?: number;
avatar_url?: string;
}
4 changes: 3 additions & 1 deletion packages/_leaa-common/src/entrys/user.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ export class User extends Base {

@BeforeInsert()
BeforeInsert?() {
this.avatar_url = genAvatarUrl(this.email || this.phone || this.id || '');
if (!this.avatar_url) {
this.avatar_url = genAvatarUrl(this.email || this.phone || this.id || '');
}
}
}
15 changes: 10 additions & 5 deletions packages/leaa-api/src/filters/http-exception.filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,11 +28,16 @@ export class HttpExceptionFilter implements ExceptionFilter {

logger.error(`${exception}` || 'HttpExceptionFilter ErrorMsg');

// @ts-ignore
console.error('\n\n---- EXCEPTION-SQL-MESSAGE ----\n', exception.sqlMessage);

// @ts-ignore
console.error('\n\n---- EXCEPTION-RESPONSE ----\n', exception.response);
console.error(
'\n---- EXCEPTION ----\n',
'\nSQL:\n',
// @ts-ignore
exception.sqlMessage,
'\n\nRES:\n',
// @ts-ignore
exception.response,
'\n\n\n\n',
);

res.status(statusCode).json({
statusCode,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ import { PermissionService } from './permission.service';
query: {
maxLimit: 1000,
alwaysPaginate: true,
sort: [
{ field: 'created_at', order: 'DESC' },
{ field: 'slug', order: 'ASC' },
],
},
routes: {
exclude: ['createManyBase'],
Expand Down
104 changes: 0 additions & 104 deletions packages/leaa-api/src/modules/v1/permission/permission.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,107 +33,3 @@ export class PermissionService extends TypeOrmCrudService<Permission> {
return permissionIds;
}
}

// import { Injectable } from '@nestjs/common';
// import { Repository, In, SelectQueryBuilder } from 'typeorm';
// import { InjectRepository } from '@nestjs/typeorm';
//
// import { Permission } from '@leaa/common/src/entrys';
// import {
// PermissionsWithPaginationObject,
// PermissionCreateOneReq,
// PermissionUpdateOneReq,
// } from '@leaa/common/src/dtos/permission';
// import { argsFormat, commonUpdate, commonDelete, isOneField, calcQbPageInfo, errorMsg } from '@leaa/api/src/utils';
// import { IPermissionsArgs, IPermissionArgs, IGqlCtx } from '@leaa/api/src/interfaces';
// import { ConfigService } from '@leaa/api/src/modules/config/config.service';
// import { permissionsSeed } from '@leaa/api/src/modules/seed/seed.data';
//
// const CLS_NAME = 'PermissionService';
//
// @Injectable()
// export class PermissionService {
// constructor(
// @InjectRepository(Permission) private readonly permissionRepository: Repository<Permission>,
// private readonly configService: ConfigService,
// ) {}
//
// async PLEASE_DONT_MODIFY_DEMO_DATA(id?: string): Promise<boolean> {
// // // const { t } = gqlCtx;
//
// if (this.configService.DEMO_MODE && !process.argv.includes('--nuke')) {
// if (!id) return true;
//
// const p = await this.permission(id);
//
// if (p && p.slug && permissionsSeed.map((seed) => seed.slug).includes(p.slug as any)) {
// throw errorMsg('_error:pleaseDontModify');
// }
// }
//
// return true;
// }
//
// async permissions(args: IPermissionsArgs): Promise<PermissionsWithPaginationObject> {
// const nextArgs: IPermissionsArgs = argsFormat(args);
//
// const qb = this.permissionRepository.createQueryBuilder();
// qb.select().orderBy(nextArgs.orderBy || 'created_at', nextArgs.orderSort);
//
// // q
// if (nextArgs.q) {
// const aliasName = new SelectQueryBuilder(qb).alias;
//
// ['name', 'slug'].forEach((key) => {
// qb.orWhere(`${aliasName}.${key} LIKE :${key}`, { [key]: `%${nextArgs.q}%` });
// });
// }
//
// const pageInfo = await calcQbPageInfo({
// qb,
// page: nextArgs.page,
// pageSize: nextArgs.pageSize,
// });
//
// return {
// ...pageInfo,
// items: pageInfo.items.map((i) => ({
// ...i,
// slugGroup: i.slug.split('.')[0],
// })),
// };
// }
//
// async permission(id: string, args?: IPermissionArgs): Promise<Permission | undefined> {
// // const { t } = gqlCtx;
//
// if (!id) throw errorMsg('_error:notFoundId');
//
// let nextArgs: IPermissionArgs = {};
// if (args) nextArgs = args;
//
// return this.permissionRepository.findOne(id, nextArgs);
// }
//

//
// async createPermission(args: PermissionCreateOneReq): Promise<Permission | undefined> {
// return this.permissionRepository.save({ ...args });
// }
//
// async updatePermission(id: string, args: PermissionUpdateOneReq): Promise<Permission | undefined> {
// if (this.configService.DEMO_MODE) await this.PLEASE_DONT_MODIFY_DEMO_DATA(id);
//
// if (isOneField(args, 'status')) {
// return commonUpdate({ repository: this.permissionRepository, CLS_NAME, id, args });
// }
//
// return commonUpdate({ repository: this.permissionRepository, CLS_NAME, id, args });
// }
//
// async deletePermission(id: string): Promise<Permission | undefined> {
// if (this.configService.DEMO_MODE) await this.PLEASE_DONT_MODIFY_DEMO_DATA(id);
//
// return commonDelete({ repository: this.permissionRepository, CLS_NAME, id });
// }
// }
4 changes: 4 additions & 0 deletions packages/leaa-api/src/modules/v1/role/role.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,10 @@ import { RoleService } from './role.service';
join: {
permissions: { eager: true },
},
sort: [
{ field: 'created_at', order: 'DESC' },
{ field: 'slug', order: 'ASC' },
],
},
routes: {
exclude: ['createManyBase'],
Expand Down
4 changes: 2 additions & 2 deletions packages/leaa-api/src/modules/v1/user/user.module.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';

import { User, Role, Permission, Auth, Verification } from '@leaa/common/src/entrys';
import { User, Role, Permission, Auth, Verification, Attachment } from '@leaa/common/src/entrys';

import { UserService } from '@leaa/api/src/modules/v1/user/user.service';
import { RoleModule } from '@leaa/api/src/modules/v1/role/role.module';
Expand All @@ -12,7 +12,7 @@ import { UserController } from '@leaa/api/src/modules/v1/user/user.controller';

@Module({
imports: [
TypeOrmModule.forFeature([User, Role, Permission, Auth, Verification]),
TypeOrmModule.forFeature([User, Role, Permission, Auth, Verification, Attachment]),
RoleModule,
AuthTokenModule,
AttachmentModule,
Expand Down
13 changes: 11 additions & 2 deletions packages/leaa-api/src/modules/v1/user/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { CrudRequest } from '@nestjsx/crud';
import { Injectable, ForbiddenException, BadRequestException } from '@nestjs/common';

import { logger } from '@leaa/api/src/utils';
import { User, Role, Auth } from '@leaa/common/src/entrys';
import { User, Role, Auth, Attachment } from '@leaa/common/src/entrys';
import { UserUpdateOneReq, UserCreateOneReq } from '@leaa/common/src/dtos/user';
import validator from 'validator';

Expand All @@ -20,6 +20,7 @@ export class UserService extends TypeOrmCrudService<User> {
@InjectRepository(User) private readonly userRepo: Repository<User>,
@InjectRepository(Role) private readonly roleRepo: Repository<Role>,
@InjectRepository(Auth) private readonly authRepo: Repository<Auth>,
@InjectRepository(Attachment) private readonly attachmentRepo: Repository<Attachment>,
) {
super(userRepo);
}
Expand Down Expand Up @@ -47,7 +48,10 @@ export class UserService extends TypeOrmCrudService<User> {
const hasSuperuser = await this.userRepo.findOne({ is_superuser: 1 });
if (hasSuperuser) delete nextDto.is_superuser;

return super.createOne(req, nextDto);
const result = await super.createOne(req, nextDto);
if (nextDto.avatar_url) await this.updateAvatarModuleIdByPath(nextDto.avatar_url, result.id);

return result;
}

// @ts-ignore
Expand Down Expand Up @@ -98,6 +102,11 @@ export class UserService extends TypeOrmCrudService<User> {
//
//

async updateAvatarModuleIdByPath(path: string, module_id: string): Promise<void> {
const atta = await this.attachmentRepo.findOne({ path });
if (atta) await this.attachmentRepo.update(atta.id, { module_id });
}

async createPassword(password: string): Promise<string> {
const salt = bcryptjs.genSaltSync();
return bcryptjs.hashSync(password, salt);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ interface IProps {
circle?: boolean;
ignoreMsg?: boolean;
onChangeAttasCallback?: (attachment: Attachment[]) => void;
onDeleteAttaCallback?: () => void;
autoUpdateRelation?: IAutoUpdateRelation;
}

Expand Down Expand Up @@ -111,6 +112,7 @@ export const AttachmentBox = (props: IProps) => {
.then(() => {
// 这里貌似没必要去拿 res 的 data 然后再设定
if (props.onChangeAttasCallback) props.onChangeAttasCallback(attas);
if (props.onDeleteAttaCallback) props.onDeleteAttaCallback();
})
.catch((err: IHttpError) => errorMsg(err.response?.data?.message || err.message));
};
Expand Down
39 changes: 27 additions & 12 deletions packages/leaa-dashboard/src/components/TableCard/TableCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,8 @@ export const TableCard = <T extends any>(props: IProps<T>) => {
id: () => ({
title: 'ID',
dataIndex: 'id',
columnWidth: 80, // ID
textWrap: 'word-break',
width: 60, // ID
sorter: true,
sortOrder: calcTableSortOrder('id', crudQuery.sort),
render: (id: string) => <TableColumnId id={id} link={`${props.route?.path}/${id}`} />,
Expand Down Expand Up @@ -91,17 +92,30 @@ export const TableCard = <T extends any>(props: IProps<T>) => {
phone: () => ({
title: t('_lang:phone'),
dataIndex: 'phone',
columnWidth: 70,
width: 140,
ellipsis: true,
textWrap: 'word-break',
sorter: true,
sortOrder: calcTableSortOrder('phone', crudQuery.sort),
render: (text: string, record: any) => <Link to={`${props.route.path}/${record.id}`}>{record.phone}</Link>,
render: (text: string, record: any) => (
<code>
{record.phone ? <Link to={`${props.route.path}/${record.id}`}>{record.phone}</Link> : <span>-</span>}
</code>
),
}),
email: () => ({
title: t('_lang:email'),
dataIndex: 'email',
sorter: true,
width: 180,
ellipsis: true,
textWrap: 'word-break',
sortOrder: calcTableSortOrder('email', crudQuery.sort),
render: (text: string, record: any) => <Link to={`${props.route.path}/${record.id}`}>{record.email}</Link>,
render: (text: string, record: any) => (
<span>
{record.email ? <Link to={`${props.route.path}/${record.id}`}>{record.email}</Link> : <span>-</span>}
</span>
),
}),
roleList: () => ({
title: t('_lang:role'),
Expand All @@ -114,12 +128,12 @@ export const TableCard = <T extends any>(props: IProps<T>) => {
avatar: () => ({
title: t('_lang:avatar'),
dataIndex: 'avatar_url',
columnWidth: 60,
width: 60,
render: (avatar: string) => <UserAvatar url={avatar} />,
}),
isAdmin: () => ({
title: <Rcon type="ri-vip-crown-2-line" />,
columnWidth: 30,
width: 30,
dataIndex: 'is_admin',
sorter: true,
sortOrder: calcTableSortOrder('name', crudQuery.sort),
Expand All @@ -128,36 +142,37 @@ export const TableCard = <T extends any>(props: IProps<T>) => {
category: () => ({
title: t('_lang:category'),
dataIndex: 'category',
columnWidth: 100,
width: 110,
render: (text: string, record: any) => (
<span>{record.categories && record.categories.length > 0 ? record.categories[0].name : '----'}</span>
),
}),
views: () => ({
title: t('_lang:views'),
dataIndex: 'views',
columnWidth: 100,
width: 100,
render: (text: string, record: any) => <small className="g-col-number">{record.views}</small>,
}),
createdAt: () => ({
title: t('_lang:createdAt'),
dataIndex: 'created_at',
sorter: true,
width: 110,
sortOrder: calcTableSortOrder('created_at', crudQuery?.sort),
render: (text: string) => <TableColumnDate date={text} size="small" />,
}),
status: () => ({
title: t('_lang:status'),
dataIndex: 'status',
columnWidth: 60,
width: 60,
render: (text: string, record: any) => (
<TableColumnStatusSwitch id={record.id} value={record.status} apiPath={props.routerName} size="small" />
),
}),
action: (options?: { fieldName?: string }) => ({
title: t('_lang:action'),
dataIndex: 'operation',
columnWidth: 60,
width: 60,
render: (text: string, record: any) => (
<TableColumnDeleteButton
id={record.id}
Expand All @@ -170,7 +185,7 @@ export const TableCard = <T extends any>(props: IProps<T>) => {
byte: (options?: { fieldName?: string }) => ({
title: t('_lang:size'),
dataIndex: 'size',
columnWidth: 75,
width: 75,
sorter: true,
sortOrder: calcTableSortOrder('size', crudQuery?.sort),
render: (text: string, record: any) =>
Expand Down Expand Up @@ -211,7 +226,7 @@ export const TableCard = <T extends any>(props: IProps<T>) => {
};

const rowSelection = {
columnWidth: 30,
width: 30,
onChange: (keys: IKey[]) => setSelectedRowKeys(keys),
selectedRowKeys,
};
Expand Down
4 changes: 1 addition & 3 deletions packages/leaa-dashboard/src/pages/User/UserEdit/UserEdit.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import { PageCard, HtmlMeta, Rcon, SubmitBar } from '@leaa/dashboard/src/compone

import { UserInfoForm } from '../_components/UserInfoForm/UserInfoForm';
import { UserRolesForm } from '../_components/UserRolesForm/UserRolesForm';
import { UploadUserAvatar } from '../_components/UploadUserAvatar/UploadUserAvatar';

import style from './style.module.less';

const API_PATH = 'users';
Expand Down Expand Up @@ -105,8 +105,6 @@ export default (props: IPage) => {

<UserInfoForm item={item} loading={itemLoading} ref={infoFormRef} />

<UploadUserAvatar item={item} loading={itemLoading} />

<UserRolesForm ref={rolesFormRef} item={item} loading={rolesLoading} roles={roles || []} />

<SubmitBar full>
Expand Down

0 comments on commit 298ccfa

Please sign in to comment.