diff --git a/api/graphql.go b/api/graphql.go index cb02e18..3fa5bb0 100644 --- a/api/graphql.go +++ b/api/graphql.go @@ -224,53 +224,34 @@ func NewSchema(config Config) (graphql.Schema, error) { after := p.Args["after"] fields_str := strings.Join(fields, ",") + // 参数到 SQL 格式字符串的映射 + var argToSQLFormat = map[string]string{ + "id": "id=%d", + "width": "width=%d", + "height": "height=%d", + "content": "content='%s'", + "remark": "remark='%s'", + "description": "description='%s'", + "tags": "tags='%s'", + "rank": "rank='%s'", + "comment_num": "comment_num=%d", + "praise_count": "praise_count=%d", + "collect_count": "collect_count=%d", + "article_id": "article_id=%d", + "user_id": "user_id=%d", + "create_time": "create_time='%s'", + "update_time": "update_time='%s'", + } + // 筛选条件 var where []string - if p.Args["id"] != nil { - where = append(where, fmt.Sprintf("id=%d", p.Args["id"])) - } - if p.Args["width"] != nil { - where = append(where, fmt.Sprintf("width=%d", p.Args["width"])) - } - if p.Args["height"] != nil { - where = append(where, fmt.Sprintf("height=%d", p.Args["height"])) - } - if p.Args["content"] != nil { - where = append(where, fmt.Sprintf("content='%s'", p.Args["content"])) - } - if p.Args["remark"] != nil { - where = append(where, fmt.Sprintf("remark='%s'", p.Args["remark"])) - } - if p.Args["description"] != nil { - where = append(where, fmt.Sprintf("description='%s'", p.Args["description"])) - } - if p.Args["tags"] != nil { - where = append(where, fmt.Sprintf("tags='%s'", p.Args["tags"])) - } - if p.Args["rank"] != nil { - where = append(where, fmt.Sprintf("rank='%s'", p.Args["rank"])) - } - if p.Args["comment_num"] != nil { - where = append(where, fmt.Sprintf("comment_num=%d", p.Args["comment_num"])) - } - if p.Args["praise_count"] != nil { - where = append(where, fmt.Sprintf("praise_count=%d", p.Args["praise_count"])) - } - if p.Args["collect_count"] != nil { - where = append(where, fmt.Sprintf("collect_count=%d", p.Args["collect_count"])) - } - if p.Args["article_id"] != nil { - where = append(where, fmt.Sprintf("article_id=%d", p.Args["article_id"])) - } - if p.Args["user_id"] != nil { - where = append(where, fmt.Sprintf("user_id=%d", p.Args["user_id"])) - } - if p.Args["create_time"] != nil { - where = append(where, fmt.Sprintf("create_time='%s'", p.Args["create_time"])) - } - if p.Args["update_time"] != nil { - where = append(where, fmt.Sprintf("update_time='%s'", p.Args["update_time"])) + for arg, format := range argToSQLFormat { + if p.Args[arg] != nil { + where = append(where, fmt.Sprintf(format, p.Args[arg])) + } } + + // 特殊处理 text 参数 if p.Args["text"] != nil { id_list := models.ElasticsearchSearch(p.Args["text"].(string)).GetIDList() id_list_str := strings.Trim(strings.Join(strings.Fields(fmt.Sprint(id_list)), ","), "[]") @@ -284,6 +265,7 @@ func NewSchema(config Config) (graphql.Schema, error) { } where = append(where, fmt.Sprintf("id IN (%s)", id_list_str)) } + where_str := strings.Join(where, " AND ") // 执行查询