nosql.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package nosql
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "github.com/jackc/pgx/v5"
  7. )
  8. // OpenTXMethod is callback functon to open transaction in NoSQL object
  9. type OpenTXMethod func(context.Context) (pgx.Tx, error)
  10. // NoSQL object
  11. type NoSQL struct {
  12. openMethod OpenTXMethod
  13. }
  14. // New is NoSQL object constructor
  15. func New(openMethod OpenTXMethod) *NoSQL {
  16. return &NoSQL{openMethod}
  17. }
  18. // CallJSON accepts raw json bytes and returns result raw json bytes
  19. func (_self *NoSQL) CallJSON(ctx context.Context, function string, rawJSON []byte) (resRawJSON []byte, err error) {
  20. // open tx
  21. var tx pgx.Tx
  22. if tx, err = _self.openMethod(ctx); err == nil {
  23. // execute query and scan result
  24. row := tx.QueryRow(context.Background(), fmt.Sprintf("select * from %v($1)", function), rawJSON)
  25. if err = row.Scan(&resRawJSON); err != nil {
  26. tx.Rollback(context.Background())
  27. return
  28. }
  29. err = tx.Commit(context.Background())
  30. }
  31. return
  32. }
  33. // CallObjParam accepts interface{} object and returns result raw json bytes
  34. func (_self *NoSQL) CallObjParam(ctx context.Context, function string, data interface{}) (resRawJSON []byte, err error) {
  35. // convert incoming object to raw json
  36. var raw []byte
  37. if raw, err = json.Marshal(data); err != nil {
  38. return
  39. }
  40. return _self.CallJSON(ctx, function, raw)
  41. }
  42. // Call accepts interface{} object and returns result interface{}
  43. func (_self *NoSQL) Call(ctx context.Context, function string, data interface{}) (res interface{}, err error) {
  44. var resRawJSON []byte
  45. if resRawJSON, err = _self.CallObjParam(ctx, function, data); err == nil {
  46. // convert raw result data to obj
  47. if len(resRawJSON) > 0 {
  48. err = json.Unmarshal(resRawJSON, &res)
  49. }
  50. }
  51. return
  52. }
  53. func (_self *NoSQL) CallObject(ctx context.Context, function string, data interface{}, resultObject interface{}) (err error) {
  54. var resRawJSON []byte
  55. if resRawJSON, err = _self.CallObjParam(ctx, function, data); err == nil {
  56. // convert raw result data to result object
  57. err = json.Unmarshal(resRawJSON, resultObject)
  58. }
  59. return
  60. }