file author Innei
 *  description import { Injectable , Logger } from '@nestjs/common' ; import fs from 'fs' ; import path , { join } from 'path' ; import { promisify } from 'util' ; import { USER_ASSET_DIR } from '~/constants/path.constant' ; import { HttpService } from './helper.http.service' ; @ Injectable ( ) export class AssetService { private logger : Logger ; constructor ( private readonly httpService ) { this . logger = new Logger ( AssetService . name ) ; } /**
     * 内置资源地址
     */ public embedAssetPath = path . resolve ( process . cwd ( ) , 'assets' ) ; private onlineAssetPath = 'https://cdn.jsdelivr.net/gh/mx-space/assets@master/' ; private checkRoot ( ) { if ( ! fs . existsSync ( this . embedAssetPath ) ) { return false ; } return true ; } param path returns private checkAssetPath ( path ) { if ( ! this . checkRoot ( ) ) { return false ; } path = join ( this . embedAssetPath , path ) ; if ( ! fs . existsSync ( path ) ) { return false ; } return true ; } private async getUserCustomAsset ( path , options ) { if ( fs . existsSync ( join ( USER_ASSET_DIR , path ) ) ) { return await promisify ( fs . readFile ) ( join ( USER_ASSET_DIR , path ) , options ) ; } return null ; } public async getAsset ( path , options ) { if ( await this . getUserCustomAsset ( path , options ) ) { return this . getUserCustomAsset ( path , options ) ; } if ( ! this . checkAssetPath ( path ) ) { try { const { data } = await this . httpService . axiosRef . get < string > ( this . onlineAssetPath + path ) ; fs . mkdirSync ( ( ( ) => { const p = join ( this . embedAssetPath , path ) . split ( '/' ) ; return p . slice ( 0 , p . length - 1 ) . join ( '/' ) ; } ) ( ) , { recursive : true } ) ; await promisify ( fs . writeFile ) ( join ( this . embedAssetPath , path ) , data , options ) ; return data ; } catch ( e ) { this . logger . error ( '本地资源不存在，线上资源无法拉取' ) ; throw e ; } } return promisify ( fs . readFile ) ( join ( this . embedAssetPath , path ) , options ) ; } public writeUserCustomAsset ( path , data , options ) { fs . mkdirSync ( ( ( ) => { const p = join ( USER_ASSET_DIR , path ) . split ( '/' ) ; return p . slice ( 0 , p . length - 1 ) . join ( '/' ) ; } ) ( ) , { recursive : true } ) ; fs . writeFileSync ( join ( USER_ASSET_DIR , path ) , data , options ) ; } public async removeUserCustomAsset ( path ) { return promisify ( fs . unlink ) ( join ( USER_ASSET_DIR , path ) ) ; } }