在复杂请求的情况下如何实现Go中的存储库?



假设我们有多个具有next字段的产品:id、名称、类型、价格、重量。我想返回与某些复杂过滤器匹配的产品,例如:

  • 名称如'%bla%'和类型= 3 -返回名称中包含特定子字符串且属于特定类型的所有产品
  • 名称为'%bla%',类型=4,重量/价格<10
  • (name like '%bla%' and type=5)或(name like '%lala%' and type=6 and price <200)

我不想为每个可能的过滤器实现单独的方法。

存储库从数据库中获取数据(我使用postgres)

你可以这样做:

package main
import(
"fmt"
"regexp"
)
type Items struct{
_id string;
_name string;
_type int;
_price float64;
_weight float64;
}
func (i *Items) filter(bla string) []Items{
items := []Items{
Items{
_id: "i_78676758",
_name: "packet1",
_type: 4,
_price: 44.65,
_weight: 3.6,
},
Items{
_id: "i_546458",
_name: "packet2",
_type: 5,
_price: 234.65,
_weight: 123.6,
},
Items{
_id: "i_5879788",
_name: "packet2",
_type: 5,
_price: 34.65,
_weight: 13.6,
},
Items{
_id: "i_7858758",
_name: "packet3",
_type: 3,
_price: 284.65,
_weight: 23.6,
},
};
var validID = regexp.MustCompile(regexp.QuoteMeta(bla))
new_items := []Items{}
for _, item := range items{
switch{
case ((validID.MatchString(item._name)) && (item._type == 3)):
new_items = items
break;
case ((validID.MatchString(item._name)) && (item._type == 4) && (item._price < 10) && (item._weight < 10)):
new_items = append(new_items, item)
case (((validID.MatchString(item._name)) && item._type == 5) || ((validID.MatchString(item._name)) && (item._type == 6) && (item._price < 200))):
new_items = append(new_items, item)
case ((validID.MatchString(item._name)) && (item._price > 100)):
new_items = append(new_items, item)
default:
}
}
return new_items;
}
func main(){
item := &Items{
_id: "i_7858758",
_name: "packet",
_type: 4,
_price: 234.65,
_weight: 23.6,
}
items := item.filter("et2")
fmt.Println(items)
}

上述代码中Itemsstruct保存有过滤器的数据。方法,循环遍历这是一个[]Items并根据Regexp匹配的文本进行过滤和开关箱来验证其他东西,最后返回一个[]Items保存过滤后的数据。

最新更新