amiddy
Version:
Middleware server with high configurability for development
1 lines • 1.46 kB
JavaScript
import micromatch from"micromatch";import mime from"mime-types";import file from"../file.js";import proxyUtils from"./utils.js";const privateApi={};privateApi.getFileName=(pattern,data)=>{let path=data.path,ignoreFromChar=path.indexOf("?");const anchorCharIndex=path.indexOf("#");return-1<anchorCharIndex&&(anchorCharIndex<ignoreFromChar||-1===ignoreFromChar)&&(ignoreFromChar=anchorCharIndex),-1<ignoreFromChar&&(path=path.substr(0,ignoreFromChar)),path=path.replace(/[/.]/g,"_"),pattern.replace(/{METHOD}/,data.method).replace(/{PATH}/,path).replace(/{EXT}/,data.ext).replace(/{STATUS}/,data.status)},privateApi.saveToFile=(body,proxyRes,config)=>{const{headers,req:{method,path},statusCode}=proxyRes,{deps,options:{recorder:{fileNamePattern,ignorePatterns,path:recorderPath}}}=config;let shouldIgnore=!proxyUtils.getDependency(deps,path);if(shouldIgnore||(shouldIgnore=micromatch.isMatch(path,ignorePatterns||[],{contains:!0})),!shouldIgnore){const ext=mime.extension(headers["content-type"]);let filePath=privateApi.getFileName(fileNamePattern,{ext,method,path,status:statusCode});recorderPath&&(filePath=`${recorderPath}/${filePath}`),file.write(filePath,body)}};const service={saveResponse:(proxyRes,config)=>{if(config.options.recorder.enabled){let body=[];proxyRes.on("data",chunk=>{body.push(chunk)}),proxyRes.on("end",()=>{body=Buffer.concat(body).toString(),privateApi.saveToFile(body,proxyRes,config)})}}};export{privateApi};export default service;