MongoDB统一数据查询钩子

MongoDB统一数据查询钩子

1.前提

使用go-zero模板生成MongoDB的查询操作不满足我们,需要生成一个带钩子的查询

2.问题分析

查询钩子经常用于业务,现在需要把查询钩子写入go-zero模板中,使每次生成都带有查询钩子

3.解决方案

通过修改go-zero模板里面的model文件,然后再使用修改后的模板进行生成代码
1.在接口里面增加一个方法

FindHook(ctx context.Context,id string,bf beforeFind,af afterFind) (*{{.Type}}, error) 

2.定义钩子函数

type beforeFind func(string)
type afterFind func(string)

3.实现查询钩子

func (m *default{{.Type}}Model) FindHook(ctx context.Context,id string,bf beforeFind,af afterFind) (*{{.Type}}, error) {
    if bf != nil {
        bf(id)
    }
​
    oid, err := primitive.ObjectIDFromHex(id)
    if err != nil {
        return nil, ErrInvalidObjectId
    }var data {{.Type}}
    {{if .Cache}}key := prefix{{.Type}}CacheKey + id{{end}}
    err = m.conn.FindOne(ctx, {{if .Cache}}key, {{end}}&data, bson.M{"_id": oid})if af != nil {
        af(id)
    }switch err {
    case nil:
        return &data, nil
    case {{if .Cache}}monc{{else}}mon{{end}}.ErrNotFound:
        return nil, ErrNotFound
    default:
        return nil, err
    }
}

4.使用修改后的模板生成我们的代码;如果以前代码已经生成了,那么就把对应的文件夹删除重新生成就好

$ goctl model mongo -e -dir ./MongoDBmodel -t edgeinstance --home template

4.实现思路

我的实现思路是先写好go的钩子查询,然后把此查询写成tpl模板格式,修改放在go-zero模板中

5.资料来源

gorm钩子