|
| 1 | +import axios from 'axios' |
| 2 | +import { Config } from '../config/config.interface' |
| 3 | +import Logger from '../pkg/logger' |
| 4 | +import S3 from './s3' |
| 5 | +import error from '../pkg/error' |
| 6 | + |
| 7 | +class FileGenerator { |
| 8 | + constructor( |
| 9 | + private config: Config, |
| 10 | + private s3: S3, |
| 11 | + private logger: Logger |
| 12 | + ) {} |
| 13 | + |
| 14 | + public async ImageCompression( |
| 15 | + uri: string, |
| 16 | + quality: number, |
| 17 | + convertTo: string, |
| 18 | + path: string |
| 19 | + ) { |
| 20 | + try { |
| 21 | + const { url, size } = await this.send('convert-image', { |
| 22 | + url: uri, |
| 23 | + quality, |
| 24 | + convertTo, |
| 25 | + }) |
| 26 | + |
| 27 | + const { data, headers } = await axios.get(url, { |
| 28 | + responseType: 'arraybuffer', |
| 29 | + }) |
| 30 | + |
| 31 | + const contentType = headers['content-type'] || '' |
| 32 | + |
| 33 | + await this.s3.Upload(data, path, contentType) |
| 34 | + this.logger.Info('process compress image success', { |
| 35 | + category: 'compress-image', |
| 36 | + }) |
| 37 | + return size |
| 38 | + } catch (error: any) { |
| 39 | + this.logger.Error( |
| 40 | + 'process compress image failed: ' + error.message, |
| 41 | + { category: 'compress-image' } |
| 42 | + ) |
| 43 | + throw error |
| 44 | + } |
| 45 | + } |
| 46 | + |
| 47 | + private async send(path: string, body: object) { |
| 48 | + try { |
| 49 | + const { data } = await axios.post( |
| 50 | + this.config.generator_file.url + '/' + path, |
| 51 | + body |
| 52 | + ) |
| 53 | + |
| 54 | + return data.data |
| 55 | + } catch (err: any) { |
| 56 | + const message = err.message |
| 57 | + |
| 58 | + this.logger.Error(message, { |
| 59 | + category: FileGenerator.name, |
| 60 | + }) |
| 61 | + |
| 62 | + throw new error(err.status, message) |
| 63 | + } |
| 64 | + } |
| 65 | +} |
| 66 | + |
| 67 | +export default FileGenerator |
0 commit comments