Advertisement
nikolayneykov

Untitled

Nov 18th, 2019
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { InvalidImageFormat } from './../../common/errors/invalid-image-format.error';
  2. import { ConfigService } from './../../config/config.service';
  3. import { Injectable } from '@nestjs/common';
  4. import axios from 'axios';
  5. import { extname } from 'path';
  6.  
  7. @Injectable()
  8. export class PhotoStorageService {
  9.   constructor(
  10.     private readonly configService: ConfigService,
  11.   ) { }
  12.  
  13.   async uploadPhoto(photo: any): Promise<{ photoLink: string, photoDeleteHash: string }> {
  14.     if (!(/\.(gif|jpg|jpeg|png)$/i).test(extname(photo.originalname))) {
  15.       throw new InvalidImageFormat();
  16.     }
  17.  
  18.     const image = photo.buffer;
  19.  
  20.     const { data } = await axios(`${this.configService.photoStorageUrl}/upload`, {
  21.       method: 'POST',
  22.       headers: {
  23.         'Authorization': this.configService.clientId,
  24.         'Content-Type': 'multipart/form-data',
  25.       },
  26.       data: image,
  27.     });
  28.  
  29.     return { photoLink: data.data.link, photoDeleteHash: data.data.deletehash };
  30.   }
  31.  
  32.   async deletePhoto(photoDeleteHash: string): Promise<void> {
  33.     await axios(`${this.configService.photoStorageUrl}/image/${photoDeleteHash}`, {
  34.       method: 'DELETE',
  35.       headers: {
  36.         Authorization: this.configService.clientId,
  37.       },
  38.     });
  39.   }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement