gitlab.com/evatix-go/core@v1.3.55/coredata/corejson/Result.go (about) 1 package corejson 2 3 import ( 4 "bytes" 5 "encoding/json" 6 "errors" 7 "fmt" 8 9 "gitlab.com/evatix-go/core/constants" 10 "gitlab.com/evatix-go/core/coredata" 11 "gitlab.com/evatix-go/core/coreindexes" 12 "gitlab.com/evatix-go/core/defaulterr" 13 "gitlab.com/evatix-go/core/errcore" 14 "gitlab.com/evatix-go/core/internal/csvinternal" 15 "gitlab.com/evatix-go/core/internal/reflectinternal" 16 ) 17 18 type Result struct { 19 jsonString *string 20 Bytes []byte 21 Error error 22 TypeName string 23 } 24 25 func (it *Result) Map() map[string]string { 26 if it == nil { 27 return map[string]string{} 28 } 29 30 newMap := make( 31 map[string]string, 32 constants.Capacity3) 33 34 if len(it.Bytes) > 0 { 35 newMap[bytesFieldName] = it.JsonString() 36 } 37 38 if it.Error != nil { 39 newMap[errorFieldName] = it.Error.Error() 40 } 41 42 if it.TypeName != "" { 43 newMap[typeFieldName] = it.TypeName 44 } 45 46 return newMap 47 } 48 49 func (it *Result) DeserializedFieldsToMap() ( 50 fieldsMap map[string]interface{}, 51 parsingErr error, 52 ) { 53 if it == nil || len(it.Bytes) == 0 { 54 return map[string]interface{}{}, nil 55 } 56 57 parsingErr = it.Deserialize(fieldsMap) 58 59 return fieldsMap, parsingErr 60 } 61 62 // SafeDeserializedFieldsToMap 63 // 64 // Warning: 65 // - Swallows the error 66 func (it *Result) SafeDeserializedFieldsToMap() ( 67 fieldsMap map[string]interface{}, 68 ) { 69 fieldsMap, _ = it.DeserializedFieldsToMap() 70 71 return fieldsMap 72 } 73 74 func (it *Result) FieldsNames() ( 75 fieldsNames []string, 76 parsingErr error, 77 ) { 78 fieldsMap, parsingErr := it.DeserializedFieldsToMap() 79 80 if len(fieldsMap) == 0 { 81 return []string{}, parsingErr 82 } 83 84 fieldsNames = make([]string, len(fieldsMap)) 85 index := 0 86 87 for fieldNameKey := range fieldsMap { 88 fieldsNames[index] = fieldNameKey 89 90 index++ 91 } 92 93 return fieldsNames, parsingErr 94 } 95 96 // SafeFieldsNames 97 // 98 // Warning: 99 // - Swallows the error 100 func (it *Result) SafeFieldsNames() ( 101 fieldsNames []string, 102 ) { 103 fieldsNames, _ = it.FieldsNames() 104 105 return fieldsNames 106 } 107 108 func (it *Result) BytesTypeName() string { 109 if it == nil { 110 return "" 111 } 112 113 return it.TypeName 114 } 115 116 func (it *Result) SafeBytesTypeName() string { 117 if it.IsEmpty() { 118 return "" 119 } 120 121 return it.TypeName 122 } 123 124 func (it *Result) SafeString() string { 125 return *it.JsonStringPtr() 126 } 127 128 func (it *Result) JsonString() string { 129 return *it.JsonStringPtr() 130 } 131 132 func (it *Result) JsonStringPtr() *string { 133 if it == nil { 134 return constants.EmptyStringPtr 135 } 136 137 if it.jsonString != nil { 138 return it.jsonString 139 } 140 141 if it.jsonString == nil && it.HasBytes() { 142 jsonString := string(it.Bytes) 143 it.jsonString = &jsonString 144 } else if it.jsonString == nil { 145 emptyStr := "" 146 it.jsonString = &emptyStr 147 } 148 149 return it.jsonString 150 } 151 152 func (it *Result) PrettyJsonBuffer(prefix, indent string) (*bytes.Buffer, error) { 153 var prettyJSON bytes.Buffer 154 155 if it.IsEmpty() { 156 return &prettyJSON, nil 157 } 158 159 err := json.Indent( 160 &prettyJSON, 161 it.Bytes, 162 prefix, 163 indent) 164 165 return &prettyJSON, err 166 } 167 168 func (it *Result) PrettyJsonString() string { 169 if it == nil || it.IsEmptyJson() { 170 return "" 171 } 172 173 prettyJSON, err := it.PrettyJsonBuffer( 174 constants.EmptyString, 175 constants.Tab) 176 177 if err != nil { 178 return "" 179 } 180 181 return prettyJSON.String() 182 } 183 184 func (it *Result) PrettyJsonStringOrErrString() string { 185 if it == nil { 186 return "json result: nil cannot have json string" 187 } 188 189 if it.HasError() { 190 return it.MeaningfulError().Error() 191 } 192 193 return it.PrettyJsonString() 194 } 195 196 func (it *Result) Length() int { 197 if it == nil || it.Bytes == nil { 198 return 0 199 } 200 201 return len(it.Bytes) 202 } 203 204 func (it *Result) HasError() bool { 205 return it != nil && it.Error != nil 206 } 207 208 func (it *Result) ErrorString() string { 209 if it.IsEmptyError() { 210 return constants.EmptyString 211 } 212 213 return it.Error.Error() 214 } 215 216 func (it *Result) IsErrorEqual(err error) bool { 217 if it.Error == nil && err == nil { 218 return true 219 } 220 221 if it.Error == nil || err == nil { 222 return false 223 } 224 225 if it.HasError() && it.ErrorString() == err.Error() { 226 return true 227 } 228 229 return false 230 } 231 232 func (it Result) String() string { 233 if it.IsAnyNull() { 234 return constants.EmptyString 235 } 236 237 var currentMap map[string]string 238 239 if it.HasError() { 240 currentMap = map[string]string{ 241 "Json": it.JsonString(), 242 "Type": it.TypeName, 243 "Error": it.MeaningfulErrorMessage(), 244 } 245 } else { 246 currentMap = map[string]string{ 247 "Json": it.JsonString(), 248 "Type": it.TypeName, 249 } 250 } 251 252 toString := fmt.Sprintf( 253 constants.SprintValueFormat, 254 currentMap) 255 256 currentMap = nil 257 258 return toString 259 } 260 261 func (it *Result) SafeNonIssueBytes() []byte { 262 if it.HasIssuesOrEmpty() { 263 return []byte{} 264 } 265 266 return it.Bytes 267 } 268 269 func (it *Result) SafeBytes() []byte { 270 if it.IsAnyNull() { 271 return []byte{} 272 } 273 274 return it.Bytes 275 } 276 277 func (it *Result) Values() []byte { 278 return it.Bytes 279 } 280 281 func (it *Result) SafeValues() []byte { 282 if it.IsAnyNull() { 283 return []byte{} 284 } 285 286 return it.Bytes 287 } 288 289 func (it *Result) SafeValuesPtr() *[]byte { 290 if it.HasIssuesOrEmpty() { 291 return &[]byte{} 292 } 293 294 return &it.Bytes 295 } 296 297 func (it *Result) Raw() ([]byte, error) { 298 if it == nil { 299 return []byte{}, defaulterr.JsonResultNull 300 } 301 302 return it.SafeBytes(), it.MeaningfulError() 303 } 304 305 func (it *Result) RawMust() []byte { 306 allBytes, err := it.Raw() 307 errcore.HandleErr(err) 308 309 return allBytes 310 } 311 312 func (it *Result) RawString() (jsonString string, err error) { 313 return it.JsonString(), it.MeaningfulError() 314 } 315 316 func (it *Result) RawStringMust() (jsonString string) { 317 jsonString, err := it.RawString() 318 319 if err != nil { 320 panic(err) 321 } 322 323 return jsonString 324 } 325 326 func (it *Result) RawErrString() (rawJsonBytes []byte, errorMsg string) { 327 return it.Bytes, it.MeaningfulErrorMessage() 328 } 329 330 func (it *Result) RawPrettyString() (jsonString string, err error) { 331 return it.PrettyJsonString(), it.MeaningfulError() 332 } 333 334 func (it *Result) MeaningfulErrorMessage() string { 335 err := it.MeaningfulError() 336 337 if err == nil { 338 return "" 339 } 340 341 return err.Error() 342 } 343 344 // MeaningfulError 345 // 346 // create error even if results are nil. 347 func (it *Result) MeaningfulError() error { 348 if it == nil { 349 return defaulterr.JsonResultNull 350 } 351 352 if it.Error == nil && len(it.Bytes) > 0 { 353 // everything is okay 354 355 return nil 356 } 357 358 if it.IsEmptyJsonBytes() { 359 // error may or may not exist 360 errMsg := errcore.BytesAreNilOrEmptyType.String() + 361 " Additional: " + 362 errcore.ToString(it.Error) + // error may or may not exist 363 ", type:" 364 365 return errcore. 366 FailedToParseType. 367 Error(errMsg, it.TypeName) 368 } 369 370 // must error and payload may or may not exist 371 return errcore. 372 FailedToParseType. 373 Error( 374 errcore.ToString(it.Error)+", type:"+it.TypeName+", payload:", 375 it.safeJsonStringInternal()) 376 } 377 378 func (it *Result) safeJsonStringInternal() string { 379 if it == nil { 380 return "" 381 } 382 383 var safeJsonString string 384 if it != nil && len(it.Bytes) > 0 { 385 safeJsonString = string(it.Bytes) 386 } 387 388 return safeJsonString 389 } 390 391 func (it *Result) IsEmptyError() bool { 392 return it == nil || it.Error == nil 393 } 394 395 // HasSafeItems 396 // 397 // Returns true if 398 // Result is not null 399 // and has NO error 400 // and has non-Empty json (other than length 0 or "{}") 401 // 402 // Invert of HasIssuesOrEmpty 403 func (it *Result) HasSafeItems() bool { 404 return !it.HasIssuesOrEmpty() 405 } 406 407 // IsAnyNull 408 // 409 // Returns true 410 // if Result is null 411 // or Bytes is null 412 func (it *Result) IsAnyNull() bool { 413 return it == nil || it.Bytes == nil 414 } 415 416 // HasIssuesOrEmpty 417 // 418 // Returns true 419 // if Result is null 420 // or has any error 421 // or has empty json (length 0 or "{}") 422 // 423 // Result.IsAnyNull() || 424 // Result.HasError() || 425 // Result.IsEmptyJsonBytes() 426 func (it *Result) HasIssuesOrEmpty() bool { 427 return it == nil || it.Error != nil || it.IsEmptyJsonBytes() 428 } 429 430 func (it *Result) HandleError() { 431 if it.HasIssuesOrEmpty() { 432 panic(it.MeaningfulError()) 433 } 434 } 435 436 // MustBeSafe alias for HandleError 437 func (it *Result) MustBeSafe() { 438 if it.HasIssuesOrEmpty() { 439 panic(it.MeaningfulError()) 440 } 441 } 442 443 func (it *Result) HandleErrorWithMsg(msg string) { 444 if it.HasIssuesOrEmpty() { 445 panic(msg + constants.DefaultLine + it.MeaningfulErrorMessage()) 446 } 447 } 448 449 // HasBytes 450 // 451 // Invert of Result.IsEmptyJsonBytes() 452 // Represents has at least valid json data other than length 0 or "{}" 453 func (it *Result) HasBytes() bool { 454 return !it.IsEmptyJsonBytes() 455 } 456 457 // HasJsonBytes 458 // 459 // Invert of Result.IsEmptyJsonBytes() 460 // Represents has at least valid json data other than length 0 or "{}" 461 func (it *Result) HasJsonBytes() bool { 462 return !it.IsEmptyJsonBytes() 463 } 464 465 // IsEmptyJsonBytes 466 // 467 // len == 0, nil, "{}" returns as empty true 468 func (it *Result) IsEmptyJsonBytes() bool { 469 if it == nil { 470 return true 471 } 472 473 isEmptyFirst := it.HasError() || 474 it.Bytes == nil 475 476 if isEmptyFirst { 477 return isEmptyFirst 478 } 479 480 length := len(it.Bytes) 481 482 if length == 0 { 483 return true 484 } 485 486 if length == 2 { 487 // empty json 488 return (it.Bytes)[coreindexes.First] == constants.CurlyBraceStartChar && 489 (it.Bytes)[coreindexes.Second] == constants.CurlyBraceEndChar 490 } 491 492 return false 493 } 494 495 func (it *Result) IsEmpty() bool { 496 return it == nil || len(it.Bytes) == 0 497 } 498 499 func (it Result) HasAnyItem() bool { 500 return !it.IsEmpty() 501 } 502 503 func (it *Result) IsEmptyJson() bool { 504 return it.IsEmptyJsonBytes() 505 } 506 507 // HasJson 508 // 509 // Invert of Result.IsEmptyJsonBytes() 510 func (it *Result) HasJson() bool { 511 return !it.IsEmptyJsonBytes() 512 } 513 514 func (it *Result) InjectInto( 515 injector JsonParseSelfInjector, 516 ) error { 517 return injector.JsonParseSelfInject(it) 518 } 519 520 // Deserialize 521 // 522 // Same as Unmarshal, just alias 523 func (it *Result) Deserialize( 524 anyPointer interface{}, 525 ) error { 526 return it.Unmarshal(anyPointer) 527 } 528 529 // DeserializeMust 530 // 531 // Same as UnmarshalMust, just alias 532 func (it *Result) DeserializeMust( 533 anyPointer interface{}, 534 ) { 535 err := it.Unmarshal(anyPointer) 536 537 if err != nil { 538 panic(err) 539 } 540 } 541 542 func (it *Result) UnmarshalMust( 543 anyPointer interface{}, 544 ) { 545 err := it.Unmarshal(anyPointer) 546 547 if err != nil { 548 panic(err) 549 } 550 } 551 552 // Unmarshal 553 // 554 // deserializes current safe bytes to given pointer 555 func (it *Result) Unmarshal( 556 anyPointer interface{}, 557 ) error { 558 if it == nil { 559 return errcore. 560 UnMarshallingFailedType. 561 Error( 562 "cannot unmarshal null json result, to pointer type", 563 reflectinternal.TypeName(anyPointer)) 564 } 565 566 if it.HasError() { 567 compiledMessage := errcore.MessageVarMap( 568 "json unmarshal failed with existing error", 569 map[string]interface{}{ 570 "err": it.Error, 571 "src": it.TypeName, 572 "dst": reflectinternal.TypeName(anyPointer), 573 "payload": it.safeJsonStringInternal(), 574 }) 575 576 return errcore. 577 UnMarshallingFailedType. 578 ErrorNoRefs(compiledMessage) 579 } 580 581 err := json.Unmarshal( 582 it.Bytes, 583 anyPointer) 584 585 if err == nil { 586 return nil 587 } 588 589 // unmarshal caught error 590 compiledMessage := errcore.MessageVarMap( 591 "json unmarshal failed", 592 map[string]interface{}{ 593 "err": it.Error, 594 "src": it.TypeName, 595 "dst": reflectinternal.TypeName(anyPointer), 596 "payload": it.safeJsonStringInternal(), 597 }) 598 599 return errcore. 600 UnMarshallingFailedType. 601 ErrorNoRefs(compiledMessage) 602 } 603 604 // SerializeSkipExistingIssues 605 // 606 // Ignores and returns nil if HasIssuesOrEmpty satisfied 607 func (it *Result) SerializeSkipExistingIssues() ( 608 []byte, error, 609 ) { 610 if it.HasIssuesOrEmpty() { 611 return nil, nil 612 } 613 614 return it.serializeInternal() 615 } 616 617 func (it *Result) serializeInternal() ( 618 []byte, error, 619 ) { 620 rawBytes, err := json.Marshal(it) 621 622 if err == nil { 623 return rawBytes, nil 624 } 625 626 // has error 627 reference := errcore.VarTwoNoType( 628 "marshal or serialize Error", err.Error(), 629 "src", it.TypeName, 630 ) 631 632 return nil, errcore. 633 Serialize. 634 ErrorRefOnly(reference) 635 } 636 637 func (it *Result) Serialize() ([]byte, error) { 638 if it == nil { 639 return nil, errcore. 640 Serialize. 641 ErrorNoRefs("cannot marshal if JsonResult is null") 642 } 643 644 if it.Error != nil { 645 return []byte{}, it.MeaningfulError() 646 } 647 648 return it.serializeInternal() 649 } 650 651 func (it *Result) SerializeMust() []byte { 652 rs, err := it.Serialize() 653 errcore.MustBeEmpty(err) 654 655 return rs 656 } 657 658 // UnmarshalSkipExistingIssues 659 // 660 // Ignores and returns nil if HasIssuesOrEmpty satisfied 661 func (it *Result) UnmarshalSkipExistingIssues( 662 toPointer interface{}, 663 ) error { 664 if it.HasIssuesOrEmpty() { 665 return nil 666 } 667 668 err := json.Unmarshal(it.Bytes, toPointer) 669 670 if err == nil { 671 return nil 672 } 673 674 // unmarshal caught error 675 compiledMessage := errcore.MessageVarMap( 676 "json unmarshal failed", 677 map[string]interface{}{ 678 "err": err, 679 "src": it.TypeName, 680 "dst": reflectinternal.TypeName(toPointer), 681 "payload": it.safeJsonStringInternal(), 682 }) 683 684 return errcore. 685 UnMarshallingFailedType. 686 ErrorNoRefs(compiledMessage) 687 } 688 689 func (it *Result) UnmarshalResult() (*Result, error) { 690 empty := Empty.ResultPtr() 691 err := it.Unmarshal(empty) 692 693 return empty, err 694 } 695 696 //goland:noinspection GoLinterLocal 697 func (it *Result) JsonModel() Result { 698 if it == nil { 699 return Result{ 700 Error: defaulterr.JsonResultNull, 701 } 702 } 703 704 return *it 705 } 706 707 //goland:noinspection GoLinterLocal 708 func (it *Result) JsonModelAny() interface{} { 709 return it.JsonModel() 710 } 711 712 // Json 713 // 714 // creates json result of self 715 func (it Result) Json() Result { 716 return NewResult.Any(it) 717 } 718 719 // JsonPtr 720 // 721 // creates json result of self 722 func (it Result) JsonPtr() *Result { 723 return NewResult.AnyPtr(it) 724 } 725 726 // ParseInjectUsingJson It will not update the self but creates a new one. 727 func (it *Result) ParseInjectUsingJson( 728 jsonResultIn *Result, 729 ) (*Result, error) { 730 err := jsonResultIn.Unmarshal( 731 it) 732 733 if err != nil { 734 return Empty.ResultPtrWithErr(it.TypeName, err), err 735 } 736 737 return it, nil 738 } 739 740 // ParseInjectUsingJsonMust Panic if error 741 func (it *Result) ParseInjectUsingJsonMust( 742 jsonResultIn *Result, 743 ) *Result { 744 result, err := it.ParseInjectUsingJson( 745 jsonResultIn) 746 747 if err != nil { 748 panic(err) 749 } 750 751 return result 752 } 753 754 func (it *Result) CloneError() error { 755 if it.HasError() { 756 return errors.New(it.Error.Error()) 757 } 758 759 return nil 760 } 761 762 func (it Result) Ptr() *Result { 763 return &it 764 } 765 766 func (it *Result) NonPtr() Result { 767 if it == nil { 768 return Result{ 769 Error: errors.New("nil json result"), 770 } 771 } 772 773 return *it 774 } 775 776 func (it Result) ToPtr() *Result { 777 return &it 778 } 779 780 func (it Result) ToNonPtr() Result { 781 return it 782 } 783 784 func (it *Result) IsEqualPtr(another *Result) bool { 785 if it == nil && another == nil { 786 return true 787 } 788 789 if it == nil || another == nil { 790 return false 791 } 792 793 if it == another { 794 return true 795 } 796 797 if it.Length() != another.Length() { 798 return false 799 } 800 801 if !it.IsErrorEqual(another.Error) { 802 return false 803 } 804 805 if it.TypeName != another.TypeName { 806 return false 807 } 808 809 if it.jsonString != nil && another.jsonString != nil && 810 it.jsonString == another.jsonString { 811 return true 812 } 813 814 return bytes.Equal(it.Bytes, another.Bytes) 815 } 816 817 func (it *Result) CombineErrorWithRefString(references ...string) string { 818 if it.IsEmptyError() { 819 return "" 820 } 821 822 csv := csvinternal.StringsToStringDefault(references...) 823 824 return fmt.Sprintf( 825 constants.MessageReferenceWrapFormat, 826 it.Error.Error(), 827 csv) 828 } 829 830 func (it *Result) CombineErrorWithRefError(references ...string) error { 831 if it.IsEmptyError() { 832 return nil 833 } 834 835 errorString := it.CombineErrorWithRefString( 836 references...) 837 838 return errors.New(errorString) 839 } 840 841 func (it Result) IsEqual(another Result) bool { 842 if it.Length() != another.Length() { 843 return false 844 } 845 846 if !it.IsErrorEqual(another.Error) { 847 return false 848 } 849 850 if it.jsonString != nil && another.jsonString != nil && 851 it.jsonString == another.jsonString { 852 return true 853 } 854 855 return bytes.Equal(it.Bytes, another.Bytes) 856 } 857 858 func (it *Result) BytesError() *coredata.BytesError { 859 if it == nil { 860 return nil 861 } 862 863 return &coredata.BytesError{ 864 Bytes: it.Bytes, 865 Error: it.Error, 866 } 867 } 868 869 func (it *Result) Dispose() { 870 if it == nil { 871 return 872 } 873 874 it.Error = nil 875 it.Bytes = nil 876 it.TypeName = constants.EmptyString 877 it.jsonString = nil 878 } 879 880 func (it Result) CloneIf(isClone, isDeepClone bool) Result { 881 if isClone { 882 return it.Clone(isDeepClone) 883 } 884 885 return it 886 } 887 888 func (it *Result) ClonePtr(isDeepClone bool) *Result { 889 if it == nil { 890 return nil 891 } 892 893 cloned := it.Clone(isDeepClone) 894 895 return &cloned 896 } 897 898 func (it Result) Clone(isDeepClone bool) Result { 899 if it.Length() == 0 { 900 return NewResult.Create( 901 []byte{}, 902 it.CloneError(), 903 it.TypeName) 904 } 905 906 if !isDeepClone || it.Length() == 0 { 907 return NewResult.Create( 908 it.Bytes, 909 it.CloneError(), 910 it.TypeName) 911 } 912 913 newBytes := make([]byte, it.Length()) 914 copy(newBytes, it.Bytes) 915 916 return NewResult.Create( 917 newBytes, 918 it.CloneError(), 919 it.TypeName) 920 } 921 922 func (it Result) AsJsonContractsBinder() JsonContractsBinder { 923 return &it 924 } 925 926 func (it Result) AsJsoner() Jsoner { 927 return &it 928 } 929 930 func (it Result) JsonParseSelfInject( 931 jsonResultIn *Result, 932 ) error { 933 _, err := it.ParseInjectUsingJson(jsonResultIn) 934 935 return err 936 } 937 938 func (it Result) AsJsonParseSelfInjector() JsonParseSelfInjector { 939 return &it 940 }