@bchr/bchr-front-lib 0.5.8 → 0.5.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -455,6 +455,617 @@ const http = {
455
455
  this.redirectTo("main_view", parameterObject)
456
456
  }
457
457
  },
458
+
459
+ post: function (options, jsonObject, mockData) {
460
+ let ajaxOptions = {};
461
+ let failedDealFunction = this.dealAjaxException;
462
+ if (lodash.isPlainObject(options)) {
463
+ if (lodash.isFunction(options.fail)) {
464
+ failedDealFunction = options.fail
465
+ delete options.fail;
466
+ }
467
+ ajaxOptions = {...options};
468
+ }
469
+
470
+ try {
471
+ this.__checkJSONObjectSecurity(jsonObject)
472
+ }
473
+ catch (e) {
474
+ let promise = new Promise(function (resolve, reject) {
475
+ return reject(e);
476
+ });
477
+
478
+ if (this.isUseDefaultExceptionHandler()) {
479
+ return promise.catch(failedDealFunction);
480
+ }
481
+
482
+ return promise;
483
+ }
484
+
485
+ if (jsonObject) {
486
+ ajaxOptions.data = jsonObject;
487
+ }
488
+
489
+ if (ajaxOptions.rpcMethodName) {
490
+ delete ajaxOptions.rpcMethodName;
491
+ }
492
+
493
+ ajaxOptions.type = "post";
494
+ ajaxOptions.dataType = "json";
495
+
496
+ if (!ajaxOptions.url) {
497
+ ajaxOptions.url = this.getRequestPath(options);
498
+ }
499
+
500
+ if (this.isValidMockData(mockData)) {
501
+ let promise = this.__postForMock(mockData);
502
+ if (this.isUseDefaultExceptionHandler()) {
503
+ return promise.catch(failedDealFunction);
504
+ }
505
+ return promise;
506
+ }
507
+ else {
508
+ let deferred = window.$.ajax(ajaxOptions);
509
+
510
+ if (this.isUseDefaultExceptionHandler()) {
511
+ return this.__toStdPromise(deferred, failedDealFunction);
512
+ }
513
+ else {
514
+ return this.__toStdPromise(deferred);
515
+ }
516
+ }
517
+ },
518
+
519
+ __postForMock: function (mockData) {
520
+
521
+ let waitTime = mockData.waitTime ? mockData.waitTime : 600;
522
+ return new Promise(function (resolve, reject) {
523
+
524
+ setTimeout(function () {
525
+ if (mockData.success === false) {
526
+ return reject(new Error(mockData.message ? mockData.message : "请求数据发生异常"));
527
+ }
528
+ else {
529
+ let resultData = mockData.data ? mockData.data : mockData;
530
+ return resolve(resultData);
531
+ }
532
+ }, waitTime)
533
+ });
534
+ },
535
+
536
+ postJSONWithNotCareSecurity: function(options, jsonObject, mockData) {
537
+ let ajaxOptions = {};
538
+ let failedDealFunction = this.dealAjaxException;
539
+ if (lodash.isPlainObject(options)) {
540
+ if (lodash.isFunction(options.fail)) {
541
+ failedDealFunction = options.fail
542
+ delete options.fail;
543
+ }
544
+ ajaxOptions = {...options};
545
+ }
546
+
547
+ if (ajaxOptions.rpcMethodName) {
548
+ delete ajaxOptions.rpcMethodName;
549
+ }
550
+
551
+ if (lodash.isPlainObject(ajaxOptions.data)) {
552
+ jsonObject = ajaxOptions.data;
553
+ }
554
+
555
+ if (jsonObject) {
556
+ ajaxOptions.data = jsonObject;
557
+ }
558
+
559
+ if (ajaxOptions.data) {
560
+ ajaxOptions.data = JSON.stringify(ajaxOptions.data);
561
+ }
562
+
563
+ ajaxOptions.type = "post";
564
+ ajaxOptions.dataType = "json";
565
+ ajaxOptions.contentType = "application/json; charset=utf-8";
566
+ if (!ajaxOptions.url) {
567
+ ajaxOptions.url = this.getRequestPath(options);
568
+ }
569
+
570
+ if (this.isValidMockData(mockData)) {
571
+ let promise = this.__postJSONForMock(mockData);
572
+ if (this.isUseDefaultExceptionHandler()) {
573
+ return promise.catch(failedDealFunction);
574
+ }
575
+ return promise;
576
+ }
577
+ else {
578
+ let deferred = window.$.ajax(ajaxOptions);
579
+ if (this.isUseDefaultExceptionHandler()) {
580
+ return this.__toStdPromise(deferred, failedDealFunction);
581
+ }
582
+ else {
583
+ return this.__toStdPromise(deferred);
584
+ }
585
+ }
586
+ },
587
+
588
+ postJSON: function(options, jsonObject, mockData) {
589
+ let ajaxOptions = {};
590
+ let failedDealFunction = this.dealAjaxException;
591
+ if (lodash.isPlainObject(options)) {
592
+ if (lodash.isFunction(options.fail)) {
593
+ failedDealFunction = options.fail
594
+ delete options.fail;
595
+ }
596
+ ajaxOptions = {...options};
597
+ }
598
+
599
+ if (lodash.isPlainObject(ajaxOptions.data)) {
600
+ jsonObject = ajaxOptions.data;
601
+ }
602
+
603
+ try {
604
+ this.__checkJSONObjectSecurity(jsonObject)
605
+ }
606
+ catch (e) {
607
+ let promise = new Promise(function (resolve, reject) {
608
+ return reject(e);
609
+ });
610
+
611
+ if (this.isUseDefaultExceptionHandler()) {
612
+ return promise.catch(failedDealFunction);
613
+ }
614
+
615
+ return promise;
616
+ }
617
+
618
+ return this.postJSONWithNotCareSecurity(options, jsonObject, mockData);
619
+ },
620
+
621
+ postJSONAllowHTML: function(options, jsonObject, mockData) {
622
+ let ajaxOptions = {};
623
+ let failedDealFunction = this.dealAjaxException;
624
+ if (lodash.isPlainObject(options)) {
625
+ if (lodash.isFunction(options.fail)) {
626
+ failedDealFunction = options.fail
627
+ delete options.fail;
628
+ }
629
+ ajaxOptions = {...options};
630
+ }
631
+
632
+ if (lodash.isPlainObject(ajaxOptions.data)) {
633
+ jsonObject = ajaxOptions.data;
634
+ }
635
+
636
+ try {
637
+ this.__checkJSONObjectContainsScriptTag(jsonObject)
638
+ }
639
+ catch (e) {
640
+ let promise = new Promise(function (resolve, reject) {
641
+ return reject(e);
642
+ });
643
+
644
+ if (this.isUseDefaultExceptionHandler()) {
645
+ return promise.catch(failedDealFunction);
646
+ }
647
+
648
+ return promise;
649
+ }
650
+
651
+ return this.postJSONWithNotCareSecurity(options, jsonObject, mockData);
652
+ },
653
+
654
+ __checkJSONObjectContainsScriptTag: function(jsonObject) {
655
+ if (!jsonObject) {
656
+ return;
657
+ }
658
+
659
+ if (lodash.isString(jsonObject)) {
660
+ this.__checkStringContainsScriptTag(jsonObject);
661
+ }
662
+ else if (Array.isArray(jsonObject)) {
663
+ let len = jsonObject.length;
664
+ if (len === 0) {
665
+ return;
666
+ }
667
+
668
+ for (let i = 0; i < len; i++) {
669
+ this.__checkJSONObjectContainsScriptTag(jsonObject[i]);
670
+ }
671
+ }
672
+ else if (lodash.isPlainObject(jsonObject)) {
673
+ for (let p in jsonObject) {
674
+ this.__checkJSONObjectContainsScriptTag(jsonObject[p]);
675
+ }
676
+ }
677
+
678
+ return;
679
+ },
680
+
681
+ __checkStringContainsScriptTag: function(str) {
682
+ if (!str || str.length < 3) {
683
+ return;
684
+ }
685
+
686
+ let containsHTML = /<(noframes|noscript|object|script|video).*?<\/\2>/i.test(str);
687
+ if (containsHTML) {
688
+ throw new IllegalArgumentError("不安全的输入,请检查!");
689
+ }
690
+ },
691
+
692
+ __checkJSONObjectSecurity: function(jsonObject) {
693
+ if (!jsonObject) {
694
+ return;
695
+ }
696
+
697
+ if (lodash.isString(jsonObject)) {
698
+ this.__checkStringIfSecurity(jsonObject);
699
+ }
700
+ else if (Array.isArray(jsonObject)) {
701
+ let len = jsonObject.length;
702
+ if (len === 0) {
703
+ return;
704
+ }
705
+
706
+ for (let i = 0; i < len; i++) {
707
+ this.__checkJSONObjectSecurity(jsonObject[i]);
708
+ }
709
+ }
710
+ else if (lodash.isPlainObject(jsonObject)) {
711
+ for (let p in jsonObject) {
712
+ this.__checkJSONObjectSecurity(jsonObject[p]);
713
+ }
714
+ }
715
+
716
+ return;
717
+ },
718
+
719
+ __checkStringIfSecurity: function(str) {
720
+ if (!str || str.length < 3) {
721
+ return;
722
+ }
723
+
724
+ let containsHTML = /<(br|basefont|hr|input|source|frame|param|area|meta|!--|col|link|option|base|img|wbr|!DOCTYPE).*?>|<(a|abbr|acronym|address|applet|article|aside|audio|b|bdi|bdo|big|blockquote|body|button|canvas|caption|center|cite|code|colgroup|command|datalist|dd|del|details|dfn|dialog|dir|div|dl|dt|em|embed|fieldset|figcaption|figure|font|footer|form|frameset|head|header|hgroup|h1|h2|h3|h4|h5|h6|html|i|iframe|ins|kbd|keygen|label|legend|li|map|mark|menu|meter|nav|noframes|noscript|object|ol|optgroup|output|p|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|small|span|strike|strong|style|sub|summary|sup|table|tbody|td|textarea|tfoot|th|thead|time|title|tr|track|tt|u|ul|var|video).*?<\/\2>/i.test(str);
725
+ if (containsHTML) {
726
+ throw new IllegalArgumentError("不安全的输入,请检查!");
727
+ }
728
+ },
729
+
730
+ __postJSONForMock: function(mockData) {
731
+ let waitTime = mockData.waitTime ? mockData.waitTime : 300;
732
+ return new Promise(function (resolve, reject) {
733
+ setTimeout(function () {
734
+ if (mockData.success === false) {
735
+ return reject(new Error(mockData.message ? mockData.message : "请求数据发生异常"));
736
+ }
737
+ else {
738
+ let resultData = mockData.data ? mockData.data : mockData;
739
+ return resolve(resultData);
740
+ }
741
+ }, waitTime)
742
+ });
743
+ },
744
+
745
+ getJSON: function(options, paramObject, mockData) {
746
+ let ajaxOptions = {};
747
+ let failedDealFunction = this.dealAjaxException;
748
+ if (lodash.isPlainObject(options)) {
749
+ if (lodash.isFunction(options.fail)) {
750
+ failedDealFunction = options.fail
751
+ delete options.fail;
752
+ }
753
+ ajaxOptions = {...options};
754
+ }
755
+
756
+ ajaxOptions.type = "get";
757
+ ajaxOptions.dataType = "json";
758
+ if (lodash.isPlainObject(paramObject)) {
759
+ ajaxOptions.data = paramObject;
760
+ }
761
+
762
+ if (!ajaxOptions.data){
763
+ ajaxOptions.data = {};
764
+ }
765
+
766
+ if (!ajaxOptions.data.euts) {
767
+ ajaxOptions.data.euts = (new Date()).getTime();
768
+ }
769
+
770
+ if (!ajaxOptions.url) {
771
+ ajaxOptions.url = this.getRequestPath(options);
772
+ }
773
+
774
+ if (this.isValidMockData(mockData)) {
775
+ let promise = this.__getJSONForMock(mockData);
776
+ if (this.isUseDefaultExceptionHandler()) {
777
+ return promise.catch(failedDealFunction);
778
+ }
779
+ return promise;
780
+ }
781
+ else {
782
+ let deferred = window.$.ajax(ajaxOptions);
783
+ if (this.isUseDefaultExceptionHandler()) {
784
+ return this.__toStdPromise(deferred, failedDealFunction);
785
+ }
786
+ else {
787
+ return this.__toStdPromise(deferred);
788
+ }
789
+ }
790
+ },
791
+
792
+ isValidMockData : function (mockData) {
793
+ if (mockData === null || mockData === void 0) {
794
+ return false;
795
+ }
796
+
797
+ return lodash.isPlainObject(mockData);
798
+ },
799
+
800
+ __getJSONForMock: function(mockData) {
801
+
802
+ let waitTime = mockData.waitTime ? mockData.waitTime : 600;
803
+ return new Promise(function (resolve, reject) {
804
+
805
+ setTimeout(function () {
806
+ if (mockData.success === false) {
807
+ return reject(new Error(mockData.message ? mockData.message : "请求数据发生异常"));
808
+ }
809
+ else {
810
+ let resultData = mockData.data ? mockData.data : mockData;
811
+ return resolve(resultData);
812
+ }
813
+ }, waitTime)
814
+ });
815
+ },
816
+
817
+ requestStaticHTMLTemplate: function(staticTemplateFilePath) {
818
+ let deferred = window.$.ajax({
819
+ url : staticTemplateFilePath,
820
+ dataType: "html"
821
+ });
822
+
823
+ let failedDealFunction = this.dealAjaxException;
824
+ return this.__toStdPromise(deferred, failedDealFunction);
825
+ },
826
+
827
+ downloadFileByPostJSON: function (options, jsonObject, saveFileName) {
828
+ let ajaxOptions = {};
829
+ let failedDealFunction = this.dealAjaxException;
830
+ if (lodash.isPlainObject(options)) {
831
+ if (lodash.isFunction(options.fail)) {
832
+ failedDealFunction = options.fail
833
+ delete options.fail;
834
+ }
835
+ ajaxOptions = {...options};
836
+ }
837
+
838
+ if (lodash.isPlainObject(ajaxOptions.data)) {
839
+ jsonObject = ajaxOptions.data;
840
+ }
841
+
842
+ try {
843
+ this.__checkJSONObjectSecurity(jsonObject)
844
+ }
845
+ catch (e) {
846
+ let promise = new Promise(function (resolve, reject) {
847
+ return reject(e);
848
+ });
849
+
850
+ if (this.isUseDefaultExceptionHandler()) {
851
+ return promise.catch(failedDealFunction);
852
+ }
853
+
854
+ return promise;
855
+ }
856
+
857
+ if (jsonObject) {
858
+ ajaxOptions.data = jsonObject;
859
+ }
860
+
861
+ if (ajaxOptions.rpcMethodName) {
862
+ delete ajaxOptions.rpcMethodName;
863
+ }
864
+
865
+ ajaxOptions.type = "post";
866
+ ajaxOptions.dataType = "*";
867
+
868
+ if (!ajaxOptions.data){
869
+ ajaxOptions.data = {};
870
+ }
871
+
872
+ if (!ajaxOptions.data.euts) {
873
+ ajaxOptions.data.euts = (new Date()).getTime();
874
+ }
875
+
876
+ if (!ajaxOptions.url) {
877
+ ajaxOptions.url = this.getRequestPath(options);
878
+ }
879
+
880
+ ajaxOptions.xhrFields = {
881
+ responseType: "blob"
882
+ }
883
+
884
+ ajaxOptions.success = function (result, request, xhr) {
885
+ let fileName = "下载文件-" + new Date().getTime();
886
+ if (lodash.isString(saveFileName) && saveFileName.length > 0) {
887
+ fileName = saveFileName
888
+ }
889
+ else {
890
+ let contentDisposition = xhr.getResponseHeader('Content-Disposition');
891
+ if (contentDisposition && contentDisposition.split) {
892
+ let parts = contentDisposition.split(';');
893
+ if (parts.length >= 1) {
894
+ let fileInfo = parts[1]
895
+ let fileInfoArray = fileInfo.split('=');
896
+ if (fileInfoArray.length >= 1) {
897
+ fileName = fileInfoArray[1];
898
+ fileName = decodeURIComponent(fileName)
899
+ fileName = fileName.replaceAll("\"", "")
900
+ }
901
+ }
902
+ }
903
+ }
904
+
905
+ let type = xhr.getResponseHeader("content-type")
906
+ if (!type) {
907
+ type = "application/octet-stream";
908
+ }
909
+ let blob = new Blob([result], { type: type })
910
+ saveAs(blob, fileName)
911
+ }
912
+
913
+ ajaxOptions.error = function (error) {
914
+ console.log('ajaxOptions :', error)
915
+ }
916
+
917
+ let deferred = window.$.ajax(ajaxOptions);
918
+
919
+ if (this.isUseDefaultExceptionHandler()) {
920
+ return this.__toStdPromise(deferred, failedDealFunction);
921
+ }
922
+ else {
923
+ return this.__toStdPromise(deferred);
924
+ }
925
+ },
926
+
927
+ createRequestURL: function (requestURL, params) {
928
+ let lastRequestURL = this.getRequestPath(requestURL);
929
+ if (!params) {
930
+ return lastRequestURL;
931
+ }
932
+ else if (lodash.isString(params)) {
933
+ if (requestURL.includes('?')) {
934
+ let requestURLData = queryString.parseUrl(requestURL);
935
+ if (JSON.stringify(requestURLData.query) === '{}') {
936
+ return `${requestURL}${params}`;
937
+ }
938
+ return `${requestURL}&${params}`;
939
+ }
940
+ return `${requestURL}?${params}`;
941
+ }
942
+ else if (lodash.isPlainObject(params)) {
943
+ if (requestURL.includes('?')) {
944
+ let requestURLData = queryString.parseUrl(requestURL);
945
+ if (JSON.stringify(requestURLData.query) === '{}') {
946
+ return `${requestURL}${this.encodeObject2ParameterString(params)}`;
947
+ }
948
+ return `${requestURL}&${this.encodeObject2ParameterString(params)}`;
949
+ }
950
+ return `${requestURL}?${this.encodeObject2ParameterString(params)}`;
951
+ }
952
+ },
953
+
954
+ /**
955
+ * !important! <br/>
956
+ * DoNot use this pointer in this function body.
957
+ */
958
+ dealAjaxException: function (httpExceptionResponse) {
959
+ let errorID = "[ClientTraceID=" + new Date().getTime() + "] ";
960
+ let errorMsg = null;
961
+ if (lodash.isString(httpExceptionResponse)) {
962
+ errorMsg = httpExceptionResponse;
963
+ Toast.error(errorMsg)
964
+ }
965
+ else if (httpExceptionResponse && (httpExceptionResponse.responseJSON || httpExceptionResponse.response)) {
966
+ let responseJSON = httpExceptionResponse.responseJSON || (Strings.isNotBlankString(httpExceptionResponse.response) ? JSON.parse(httpExceptionResponse.response) : httpExceptionResponse.response);
967
+ let responseJSONData = responseJSON.resultData || responseJSON.data;
968
+ let statusCode = responseJSON.statusCode;
969
+ if (statusCode && statusCode > 40000 && statusCode < 50000) {
970
+ errorMsg = responseJSON.msg || responseJSON.message;
971
+ Toast.error(errorMsg)
972
+ console.error(errorID + "Http request error:" + errorMsg, httpExceptionResponse)
973
+ if (isNeedForceRedirect()) {
974
+ setTimeout(() => {
975
+ forceRedirectToForError();
976
+ }, 300)
977
+ }
978
+
979
+ return httpExceptionResponse;
980
+ }
981
+
982
+ if (Values.isNotEmptyArray(responseJSONData)) {
983
+ let msgItemList = responseJSONData.map(msgItem => <li>{msgItem}</li>)
984
+ let durationSeconds = responseJSONData.length * 1;
985
+ durationSeconds = durationSeconds < 3 ? 3 : durationSeconds;
986
+ let multiLineOpts = {
987
+ content: (
988
+ <>
989
+ <div>{responseJSON.msg}</div>
990
+ <ol style={{ marginTop: 8, paddingLeft: 0 }}>
991
+ {msgItemList}
992
+ </ol>
993
+ </>
994
+ ),
995
+ duration: durationSeconds,
996
+ };
997
+ Toast.error(multiLineOpts);
998
+ } else {
999
+ if (responseJSON.error) {
1000
+ if (Values.isNotBlankString(responseJSON.error.msg)) {
1001
+ errorMsg = responseJSON.error.msg;
1002
+ }
1003
+ else if (Values.isNotBlankString(responseJSON.error.message)) {
1004
+ errorMsg = responseJSON.error.message;
1005
+ }
1006
+ else if (Values.isNotBlankString(responseJSON.error)) {
1007
+ errorMsg = responseJSON.error;
1008
+ }
1009
+
1010
+ if (Values.isNotBlankString(errorMsg)) {
1011
+ Toast.error(errorMsg)
1012
+ }
1013
+ } else {
1014
+ errorMsg = responseJSON.msg || responseJSON.message || responseJSON.err;
1015
+
1016
+ if (Values.isNotBlankString(errorMsg)) {
1017
+ Toast.error(errorMsg)
1018
+ }
1019
+ }
1020
+ }
1021
+ console.error(errorID + "Http request error:" + errorMsg, httpExceptionResponse)
1022
+ return httpExceptionResponse;
1023
+ }
1024
+ else if (Values.isNotBlankString(httpExceptionResponse.message)) {
1025
+ Toast.error(httpExceptionResponse.message)
1026
+ }
1027
+ else if (httpExceptionResponse.status === 502) {
1028
+ Toast.error("[502]服务正在重启,请稍后重试")
1029
+ }
1030
+ else if (httpExceptionResponse.status === 200) {
1031
+ Toast.error("[200]Http状态码为200,但是出错,可能的原因是数据格式转换异常,请排查。")
1032
+ }
1033
+ else if (httpExceptionResponse.status === 404) {
1034
+ let contentType = httpExceptionResponse.getResponseHeader("Content-Type");
1035
+ if (Values.isNotBlankString(contentType) && !contentType.toLowerCase().startsWith("application/json")) {
1036
+ // because the request is always to for backend service
1037
+ // but when failed, we always return json;
1038
+ // when not json, that is always the backend service not available (not start);
1039
+ Toast.error("[404] Not Found, 可能是后端服务尚未启动.")
1040
+ if (isNeedForceRedirect()) {
1041
+ setTimeout(() => {
1042
+ forceRedirectToForError();
1043
+ }, 300)
1044
+ }
1045
+ }
1046
+ else {
1047
+ Toast.error("[404] Not Found(所请求的资源不存在)")
1048
+ }
1049
+ }
1050
+ else if (httpExceptionResponse.status === 0 || httpExceptionResponse.readyState === 0) {
1051
+ Toast.error("应用服务链路不通:请联系管理员检查应用服务是否已启动.")
1052
+ }
1053
+ else if (httpExceptionResponse.status && httpExceptionResponse.statusText) {
1054
+ let errorTip = "[" + httpExceptionResponse.status + "] " + httpExceptionResponse.statusText;
1055
+ Toast.error(errorTip)
1056
+ }
1057
+
1058
+ console.error(errorID + "Maybe Http request error or Unresolved promise message:", httpExceptionResponse)
1059
+ return httpExceptionResponse;
1060
+ },
1061
+
1062
+ __toStdPromise: function (deferred, failedDealFunction) {
1063
+ if (failedDealFunction === null || failedDealFunction === void 0) {
1064
+ return Promise.resolve(deferred);
1065
+ }
1066
+
1067
+ return Promise.resolve(deferred).catch(failedDealFunction)
1068
+ }
458
1069
  }
459
1070
 
460
1071
  export default http;