xiongzhu 2 ani în urmă
părinte
comite
7c48956f1c

+ 1 - 0
package.json

@@ -38,6 +38,7 @@
     "bcrypt": "^5.1.0",
     "class-transformer": "^0.5.1",
     "class-validator": "^0.13.0",
+    "date-fns": "^2.29.3",
     "express-basic-auth": "^1.2.1",
     "express-handlebars": "^7.0.6",
     "handlebars": "^4.7.7",

+ 12 - 9
src/aliyun/aliyun.service.ts

@@ -9,6 +9,7 @@ import { SendSmsResponse } from '@alicloud/dysmsapi20170525'
 import * as randomstring from 'randomstring'
 import * as OSS from 'ali-oss'
 import { buffer } from 'stream/consumers'
+import * as fs from 'fs'
 
 @Injectable()
 export class AliyunService {
@@ -48,7 +49,7 @@ export class AliyunService {
         }
     }
 
-    public async uploadFile(fileName: string, fileBuffer: Buffer) {
+    public async uploadFile(path: string, data: Buffer) {
         let client = new OSS({
             endpoint: this.aliyunConfiguration.ossEndPoint,
             accessKeyId: this.aliyunConfiguration.accessKeyId,
@@ -56,13 +57,15 @@ export class AliyunService {
             bucket: this.aliyunConfiguration.ossBucket
         })
         try {
-            const result = await client.put(buffer, 'files/111.png')
-            // 自定义headers
-            //,{headers}
-           
-            console.log(result);
-          } catch (e) {
-            console.log(e);
-          }
+            const result = await client.put(path, data)
+            if (result.res.status === 200) {
+                return { url: result.url }
+            } else {
+                throw new InternalServerErrorException(result.res.statusMessage)
+            }
+        } catch (e) {
+            Logger.error(e)
+            throw new InternalServerErrorException(e.message)
+        }
     }
 }

+ 19 - 1
src/file/file.service.ts

@@ -1,5 +1,7 @@
 import { Injectable, Logger } from '@nestjs/common'
 import { AliyunService } from 'src/aliyun/aliyun.service'
