存储转发服务

此服务用于以下场景,有模拟服务的需求,可以通过转发服务,记录请求和返回参数,存入本地,下次同样请求,不再请求真实服务。可以用在soap服务,webapi服务。

Router:

import { RouterAbs } from './commons/router.abs';  

import { SystemApiController } from '../controllers/system/systemApi.controller';

import path from 'path';

export class SystemRouter extends RouterAbs {

  config() {

    let controllerName = '/*';

    let _SystemApiController = new SystemApiController();

    this.server.post(controllerName + '/*', _SystemApiController.Proxy.bind(_SystemApiController));

    this.server.get(controllerName + '/*', _SystemApiController.Proxy.bind(_SystemApiController));

    this.server.put(controllerName + '/*', _SystemApiController.Proxy.bind(_SystemApiController));

    this.server.patch(controllerName + '/*', _SystemApiController.Proxy.bind(_SystemApiController));

  }

}

Controller:

import { Request, Response, Next } from 'restify';

import { SystemApiAction } from '../../actions/system/systemApi.action';

import { ControllerAbs } from '../commons/controller.abs';


 

export class SystemApiController extends ControllerAbs {

  public Proxy(req: Request, res: Response, next: Next) {

      let action = new   SystemApiAction();

      action .Proxy(req, res, next);

  }

}

Action:

import { Request, Response, Next } from 'restify';

import { AppUtils } from '../../utils/app.utils';

import { LogHelper } from '../../utils/log.helper';

import { v1 } from 'uuid';

import { Op, Transaction,Sequelize } from 'sequelize';

import { promises } from 'dns';

import { serialize } from 'v8';

import { HttpUtil } from '../../common/http.util';

import { resolve } from 'bluebird';

import request from 'request'

import { Json } from 'sequelize/types/lib/utils';

import { ApiConfig } from '../../api.config';

import X2JS = require("x2js");

export class SystemApiAction  {

  constructor() {

  }


 

  public Proxy(req: Request, res: Response, next: Next) {



 

    let remoteAddress = req.connection.remoteAddress + '';

    let extFile = 'json';

   

    let input = req.body;

    LogHelper.Info(remoteAddress, 'Proxy 开始');

    LogHelper.Info(remoteAddress, 'Proxy 输入参数' + JSON.stringify(input));

    if (req.url && req.method)

    {

       let apiUrl = req.url;

       if (req.headers.soapaction)

       {

          apiUrl = req.headers.soapaction.toString();

       }

       

       let contentType ='json';

       if ( req.headers && req.headers['content-type'] && req.headers['content-type'] .includes('text/xml'))

       {

          contentType = 'xml';    

          extFile = 'xml';  

       }

       let _md5 = AppUtils.CalcMD5( req.method +'|' + apiUrl);

       


 

       AppUtils.WriteLog(apiUrl);

       let fackDataCheckResult = AppUtils. FackDataExist(_md5,extFile);

   

         if (fackDataCheckResult.fileExist)

       {

          let fackData =  AppUtils.GetFackData(fackDataCheckResult.fileName);


 

         

          if (contentType == 'xml')

          {  

            res.sendRaw(   fackData );

          }

         else

          {

            res.send( JSON.parse( fackData));

          }

       }

       else  

     

       {

          let _url =  ApiConfig.targetService + req.url;

          let _method :string = req.method;

     

   

           


 

          request(_url,

           

              { body: req.body ,

                method:_method,  

                json:  contentType == 'json'? true:false,

                headers:req.headers,              

              },


 

            (err, response,body)=>{

                if (!err)

                {

               

                 

                 if (contentType != 'json')

                 {

                 

                    let _txtBody = '';

                    if (body)

                    {

                      _txtBody= body.toString();

                    }


 

                    AppUtils.SaveFackData(_md5,_txtBody,extFile);

                    AppUtils.SaveFackData(_md5,apiUrl,'txt');

                 

                    res.sendRaw(body);

                 }

                 else

                 {

                    let _txtBody = '';

                    if (body)

                    {

                      _txtBody= JSON.stringify(body);

                    }

                    AppUtils.SaveFackData(_md5,_txtBody,extFile);

                    AppUtils.SaveFackData(_md5,apiUrl,'txt');

                   

                    res.send(body);

                 }

       

                }

                else

                {

                  res.send(body);

                }

              }

            );

           

       

        }

       

    }

  }

}

