application.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package model
  2. import (
  3. "fmt"
  4. "sparrow/pkg/models"
  5. "github.com/jinzhu/gorm"
  6. )
  7. // Application 应用
  8. type Application struct {
  9. db *gorm.DB
  10. }
  11. // Init 初始化
  12. func (a *Application) Init(db *gorm.DB) *Application {
  13. a.db = db
  14. return a
  15. }
  16. // Create 创建
  17. func (a *Application) Create(app *models.Application) error {
  18. cache := getCache()
  19. key := fmt.Sprintf("Application:%s", app.AppKey)
  20. cache.Set(key, app)
  21. return a.db.Save(app).Error
  22. }
  23. //Delete 删除
  24. func (a *Application) Delete(app *models.Application) error {
  25. cache := getCache()
  26. key := fmt.Sprintf("Application:%s", app.AppKey)
  27. if _, ok := cache.Get(key); ok {
  28. cache.Delete(key)
  29. }
  30. return a.db.Delete(app).Error
  31. }
  32. // GetAppCount 查询一个厂商的Application数量
  33. func (a *Application) GetAppCount(vendorid string) (int, error) {
  34. var count int
  35. err := a.db.Model(&models.Application{}).Where("vendor_id = ?", vendorid).Count(&count).Error
  36. if err != nil {
  37. return 0, err
  38. }
  39. return count, nil
  40. }
  41. // GetVendorApps 获取厂商的app列表
  42. func (a *Application) GetVendorApps(vendorid string, pi, ps int, name string) (datas []models.Application, count int, err error) {
  43. tx := a.db.Where("vendor_id = ? and 1=1", vendorid)
  44. if name != "" {
  45. tx = tx.Where("app_name = ?", name)
  46. }
  47. err = tx.Limit(ps).Offset((pi - 1) * ps).Find(&datas).Error
  48. tx.Model(&models.Application{}).Count(&count)
  49. return
  50. }
  51. // GetAppInfo 查询app信息
  52. func (a *Application) GetAppInfo(vendorid string, appkey string) (data models.Application, err error) {
  53. cache := getCache()
  54. key := fmt.Sprintf("Application:%s", appkey)
  55. if v, ok := cache.Get(key); ok {
  56. _d := v.(*models.Application)
  57. data = *_d
  58. } else {
  59. err = a.db.Where("vendor_id = ? and app_key = ?", vendorid, appkey).First(&data).Error
  60. if err == nil {
  61. cache.Set(key, &data)
  62. }
  63. }
  64. return
  65. }
  66. // Update 更新
  67. func (a *Application) Update(app *models.Application) (data models.Application, err error) {
  68. cache := getCache()
  69. key := fmt.Sprintf("Application:%s", app.AppKey)
  70. if _, ok := cache.Get(key); ok {
  71. cache.Delete(key)
  72. }
  73. cache.Set(key, app)
  74. err = a.db.Model(&data).Save(app).Error
  75. return
  76. }