+import * as randomstring from 'randomstring'
+import { format } from 'date-fns'
 
 @Injectable()
 export class FileService {
@@ -7,8 +9,24 @@ export class FileService {
 
     public async upload(file: Express.Multer.File) {
         const { originalname, buffer, mimetype } = file
+        let path = 'file/'
+        if (mimetype) {
+            path = mimetype.split('/')[0] + '/'
+        }
+        path +=
+            format(new Date(), 'yyyyMMdd/') +
+            randomstring.generate({ length: 8, charset: 'alphanumeric' }).toLowerCase() +
+            this.getFileExt(originalname)
         Logger.log(`upload file name=${originalname} type=${mimetype}`)
-        const result = await this.aliyunService.uploadFile(originalname, buffer)
+        const result = await this.aliyunService.uploadFile(path, buffer)
         return result
     }
+
+    public getFileExt(filename: string) {
+        const index = filename.lastIndexOf('.')
+        if (index === -1) {
+            return ''
+        }
+        return filename.substring(index)
+    }
 }

+ 1 - 1
src/main.ts

@@ -27,7 +27,7 @@ async function bootstrap() {
     configureSwaggerDocs(app, configService)
 
     app.enableCors({
-        origin: configService.get<string>('ENDPOINT_CORS'),
+        origin: true,
         methods: 'GET,POST,PUT,PATCH,DELETE',
         credentials: true
     })

+ 4 - 3
src/users/dto/user-profile.dto.ts

@@ -1,4 +1,5 @@
-import { OmitType } from '@nestjs/swagger'
-import { UserDto } from './user.dto'
+export class UserProfileDto {
+    name: string
 
-export class UserProfileDto extends OmitType(UserDto, ['password'] as const) {}
+    avatar: string
+}

+ 4 - 1
src/users/dto/user.dto.ts

@@ -1,4 +1,4 @@
-import { MaxLength, IsNotEmpty, IsEmail, IsString } from 'class-validator'
+import { MaxLength, IsNotEmpty, IsEmail, IsString, isString } from 'class-validator'
 
 export class UserDto {
     @IsString()
@@ -9,6 +9,9 @@ export class UserDto {
     @MaxLength(40)
     readonly username: string
 
+    @IsString()
+    readonly avatar: string
+
     @IsEmail()
     @IsString()
     @IsNotEmpty()

+ 3 - 0
src/users/entities/users.entity.ts

@@ -12,6 +12,9 @@ export class Users {
     @Column()
     username: string
 
+    @Column()
+    avatar: string
+
     @Column({ unique: true, nullable: true })
     email: string
 

+ 16 - 18
src/users/users.controller.ts

@@ -8,7 +8,8 @@ import {
     NotFoundException,
     Delete,
     BadRequestException,
-    Req
+    Req,
+    Post
 } from '@nestjs/common'
 import { UsersService } from './users.service'
 import { UserProfileDto } from './dto/user-profile.dto'
@@ -26,6 +27,20 @@ export class UsersController {
         return this.usersService.findById(req.user.userId)
     }
 
+    @Post('/update')
+    public async update(@Body() userProfileDto: UserProfileDto, @Req() req): Promise<any> {
+        try {
+            await this.usersService.updateProfileUser(req.user.userId, userProfileDto)
+
+            return {
+                message: 'User Updated successfully!',
+                status: HttpStatus.OK
+            }
+        } catch (err) {
+            throw new BadRequestException(err, 'Error: User not updated!')
+        }
+    }
+
     @Get()
     public async findAllUser(): Promise<IUsers[]> {
         return this.usersService.findAll()
@@ -50,23 +65,6 @@ export class UsersController {
         }
     }
 
-    @Put('/:userId/profile')
-    public async updateProfileUser(
-        @Param('userId') userId: string,
-        @Body() userProfileDto: UserProfileDto
-    ): Promise<any> {
-        try {
-            await this.usersService.updateProfileUser(userId, userProfileDto)
-
-            return {
-                message: 'User Updated successfully!',
-                status: HttpStatus.OK
-            }
-        } catch (err) {
-            throw new BadRequestException(err, 'Error: User not updated!')
-        }
-    }
-
     @Put('/:userId')
     public async updateUser(@Param('userId') userId: string, @Body() userUpdateDto: UserUpdateDto) {
         try {

+ 2 - 3
src/users/users.service.ts

@@ -102,9 +102,8 @@ export class UsersService {
     public async updateProfileUser(id: string, userProfileDto: UserProfileDto): Promise<Users> {
         try {
             const user = await this.userRepository.findOneBy({ id: +id })
-            user.name = userProfileDto.name
-            user.email = userProfileDto.email
-            user.username = userProfileDto.username
+            if (userProfileDto.name) user.name = userProfileDto.name
+            if (userProfileDto.avatar) user.avatar = userProfileDto.avatar
 
             return await this.userRepository.save(user)
         } catch (err) {

+ 5 - 0
yarn.lock

@@ -2270,6 +2270,11 @@ data-uri-to-buffer@3:
   resolved "https://registry.npmmirror.com/data-uri-to-buffer/-/data-uri-to-buffer-3.0.1.tgz#594b8973938c5bc2c33046535785341abc4f3636"
   integrity sha512-WboRycPNsVw3B3TL559F7kuBUM4d8CgMEvk6xEJlOp7OBPjt6G7z8WMWlD2rOFZLk6OYfFIUGsCOWzcQH9K2og==
 
+date-fns@^2.29.3:
+  version "2.29.3"
+  resolved "https://registry.npmmirror.com/date-fns/-/date-fns-2.29.3.tgz#27402d2fc67eb442b511b70bbdf98e6411cd68a8"
+  integrity sha512-dDCnyH2WnnKusqvZZ6+jA1O51Ibt8ZMRNkDZdyAyK4YfbDwa/cEmuztzG5pk6hqlp9aSBPYcjOlktquahGwGeA==
+
 dateformat@^2.0.0:
   version "2.2.0"
   resolved "https://registry.npmmirror.com/dateformat/-/dateformat-2.2.0.tgz#4065e2013cf9fb916ddfd82efb506ad4c6769062"