amiddy
Version:
Middleware server with high configurability for development
1 lines • 1.98 kB
JavaScript
import chalk from"chalk";const privateApi={};privateApi.methodBg={DELETE:chalk.bgRed.white,GET:chalk.bgGreen.black,HEAD:chalk.bgCyanBright.black,PATCH:chalk.bgCyan.black,POST:chalk.bgBlue.white,PUT:chalk.bgBlueBright.white},privateApi.statusColor={2:chalk.green,3:chalk.yellow,4:chalk.redBright,5:chalk.red},privateApi.messageColors={error:{category:chalk.bgRed.white,text:chalk.red},success:{category:chalk.bgGreen.black,text:chalk.green}},privateApi.message=(message,category,type)=>{const color=privateApi.messageColors[type]||privateApi.messageColors.success,categoryLog=category?color.category(`[${category}]`):"";console.log(`${categoryLog} ${color.text(message)}`)},privateApi.method=name=>{const color=privateApi.methodBg[name]||chalk.bgMagenta.black;return color(` ${name.padEnd(7," ")} `)},privateApi.status=code=>{const codePrefix=Math.floor(code/100),color=privateApi.statusColor[codePrefix]||chalk.magenta;return color(` ${code} `)},privateApi.time=(start,now)=>{const time=now-start;let str=time.toString(),unit="ms";if(1e3<time){const seconds=time/1e3;let fractionDigit=2;100<seconds?fractionDigit=0:10<seconds&&(fractionDigit=1),str=seconds.toFixed(fractionDigit),unit="s"}return chalk.gray(`${str.padStart(5," ")} ${unit.padStart(2," ")} `)},privateApi.mock=isMock=>{let str="PROXY",color=chalk.bgBlack.white;return isMock&&(str="MOCK",color=chalk.bgBlack.yellow),color(` ${str.padEnd(5," ")} `)};const service={response:(data,res)=>{let executionTime,isMock=!1;if(data.startTime){const now=global.Date.now();executionTime=privateApi.time(data.startTime,now)}else isMock=!0,executionTime=privateApi.time(0,0);const msgParts=[privateApi.method(data.method),privateApi.status(res.statusCode),executionTime,privateApi.mock(isMock),data.uri];console.log(msgParts.join(""))},error:(message,category)=>{privateApi.message(message,category,"error")},success:(message,category)=>{privateApi.message(message,category,"success")}};export{privateApi};export default service;