import { reduce , some } from "lodash" ; import md5 from "md5" ; import { isMatch } from "micromatch" ; import { getType } from "mime" ; import { BundleFallbackAssetNotFoundError } from "../common/errors" ; import generateId from "../common/generateId" ; import Usecase from "../common/Usecase" ; import { IBundle , validateBundleNameOrTag } from "../entities/Bundle" ; import { Operation } from "../entities/OperationLog" ; export default class CreateBundle extends Usecase { async exec ( partial ) { await this . authorizer . ensureCanCreateBundle ( partial . name ) ; validateBundleNameOrTag ( partial . name , "name" ) ; validateBundleNameOrTag ( partial . tag , "tag" ) ; const id = generateId ( ) ; const files = await this . archiver . extractFiles ( partial . content ) ; const assets = files . map ( ( file ) => { return { path : file . path , mimeType : getType ( file . path ) || "application/octet-stream" , content : file . content , headers : reduce ( partial . headers , ( finalHeaders , headers , assetMatcher ) => ( { ... finalHeaders , ... ( isMatch ( file . path , assetMatcher ) ? headers : null ) , } ) , { } ) , } ; } ) ; if ( ! some ( assets , { path : partial . fallbackAssetPath } ) ) { throw new BundleFallbackAssetNotFoundError ( partial . fallbackAssetPath ) ; } const createdBundle = await this . storages . bundles . createOne ( { id : id , name : partial . name , tag : partial . tag , description : partial . description , hash : md5 ( partial . content ) , assets : assets , fallbackAssetPath : partial . fallbackAssetPath , fallbackStatusCode : partial . fallbackStatusCode , createdAt : new Date ( ) , } ) ; await this . operationLogger . logOperation ( Operation . CreateBundle , { createdBundle , } ) ; return createdBundle ; } }