Utils:

import  * as  crypto  from 'crypto';

import { ApiConfig } from '../api.config';

 import { writeFileSync,readFileSync,existsSync} from 'fs';

import { join} from 'path';

import uuid, { v1 } from 'uuid';

import { UUID } from 'sequelize/types';

import { XmlHelper } from './xml.helper';

//import * as tls from 'tls'

export   class AppUtils {

    public static ConvertDateTimeMulitSecondToString(date?:Date):string {

        if (!date )

        {

          date = new Date();

        }

        //let date= new Date();

        let year:number= date.getFullYear();

        let month:string| number=date.getMonth()+1;

        let day:string| number=date.getDate();

        let hour:string| number=date.getHours()<10?"0"+date.getHours():date.getHours();

        let minute:string| number=date.getMinutes()<10?"0"+date.getMinutes():date.getMinutes();

        let second:string| number=date.getSeconds()<10?"0"+date.getSeconds():date.getSeconds();

        let mulitsecond:string| number=date.getMilliseconds()<10?"0"+date.getMilliseconds():date.getMilliseconds();

       

        if (month<10) {

            month="0"+month;

        }

        if (day<10) {

            day="0"+day;

        }

   

        return year+ "-"+month+"-"+day+" "+hour + ":" + minute +":" + second +":" + mulitsecond;

     }

     public static ConvertDateTimeSecondToString(date?:Date):string {

        if (!date )

        {

          date = new Date();

        }

        //let date= new Date();

        let year:number= date.getFullYear();

        let month:string| number=date.getMonth()+1;

        let day:string| number=date.getDate();

        let hour:string| number=date.getHours()<10?"0"+date.getHours():date.getHours();

        let minute:string| number=date.getMinutes()<10?"0"+date.getMinutes():date.getMinutes();

        let second:string| number=date.getSeconds()<10?"0"+date.getSeconds():date.getSeconds();

        let mulitsecond:string| number=date.getMilliseconds()<10?"0"+date.getMilliseconds():date.getMilliseconds();

       

        if (month<10) {

            month="0"+month;

        }

        if (day<10) {

            day="0"+day;

        }

   

        return year+ "-"+month+"-"+day+" "+hour + ":" + minute +":" + second  ;

     }

    public static ConvertDateTimeToString(date?:Date):string {

        if (!date )

        {

          date = new Date();

        }

        //let date= new Date();

        let year:number= date.getFullYear();

        let month:string| number=date.getMonth()+1;

        let day:string| number=date.getDate();

        let hour:string| number=date.getHours()<10?"0"+date.getHours():date.getHours();

        let minute:string| number=date.getMinutes()<10?"0"+date.getMinutes():date.getMinutes();

        let second:string| number=date.getSeconds()<10?"0"+date.getSeconds():date.getSeconds();

     

       

        if (month<10) {

            month="0"+month;

        }

        if (day<10) {

            day="0"+day;

        }

   

        return year+ "-"+month+"-"+day+" "+hour + ":" + minute +":" + second ;

     }

     public static ConvertDateToString(date?:Date):string {

        if (!date )

        {

          date = new Date();

        }

        //let date= new Date();

        let year:number= date.getFullYear();

        let month:string| number=date.getMonth()+1;

        let day:string| number=date.getDate();

        let hour:string| number=date.getHours()<10?"0"+date.getHours():date.getHours();

        let minute:string| number=date.getMinutes()<10?"0"+date.getMinutes():date.getMinutes();

        let second:string| number=date.getSeconds()<10?"0"+date.getSeconds():date.getSeconds();

     

       

        if (month<10) {

            month="0"+month;

        }

        if (day<10) {

            day="0"+day;

        }

   

        return year+ "-"+month+"-"+day  ;

     }

   

     public static WriteLog(msg:string)

     {

         console.log(msg);

     }

