kobe6258 4 ヶ月 前
コミット
718fbd62c5

+ 67 - 4
common/component/es/es.go

@@ -4,6 +4,7 @@ import (
 	"bytes"
 	"context"
 	"encoding/json"
+	"errors"
 	"eta/eta_mini_ht_api/common/component/config"
 	logger "eta/eta_mini_ht_api/common/component/log"
 	"eta/eta_mini_ht_api/common/contants"
@@ -152,6 +153,16 @@ type Hit struct {
 	Highlight json.RawMessage `json:"highlight"`
 }
 
+type Doc struct {
+	Index       string          `json:"_index"`
+	Type        string          `json:"_type"`
+	ID          string          `json:"_id"`
+	Version     float64         `json:"_version"`
+	SeqNo       float64         `json:"_seq_no"`
+	PrimaryTerm float64         `json:"_primary_term"`
+	Found       bool            `json:"found"`
+	Source      json.RawMessage `json:"_source"`
+}
 type ShardsInfo struct {
 	Total      int `json:"total"`
 	Successful int `json:"successful"`
@@ -695,25 +706,27 @@ func (es *ESClient) Exist(indexName string, docId int) (exist bool, err error) {
 	res, err := getRequest.Do(context.Background(), es.es())
 	if err != nil {
 		logger.Error("es获取文档是否存在失败: %v", err)
+		return
 	}
 	defer res.Body.Close()
-
 	// 检查文档是否存在
 	if res.IsError() {
 		// 如果文档不存在,通常返回 404 Not Found
 		if res.StatusCode == 404 {
 			logger.Info("文档不存在.")
-			return false, nil
+			err = errors.New("ES文档不存在")
+			return
 		} else {
 			// 其他错误
 			var e map[string]interface{}
 			if err = json.NewDecoder(res.Body).Decode(&e); err != nil {
 				logger.Error("解析es应答失败: %v", err)
-				return false, err
+				return
 			} else {
 				// Print the response status and error information.
 				logger.Error("[%s] %s: %s\n", res.Status(), e["error"].(map[string]interface{})["type"], e["error"].(map[string]interface{})["原因"])
-				return false, nil
+				err = errors.New("获取ES记录失败")
+				return
 			}
 		}
 	} else {
@@ -723,6 +736,56 @@ func (es *ESClient) Exist(indexName string, docId int) (exist bool, err error) {
 	}
 }
 
+func (es *ESClient) Get(indexName string, docId int) (doc Doc, err error) {
+
+	getRequest := esapi.GetRequest{
+		Index:      indexName,
+		DocumentID: strconv.Itoa(docId),
+	}
+	// 执行请求
+	res, err := getRequest.Do(context.Background(), es.es())
+	if err != nil {
+		logger.Error("es获取文档是否存在失败: %v", err)
+		return
+	}
+	defer res.Body.Close()
+	// 检查文档是否存在
+	if res.IsError() {
+		// 如果文档不存在,通常返回 404 Not Found
+		if res.StatusCode == 404 {
+			logger.Info("文档不存在.")
+			err = errors.New("ES文档不存在")
+			return
+		} else {
+			// 其他错误
+			var e map[string]interface{}
+			if err = json.NewDecoder(res.Body).Decode(&e); err != nil {
+				logger.Error("解析es应答失败: %v", err)
+				return
+			} else {
+				// Print the response status and error information.
+				logger.Error("[%s] %s: %s\n", res.Status(), e["error"].(map[string]interface{})["type"], e["error"].(map[string]interface{})["原因"])
+				err = errors.New("获取ES记录失败")
+				return
+			}
+		}
+	} else {
+		// 如果文档存在
+		body, readErr := io.ReadAll(res.Body)
+		if readErr != nil {
+			logger.Error("获取es应答失败: %v", err)
+			err = readErr
+			return
+		}
+		err = json.Unmarshal(body, &doc)
+		if err != nil {
+			logger.Error("反序列化es应答失败: %v", err)
+			return
+		}
+		return
+	}
+}
+
 //
 //func CreateIndex(indexName string) error {
 //	resp, err := esClient.es().Indices.

+ 6 - 0
common/exception/exc_enums.go

@@ -119,6 +119,9 @@ const (
 	MediaFoundFailed
 	GetMediaListFailed
 	GetAnalystMediaListFailed
+	ChartImageEmptyError
+	IllegalChartId
+	UpdateChartImageFailed
 )
 
 const (
@@ -254,6 +257,9 @@ var ErrorMap = map[int]string{
 	GetMediaListFailed:        "查询媒体列表失败",
 	GetAnalystMediaListFailed: "查询研究员媒体列表失败",
 	BindMobileFailed:          "绑定手机号失败",
+	ChartImageEmptyError:      "图表缩略图url不能为空",
+	IllegalChartId:            "非法的图表ID",
+	UpdateChartImageFailed:    "更新图表缩略图失败",
 	//商户
 	ProductInfoError:      "获取商品信息失败",
 	IllegalProductId:      "非法的产品ID",

+ 48 - 0
controllers/chart/chart_controller.go

@@ -0,0 +1,48 @@
+package chart
+
+import (
+	logger "eta/eta_mini_ht_api/common/component/log"
+	"eta/eta_mini_ht_api/common/exception"
+	"eta/eta_mini_ht_api/controllers"
+	chart "eta/eta_mini_ht_api/service/media"
+)
+
+type ChartController struct {
+	controllers.ListController
+}
+type ChartEsUpdateReq struct {
+	ChartImage  string `json:"chartImage"`
+	ChartInfoId int    `json:"chartInfoId"`
+}
+
+// UpdateChartImage 更新图表缩略图
+// @Description 更新图表缩略图
+// @Success 200 {object}
+// @router /updateChartImage [post]
+func (m *ChartController) UpdateChartImage() {
+	controllers.Wrap(&m.BaseController, func() (result *controllers.WrapData, err error) {
+		result = m.InitWrapData("更新图表缩略图成功")
+		var chartEsUpdateReq ChartEsUpdateReq
+		m.GetPostParams(&chartEsUpdateReq)
+		if chartEsUpdateReq.ChartImage == "" {
+			err = exception.New(exception.ChartImageEmptyError)
+			m.FailedResult("更新图表缩略图失败", result)
+			return
+		}
+		if chartEsUpdateReq.ChartInfoId == 0 {
+			err = exception.New(exception.IllegalChartId)
+			m.FailedResult("更新图表缩略图失败", result)
+			return
+		}
+		success := chart.UpdateChartImage(chartEsUpdateReq.ChartImage, chartEsUpdateReq.ChartInfoId)
+		if !success {
+			err = exception.New(exception.UpdateChartImageFailed)
+			logger.Error("更新图表缩略图失败,chartInfoId:%d", chartEsUpdateReq.ChartInfoId)
+			m.FailedResult("更新图表缩略图失败", result)
+			return
+		}
+
+		m.SuccessResult("更新图表缩略图成功", nil, result)
+		return
+	})
+}

+ 24 - 0
domian/media/chart_service.go

@@ -1,5 +1,10 @@
 package media
 
+import (
+	"encoding/json"
+	logger "eta/eta_mini_ht_api/common/component/log"
+)
+
 const (
 	ChartESColumn      = "chartName"
 	ChartESRangeColumn = "chartInfoId"
@@ -45,3 +50,22 @@ type EsChartInfo struct {
 func AddChartToEs(esChart EsChartInfo) bool {
 	return elastic().InsertOrUpdate(htConfig.GetChartIndex(), esChart.ChartInfoId, esChart)
 }
+
+func UpdateChartImage(image string, id int) bool {
+	doc, err := elastic().Get(htConfig.GetChartIndex(), id)
+	if err != nil {
+		return false
+	}
+	var chartInfo EsChartInfo
+	err = json.Unmarshal(doc.Source, &chartInfo)
+	if err != nil {
+		logger.Error("es获取图表数据失败:%v", err)
+		return false
+	}
+	if chartInfo.ChartInfoId == 0 {
+		logger.Error("es获取图表数据失败,chartInfoId:%d", id)
+		return false
+	}
+	chartInfo.ChartImage = image
+	return elastic().Update(htConfig.GetChartIndex(), chartInfo.ChartInfoId, chartInfo)
+}

+ 1 - 0
middleware/auth_middleware.go

@@ -61,6 +61,7 @@ var publicRoutes = []string{
 	"/user/bind_gzh",
 	"/user/wx/notify",
 	"/webhook/*",
+	"/chart/updateChartImage",
 }
 var privateRoutes = []string{
 	"/user/profile",

+ 9 - 0
routers/commentsRouter.go

@@ -7,6 +7,15 @@ import (
 
 func init() {
 
+    beego.GlobalControllerRouter["eta/eta_mini_ht_api/controllers/chart:ChartController"] = append(beego.GlobalControllerRouter["eta/eta_mini_ht_api/controllers/chart:ChartController"],
+        beego.ControllerComments{
+            Method: "UpdateChartImage",
+            Router: `/updateChartImage`,
+            AllowHTTPMethods: []string{"post"},
+            MethodParams: param.Make(),
+            Filters: nil,
+            Params: nil})
+
     beego.GlobalControllerRouter["eta/eta_mini_ht_api/controllers/home:HomeController"] = append(beego.GlobalControllerRouter["eta/eta_mini_ht_api/controllers/home:HomeController"],
         beego.ControllerComments{
             Method: "Search",

+ 6 - 0
routers/router.go

@@ -2,6 +2,7 @@ package routers
 
 import (
 	"eta/eta_mini_ht_api/controllers"
+	"eta/eta_mini_ht_api/controllers/chart"
 	"eta/eta_mini_ht_api/controllers/home"
 	"eta/eta_mini_ht_api/controllers/media"
 	"eta/eta_mini_ht_api/controllers/order"
@@ -101,6 +102,11 @@ func init() {
 				&payment.PaymentController{},
 			),
 		),
+		web.NSNamespace("/chart",
+			web.NSInclude(
+				&chart.ChartController{},
+			),
+		),
 	)
 	web.AddNamespace(ns)
 }

+ 4 - 0
service/media/chart_service.go

@@ -23,3 +23,7 @@ func AddChartToEs(chartInfo ChartInfo) {
 		logger.Error("新增图表到ES失败, chartInfoId:%d,uniqueCode:%s", chartInfo.ChartInfoId, chartInfo.UniqueCode)
 	}
 }
+
+func UpdateChartImage(image string, id int) bool {
+	return chartService.UpdateChartImage(image, id)
+}