utils.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854
  1. package api
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "net/url"
  6. "regexp"
  7. "strconv"
  8. "strings"
  9. "time"
  10. "git.eugeniocarvalho.dev/eugeniucarvalho/apicodegen/api/errs"
  11. "github.com/davecgh/go-spew/spew"
  12. "github.com/eugeniucarvalho/validator"
  13. "github.com/kataras/iris/v12/context"
  14. "go.mongodb.org/mongo-driver/bson"
  15. "go.mongodb.org/mongo-driver/bson/primitive"
  16. "go.mongodb.org/mongo-driver/mongo"
  17. )
  18. var (
  19. AcceptJson = regexp.MustCompile("^application/json")
  20. Environment = map[string]interface{}{}
  21. ToReference = references{}
  22. )
  23. type references struct {
  24. }
  25. func (this *references) True() *bool {
  26. value := true
  27. return &value
  28. }
  29. func (this *references) False() *bool {
  30. value := false
  31. return &value
  32. }
  33. func (this *references) String(value string) *string {
  34. return &value
  35. }
  36. func (this *references) Bool(value bool) *bool {
  37. return &value
  38. }
  39. type ModeInterface interface {
  40. Mode() string
  41. }
  42. type PatchHistoryRegister struct {
  43. Id primitive.ObjectID `bson:"_id" json:"-"`
  44. CreatedAt int64 `bson:"createdAt" json:"-"`
  45. CreatedBy string `bson:"createdBy" json:"-"`
  46. Parent string `bson:"parent" json:"-"`
  47. ApiTags []string `bson:"apiTags" json:"-"`
  48. }
  49. type EntityModel struct {
  50. Mode string `bson:"-" json:"-"`
  51. ApplicationVersion *string `bson:"appVersion,omitempty" json:"-"`
  52. Deleted *bool `bson:"deleted,omitempty" json:"-"`
  53. DeletedIn *int64 `bson:"deletedIn,omitempty" json:"-"`
  54. }
  55. // type DotNotation struct {
  56. // Rules map[string]interface{} `bson:",inline" json:"-"`
  57. // }
  58. // func (model *DotNotation) DotNotation() map[string]interface{} {
  59. // if model.Rules == nil {
  60. // model.Rules = map[string]interface{}{}
  61. // }
  62. // return model.Rules
  63. // }
  64. func UserIDString(ctx context.Context) (id string, err *errs.Error) {
  65. if user, ok := ctx.Values().Get("$user.ref").(map[string]interface{}); ok {
  66. id = user["id"].(primitive.ObjectID).Hex()
  67. return
  68. }
  69. err = errs.Internal().Details(&errs.Detail{
  70. Message: "Invalid user instance",
  71. })
  72. return
  73. }
  74. func (model *EntityModel) SetMode(mode string) {
  75. model.Mode = mode
  76. switch mode {
  77. case "create":
  78. model.ApplicationVersion = &BuildVersion
  79. deleted := false
  80. model.Deleted = &deleted
  81. case "update":
  82. if model.Deleted == nil {
  83. deleted := false
  84. model.Deleted = &deleted
  85. }
  86. case "patch":
  87. // if model.Deleted == nil {
  88. // deleted := false
  89. // model.Deleted = &deleted
  90. // }
  91. // case "delete":
  92. // case "undelete":
  93. }
  94. }
  95. func GetIDString(input interface{}) (string, *errs.Error) {
  96. if value, converted := input.(string); converted {
  97. return value, nil
  98. }
  99. if value, converted := input.(*primitive.ObjectID); converted {
  100. return value.Hex(), nil
  101. }
  102. if value, converted := input.(primitive.ObjectID); converted {
  103. return value.Hex(), nil
  104. }
  105. return "", errs.Internal().Details(&errs.Detail{
  106. Reason: fmt.Sprintf("Can't convert ID into string. Invalid type '%T", input),
  107. })
  108. }
  109. func NowUnix() int64 {
  110. return time.Now().Unix()
  111. }
  112. func GetUser(ctx context.Context) interface{} {
  113. return ctx.Values().Get("$user.ref")
  114. }
  115. func (model *EntityModel) SetDeleted(deleted bool) {
  116. var deletedIn = int64(0)
  117. model.Deleted = &deleted
  118. if *model.Deleted {
  119. deletedIn = time.Now().Unix()
  120. }
  121. model.DeletedIn = &deletedIn
  122. }
  123. type CorsOptions struct {
  124. ExposeHeaders []string
  125. AllowHeaders []string
  126. AllowMethods []string
  127. AllowOrigin []string
  128. }
  129. type GetManyResponse struct {
  130. ResultSizeEstimate int `json:"resultSizeEstimate"` // Estimativa do numero total de itens.
  131. NextPageToken string `json:"nextPageToken"` // Referência para a proxima pagina de resultados.
  132. Itens interface{} `json:"itens"` // Lista contento os elementos da resposta.
  133. }
  134. var (
  135. // ParamsFlag map[string]*ParamFlag
  136. CorsDefaultOptions = CorsOptions{
  137. AllowOrigin: []string{"*"},
  138. // AllowOrigin: []string{"http://localhost:4200"},
  139. AllowMethods: []string{"OPTIONS", "GET", "POST", "PUT", "DELETE", "PATCH"},
  140. AllowHeaders: []string{"Authorization", "Content-Type", "Origin", "Host", "x-api-build"},
  141. ExposeHeaders: []string{"X-total-count"},
  142. }
  143. BuildVersion = "0"
  144. ApiVersion = "0"
  145. // Armazena os mimes dos arquivos consultados
  146. // MimeCache = xmap.NewMS2S()
  147. replaceEmpty = regexp.MustCompile(`\s+`)
  148. // pageTokenRegex = regexp.MustCompile(`(?P<ids>\w+):(?P<idc>\w+):(?P<page>\d{1,6})`)
  149. pageTokenRegex = regexp.MustCompile(`(?P<idc>[\w-]+):(?P<count>\d+)`)
  150. replaceIndex = regexp.MustCompile(`\.\d+\.`)
  151. )
  152. func init() {
  153. // fmt.Println("Register validation functions")
  154. // err := Validator.RegisterValidation("req", func(f validator.FieldLevel) bool {
  155. // fmt.Println("Running req validation")
  156. // spew.Dump(f)
  157. // return true
  158. // })
  159. validator.RegisterValidator("requiredOnCreate", func(i interface{}, o interface{}, v *validator.ValidatorOption) error {
  160. if schema, ok := o.(ModeInterface); ok {
  161. fmt.Println("requiredOnCreate ->", schema.Mode())
  162. switch schema.Mode() {
  163. case "create":
  164. if i == nil {
  165. return fmt.Errorf("")
  166. }
  167. case "update":
  168. }
  169. }
  170. return nil
  171. })
  172. // Validator.RegisterValidation("req",
  173. // func(fl validator.FieldLevel) bool {
  174. // // func(v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value, field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string) bool {
  175. // // func(v *validator.Validate, param string) bool {
  176. // // return passwordRegex.MatchString(field.String())
  177. // })
  178. // if err != nil {
  179. // panic(err)
  180. // }
  181. }
  182. func Panic() {
  183. if err := recover(); err != nil {
  184. LogError(0, err.(error).Error())
  185. }
  186. }
  187. func Validate(i interface{}) *errs.Error {
  188. // if err := Validator.Struct(i); err != nil {
  189. // fmt.Println("VALIDATE", result, err)
  190. // spew.Dump(i)
  191. if errors, valid := validator.Struct(i); !valid {
  192. err := errs.InvalidArgument()
  193. // er := Error(ERR_INVALID_PARAM, "Invalid params")
  194. for _, e := range errors {
  195. err.Details(&errs.Detail{
  196. Dominio: "global",
  197. Reason: "invalidParameter",
  198. Message: e.Message,
  199. // Message: fmt.Sprintf("%+v", e.Message),
  200. // LocationType:,
  201. // Location :,
  202. })
  203. }
  204. // if _, ok := err.(*validator.InvalidValidationError); ok {
  205. // fmt.Println("INvalid")
  206. // er.LastDescription().Message = err.Error()
  207. // } else {
  208. // for _, err := range err.(validator.ValidationErrors) {
  209. // switch err.Tag() {
  210. // case "required":
  211. // }
  212. // er.Add(&ErrDescription{
  213. // Dominio: "global",
  214. // Reason: "invalidParameter",
  215. // Message: fmt.Sprintf("%+v", err),
  216. // // LocationType:,
  217. // // Location :,
  218. // })
  219. // // fmt.Println("1", err.Namespace())
  220. // // fmt.Println("2", err.Field())
  221. // // fmt.Println("3", err.StructNamespace()) // can differ when a custom TagNameFunc is registered or
  222. // // fmt.Println("4", err.StructField()) // by passing alt name to ReportError like below
  223. // // fmt.Println("5", err.Tag())
  224. // // fmt.Println("6", err.ActualTag())
  225. // // fmt.Println("7", err.Kind())
  226. // // fmt.Println("8", err.Type())
  227. // // fmt.Println("9", err.Value())
  228. // // fmt.Println("10", err.Param())
  229. // // fmt.Println("-------------")
  230. // }
  231. // }
  232. return err
  233. // from here you can create your own error messages in whatever language you wish
  234. }
  235. return nil
  236. }
  237. // ApiResponse é a estrutura padrão de respostas
  238. // Apenas os campos preenchidos serão retornados
  239. type ApiResponse struct {
  240. Entity interface{} `json:"entity,omitempty"`
  241. List interface{} `json:"list,omitempty"`
  242. NextPageToken string `json:"nextPageToken,omitempty"`
  243. ResultSizeEstimate int `json:"resultSizeEstimate,omitempty"`
  244. }
  245. // func ErroCtxHandler(ctx context.Context, err *errs.Error) {
  246. // if accept := ctx.GetHeader("Accept"); AcceptJson.Match([]byte(accept)) {
  247. // ctx.JSON(err)
  248. // } else {
  249. // ctx.ViewData("", err)
  250. // }
  251. // }
  252. func finalizeRequest(ctx context.Context, resp interface{}, err *errs.Error) {
  253. var (
  254. status = 200
  255. accept = ctx.Request().Header.Get("accept")
  256. types = strings.Split(accept, ",")
  257. )
  258. defer func() {
  259. ctx.StopExecution()
  260. if err != nil {
  261. ctx.Application().Logger().Error(err.Error())
  262. if description := err.LastDescription(); description != nil {
  263. err.Stack.Print()
  264. // ctx.Application().Logger().Error(fmt.Printf("%s\n%s\n", description.Reason, description.Message))
  265. }
  266. // ctx.Application().Logger().Error()
  267. spew.Dump(err)
  268. }
  269. fmt.Println("defer of finalizeRequest")
  270. if r := recover(); r != nil {
  271. fmt.Println("Recovered in f", r)
  272. }
  273. fmt.Println(string(ctx.Values().Serialize()))
  274. }()
  275. if err != nil {
  276. status = err.HttpStatus
  277. // fmt.Println(status, err.Message, "------------------------------------------\n")
  278. // spew.Dump(err)
  279. // debbug
  280. // err.Stack.Print()
  281. resp = err
  282. abortTransaction(ctx)
  283. // fmt.Println("------------------------------------------\n", status)
  284. // spew.Dump(err)
  285. // fmt.Println("------------------------------------------\n", status)
  286. }
  287. ctx.Values().Set("res", resp)
  288. ctx.Header("x-api-build", BuildVersion)
  289. // fmt.Println("error")
  290. // spew.Dump(resp)
  291. // spew.Dump(types)
  292. // spew.Dump(ctx.Request().Header)
  293. ctx.StatusCode(status)
  294. for _, mime := range types {
  295. switch mime {
  296. case "application/json":
  297. ctx.JSON(resp)
  298. return
  299. }
  300. }
  301. // default response case
  302. ctx.WriteString("")
  303. }
  304. // Call encapsula e trata os erros para cada requisição.
  305. func CallAction(id string, fn func(context.Context) (interface{}, *errs.Error)) func(context.Context) {
  306. return func(ctx context.Context) {
  307. var (
  308. err *errs.Error
  309. resp interface{}
  310. finalize = true
  311. )
  312. defer func() {
  313. if !ctx.IsStopped() {
  314. if _err := recover(); _err != nil {
  315. err = errs.Internal().Details(&errs.Detail{
  316. Message: "",
  317. Location: fmt.Sprintf("call.action.%s", id),
  318. LocationType: "application.pipe.resource.stage",
  319. Reason: _err.(error).Error(),
  320. })
  321. }
  322. if finalize {
  323. finalizeRequest(ctx, resp, err)
  324. }
  325. }
  326. }()
  327. fmt.Println("apply -> ", id)
  328. if resp, err = fn(ctx); err != nil {
  329. return
  330. }
  331. if !ctx.IsStopped() {
  332. if resp != nil {
  333. err = commitTransaction(ctx)
  334. } else {
  335. ctx.Next()
  336. finalize = false
  337. }
  338. }
  339. return
  340. }
  341. }
  342. func abortTransaction(ctx context.Context) (err *errs.Error) {
  343. return transactionHandler(ctx, "abort")
  344. }
  345. func commitTransaction(ctx context.Context) (err *errs.Error) {
  346. return transactionHandler(ctx, "commit")
  347. }
  348. func transactionHandler(ctx context.Context, action string) (err *errs.Error) {
  349. var (
  350. localErr error
  351. operation func() error
  352. )
  353. contextSession := GetSessionContext(ctx)
  354. if contextSession == nil {
  355. return
  356. }
  357. switch action {
  358. case "abort":
  359. operation = func() error { return contextSession.AbortTransaction(contextSession) }
  360. case "commit":
  361. operation = func() error { return contextSession.CommitTransaction(contextSession) }
  362. }
  363. try := 4
  364. for {
  365. if localErr = operation(); localErr == nil {
  366. fmt.Println(action, "executed ")
  367. return
  368. }
  369. if try == 0 {
  370. return
  371. }
  372. try--
  373. fmt.Println(action, "transaction error loop ")
  374. // time.Sleep(4 * time.Second)
  375. // retry operation when command contains TransientTransactionError
  376. // if cmdErr, ok := localErr.(mongo.CommandError); ok && cmdErr.HasErrorLabel("TransientTransactionError") {
  377. if cmdErr, ok := localErr.(mongo.CommandError); ok {
  378. fmt.Println(action, cmdErr)
  379. if cmdErr.HasErrorLabel("TransientTransactionError") {
  380. continue
  381. }
  382. }
  383. }
  384. if localErr != nil {
  385. err = errs.Internal().Details(&errs.Detail{
  386. Message: localErr.Error(),
  387. })
  388. }
  389. return
  390. }
  391. func ReadJson(ctx context.Context, entity interface{}) (err *errs.Error) {
  392. if err := ctx.ReadJSON(entity); err != nil {
  393. err = errs.DataCaps().Details(&errs.Detail{
  394. Message: err.Error(),
  395. })
  396. }
  397. return
  398. }
  399. func MgoSortBson(fields []string) *bson.M {
  400. order := bson.M{}
  401. for _, field := range fields {
  402. n := 1
  403. if field != "" {
  404. fmt.Printf("sort '%c'\n", field[0])
  405. switch field[0] {
  406. case '+':
  407. field = field[1:]
  408. case '-':
  409. n = -1
  410. field = field[1:]
  411. default:
  412. panic(fmt.Sprintf("Invalid sort field %s.", field))
  413. }
  414. }
  415. if field == "" {
  416. panic("Sort: empty field name")
  417. }
  418. field = string(replaceIndex.ReplaceAll([]byte(field), []byte(".")))
  419. order[field] = n
  420. }
  421. return &order
  422. }
  423. func MgoSort(ctx context.Context, field string) []string {
  424. result := []string{}
  425. if fields := Q(ctx, field, ""); fields != "" {
  426. sort := string(replaceEmpty.ReplaceAll([]byte(fields), []byte("")))
  427. result = strings.Split(sort, ",")
  428. }
  429. // return nil
  430. return result
  431. }
  432. func MgoFieldsCtx(ctx context.Context, field string) *bson.M {
  433. return MgoFields(Q(ctx, field, ""))
  434. }
  435. func MgoFields(fields string) (projection *bson.M) {
  436. // fmt.Printf("MgoFields '%s'\n", fields)
  437. if fields != "" {
  438. projection = &bson.M{}
  439. for _, v := range strings.Split(fields, ",") {
  440. (*projection)[v] = 1
  441. }
  442. // spew.Dump(projection)
  443. }
  444. return
  445. }
  446. func MgoQuery(ctx context.Context, field string) (*bson.M, *errs.Error) {
  447. return MgoQueryString(ctx, Q(ctx, field, ""))
  448. }
  449. func MgoQueryString(ctx context.Context, query string) (*bson.M, *errs.Error) {
  450. var (
  451. selector = make(bson.M)
  452. // id = "_id"
  453. err error
  454. )
  455. // Unmarshal json query if any
  456. if query != "" {
  457. if err = bson.UnmarshalExtJSON([]byte(query), true, &selector); err != nil {
  458. // return nil, Error(ERR_GENERAL, err.Error())
  459. return nil, errs.Internal().Details(&errs.Detail{
  460. Message: err.Error(),
  461. })
  462. }
  463. if query, err = url.QueryUnescape(query); err != nil {
  464. return nil, errs.Internal().Details(&errs.Detail{
  465. Message: err.Error(),
  466. })
  467. // return nil, Error(ERR_GENERAL, err.Error())
  468. }
  469. if err = json.Unmarshal([]byte(query), &selector); err != nil {
  470. // return nil, Error(ERR_GENERAL, err.Error())
  471. return nil, errs.Internal().Details(&errs.Detail{
  472. Message: err.Error(),
  473. })
  474. }
  475. // if selector, err = mejson.Unmarshal(selector); err != nil {
  476. // return nil, Error(ERR_GENERAL, err.Error())
  477. // }
  478. }
  479. // Transform string HexId to ObjectIdHex
  480. // if selid, _ := selector[id].(string); selid != "" {
  481. // if bson.IsObjectIdHex(selid) {
  482. // selector[id] = bson.ObjectIdHex(selid)
  483. // }
  484. // // else {
  485. // // selector[id] = selid
  486. // // }
  487. // }
  488. return &selector, nil
  489. }
  490. func DefaultCorsHandler() func(ctx context.Context) {
  491. return Cors(CorsDefaultOptions)
  492. }
  493. func Cors(opt CorsOptions) func(ctx context.Context) {
  494. return func(ctx context.Context) {
  495. ctx.Header("Access-Control-Allow-Credentials", "true")
  496. if len(opt.AllowOrigin) > 0 {
  497. // ctx.Header("Access-Control-Allow-Origin", strings.Join(opt.AllowOrigin, ","))
  498. // ctx.Header("Access-Control-Allow-Origin", "*")
  499. // ctx.Header("Origin", "*")
  500. ctx.Header("Access-Control-Allow-Origin", ctx.GetHeader("Origin"))
  501. }
  502. if len(opt.AllowMethods) > 0 {
  503. ctx.Header("Access-Control-Allow-Methods", strings.Join(opt.AllowMethods, ","))
  504. }
  505. if len(opt.AllowHeaders) > 0 {
  506. ctx.Header("Access-Control-Allow-Headers", strings.Join(opt.AllowHeaders, ","))
  507. }
  508. if len(opt.ExposeHeaders) > 0 {
  509. ctx.Header("Access-Control-Expose-Headers", strings.Join(opt.ExposeHeaders, ","))
  510. }
  511. ctx.Next()
  512. }
  513. }
  514. // Retorna um valor de um parametro no path da url.
  515. func P(ctx context.Context, name string, def string) string {
  516. val := ctx.Params().Get(name)
  517. if val == "" {
  518. val = def
  519. }
  520. return val
  521. }
  522. //Retorna um valor de um parametro da query. Ex: ?x=1
  523. func Q(ctx context.Context, name string, def string) string {
  524. val := ctx.URLParam(name)
  525. if val == "" {
  526. val = def
  527. }
  528. return val
  529. }
  530. //Retorna um valor de um parametro da query
  531. func QInt(ctx context.Context, name string, def int) int {
  532. val, e := strconv.Atoi(Q(ctx, name, ""))
  533. if e != nil {
  534. val = def
  535. }
  536. return val
  537. }
  538. // Retorna um valor de um parametro do post.
  539. func F(ctx context.Context, name string, def interface{}) interface{} {
  540. var val interface{}
  541. val = ctx.FormValue(name)
  542. if val == "" {
  543. val = def
  544. }
  545. return val
  546. }
  547. func LogError(code int, m string) {
  548. log("31", fmt.Sprintf("[ERROR| %d] %s", code, m))
  549. }
  550. func LogInfo(code int, m string) {
  551. log("34", fmt.Sprintf("[INFO| %d] %s", code, m))
  552. }
  553. func LogWarning(code int, m string) {
  554. log("35", fmt.Sprintf("[WARNING| %d] %s", code, m))
  555. }
  556. func log(color string, m string) {
  557. fmt.Printf("\x1b[%s;1m%s\x1b[0m\n", color, m)
  558. }
  559. // func ParseRequestTest(ctx context.Context) {
  560. // var (
  561. // err error
  562. // filter = &Filter{
  563. // MaxResults: QInt(ctx, "maxResults", 10),
  564. // }
  565. // oid primitive.ObjectID
  566. // )
  567. // // parse parameter of path
  568. // id := P(ctx, "userId", "")
  569. // if oid, err = primitive.ObjectIDFromHex(id); err != nil {
  570. // filter.UserId = oid
  571. // }
  572. // id = P(ctx, "id", "")
  573. // if oid, err = primitive.ObjectIDFromHex(id); err != nil {
  574. // filter.Id = oid
  575. // }
  576. // // filter.PageToken.Parse(Q(ctx, "nextPageToken", ""))
  577. // if filter.Query, err = MgoQuery(ctx, "q"); err != nil {
  578. // goto Error
  579. // }
  580. // filter.Format = Q(ctx, "format", "full")
  581. // filter.Sort = MgoSortBson(MgoSort(ctx, "sort"))
  582. // filter.Fields = MgoFieldsCtx(ctx, "fields")
  583. // Error:
  584. // if err != nil {
  585. // ErroCtxHandler(
  586. // ctx,
  587. // // Error(ERR_INVALID_PARAM, err.Error()),
  588. // errs.Internal().Details(&errs.Detail{
  589. // Message: err.Error(),
  590. // }),
  591. // )
  592. // return
  593. // }
  594. // ctx.Values().Set("$filter", filter)
  595. // ctx.Next()
  596. // }
  597. // func MapError(erro *errs.Error) *errs.Error {
  598. // if strings.Contains(erro.Message, "E11000") {
  599. // return errs.AlreadyExists().Details(&errs.Detail{
  600. // Message: "DUPLICATED_ITEM",
  601. // })
  602. // } else if strings.Contains(erro.Message, "no documents in result") {
  603. // return errs.Internal().Details(&errs.Detail{
  604. // Message: "NOT_FOUND",
  605. // })
  606. // }
  607. // return erro
  608. // }
  609. // type PageToken struct {
  610. // // StartID string
  611. // // CurrentID string
  612. // Cursor string
  613. // NewCursor string
  614. // Page int
  615. // Count int
  616. // }
  617. // // Encode cria um novo token formatado
  618. // func (p *PageToken) Encode() string {
  619. // out := ""
  620. // if p.NewCursor != "" {
  621. // out = base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf("%s:%d", p.NewCursor, p.Count)))
  622. // }
  623. // return out
  624. // // return string([]byte(fmt.Sprintf("%s:%d", p.NewCursor, p.Count)))
  625. // }
  626. // // HasToken determina se a requisição apresenta um token de paginacao
  627. // func (p *PageToken) HasToken() bool {
  628. // return p.Cursor != ""
  629. // }
  630. // // func (p *PageToken) GetBsonID() bson.ObjectId {
  631. // // if !bson.IsObjectIdHex(p.ID) {
  632. // // return nil
  633. // // }
  634. // // return bson.ObjectIdHex(p.ID)
  635. // // }
  636. // func (p *PageToken) Parse(s string) error {
  637. // var (
  638. // decoded []byte
  639. // err error
  640. // )
  641. // if decoded, err = base64.StdEncoding.DecodeString(s); err != nil {
  642. // return err
  643. // }
  644. // match := pageTokenRegex.FindStringSubmatch(string(decoded))
  645. // if len(match) != 3 {
  646. // return fmt.Errorf("Invalid Page Token")
  647. // }
  648. // p.Cursor = match[1]
  649. // // p.Page, err = strconv.Atoi(match[2])
  650. // p.Count, err = strconv.Atoi(match[2])
  651. // return err
  652. // }
  653. // Layout aplica o path do layout
  654. // func Layout(ctx context.Context) {
  655. // ctx.ViewLayout(ViewScript(ctx, "layout/layout.html"))
  656. // ctx.Next()
  657. // }
  658. // // ViewScript devolve o path do arquivo de script a ser renderizaco
  659. // func ViewScript(ctx context.Context, filename string) string {
  660. // var (
  661. // base string
  662. // ok bool
  663. // )
  664. // domain := strings.Split(ctx.Request().Host, ":")[0]
  665. // if base, ok = TemplateDomainMap[domain]; !ok {
  666. // base = "default"
  667. // }
  668. // return base + "/" + filename
  669. // }
  670. // defer func() {
  671. // var (
  672. // erro *errs.Error
  673. // // ok bool
  674. // err error
  675. // )
  676. // if err = recover(); err != nil {
  677. // if erro, ok = err.(*errs.Error); !ok {
  678. // erro = Error(ERR_GENERAL, err.Error())
  679. // }
  680. // ErroCtxHandler(ctx, erro)
  681. // }
  682. // // ctx.Header("Accept", "application/json")
  683. // // spew.Dump(err)
  684. // }()
  685. // func CallAction(f func(context.Context, *ApiResponse) *errs.Error) func(ctx context.Context) {
  686. // return func(ctx context.Context) {
  687. // var (
  688. // err *errs.Error
  689. // response = &ApiResponse{}
  690. // )
  691. // if err = f(ctx, response); err != nil {
  692. // ErroCtxHandler(ctx, err)
  693. // return
  694. // }
  695. // ctx.JSON(response)
  696. // }
  697. // }
  698. // Verifica se existe alguma pagina para ser carragada.
  699. // func UpdateCursorResponse(models *Mongo, f *Filter, resp interface{}) bool {
  700. // count := f.PageToken.Count
  701. // // Se não foi encontrado nenhum registro
  702. // if count > 0 {
  703. // resp.ResultSizeEstimate = count
  704. // resp.NextPageToken = f.PageToken.Encode()
  705. // return true
  706. // }
  707. // return false
  708. // }