     public static ReplenishLeftSpace(input:string , totalLen:number ):string

     {

        var len = this. getStringLen( input);

        if (len == totalLen)

        {}

        else if (len < totalLen)

        {

            input =  this.getSpace( totalLen - len) +  input;

        }

       

        return input;

     }

    public static getStringLen(input:string):number{  

        var   i,len,code;  

        if(input==null || input == "")   return   0;  

        len   =   input.length;  

        for   (i   =   0;i   <   input.length;i++)    

        {    

        code   =   input.charCodeAt(i);  

        if   (code   >   255) {len ++;}  

        }  

        return   len;  

    }

   

    public static getSpace(spacelen:number ):string{  

       

        let result ='';

        let len = spacelen ;// Math.ceil(spacelen/2);

        if (len>0)

        {

            for (let i = 0; i < len ; i++) {

                result = result + ' ';

            }

        }

        return result;

    }

   

    public static  PrefixInteger(num:string, length:number) {

        return (Array(length).join('0') + num).slice(-length);

    }

    public static ReplaceString(input:string,searchValue:string,replaceValue:string)

    {

        let result = '';

        for (let index = 0; index < input.length; index++) {

            let element = input[index];

            element = element.replace(searchValue,replaceValue);

            result = result + element;

        }

        return result;

    }


 

    public static formatParams(params: any): string {

        return Object.keys(params)

          .filter(k => params[k] !== undefined && params[k] !== '')

          .sort()

          .map(k => `${k}=${params[k]}`)

          .join('');

    }

   

    public static CalcMD5(input :string):string{

       

        let md5 =   crypto .createHash('md5');

        md5.update(input);

       

        return md5.digest('hex');

    }

    public static  FileExist(fileName :string):boolean{

        return existsSync( fileName);

    }

   

    public static  FackDataExist(fileName :string,ext? :string):{fileName:string ,fileExist:boolean}

    {

        let result :{fileName:string ,fileExist:boolean} ={fileName:'' ,fileExist:false};

        if (!ext)

        {

            ext ='josn';

        }

        let _fakeFile = AppUtils. GetFacDataFileName(fileName,ext);

        let _exist =  existsSync( _fakeFile);

        result.fileExist = _exist;

        if (_exist)

        {

            result.fileName = _fakeFile;

        }

        return result;

    }

    public static  SaveFackData(fileName :string,bodyTxt :any,ext?:string):string{

        let fullName = '';

        try

        {

            fullName = AppUtils. GetFacDataFileName(fileName,ext);

            //join(__dirname,'assets','fackdata','ward') + fileName + '.json';

            writeFileSync( fullName, bodyTxt, { encoding: 'utf8' , flag: 'w' } )

/*

            if (ext && ext=='json')

            {

                let _jsonBody = JSON.stringify(body);

                writeFileSync( fullName, _jsonBody, { encoding: 'utf8' , flag: 'w' } )

            }

            else  

            {

               

                let _txtBody = '';

                if (body)

                {

                 _txtBody= body.toString();

                }

                writeFileSync( fullName, _txtBody, { encoding: 'utf8' , flag: 'w' } )

            }

 */

        }

       catch(err)  {

            console.error(err);

           

       }

       

        return fullName;

         

    }

    public static  GetFackData(fileName :string):string{

     

     

      let content:string =  readFileSync(fileName,{ encoding: 'utf8', flag: 'r'  } );

      return content;

    }

    public static GetFacDataFileName(fileName: string,ext?:string): string {

        let url =  join(  __dirname,'../../','assets','fackdata',fileName);

   

        if (ext)

        {

           //url = 'http://localhost:' + ApiConfig.port + '/assets/fackdata/ward/' + fileName + '.' + ext;

           url +=  '.' + ext;

        }

        else

        {

           url +=  '.' + 'json';

        }

   

        return url;

      }


 

      public static GetRandomNum(Min:number,Max:number)

      {  

            let Range = Max - Min;  

            let Rand = Math.random();  

            return(Min + Math.round(Rand * Range));  

      }

      public static GetUUID():string{

        return uuid.v1();

      }

}





 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值