mab

package module
v0.0.0-...-7dbae93 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 30, 2024 License: BSD-3-Clause Imports: 20 Imported by: 1

README

ab

  • page 控制页码 page_size 控制条数

    • 最大均为100 100页 100条
  • _last mid 大页码通用

  • _o(asc) _od(desc) 排序 _o=like _od=字段名

  • _s搜索 __在左右则为模糊 _s=__赵日天

  • [字段名] 进行过滤 id=1 最长64位请注意 and关系 eg name=赵日天

  • o[字段名] 进行过滤 _o_id=2 最长64位 or关系 eg _o_name=赵日天

  • _g $geoNear 根据此点返回由近到远的列表 _g=lng,lat

    • 一旦出现此参数则会自动进入Aggregate执行模式且$geoNear排名第一位
    • 官方文档点这里
    • 默认 distanceField 为 _distance
    • 使用geojson方式 所以返回的距离为米
    • spherical 为true 是球面计算方式
    • maxDistance 取参数_gmax 单位为米 可不传
    • minDistance 取参数_gmin 单位为米 可不传
    • key 默认为location 暂不支持修改
  • _gmax 必须与_g参数同时出现才有意义 为最大距离 单位米

  • _gmin 必须与_g参数同时出现才有意义 为最小距离 单位米

别名配置

  • 表别名 struct方法
    • Alias() string 或者 SpAlias() string 均可配置表别名 格式为 _组名-1_表名-1 也可以为仅返回表名 会进入默认的 未命名
      • 组名和表名 后面如果是 -1 则是排序的数组 会自动去除 数字越大 排名优先
  • 字段别名 comment 标签

说明

  • 全面拥抱json 新增修改均使用json上传
  • 约定大于配置
struct定义的名称
  * Id 为主键
  * UpdateAt 为更新时间 每次更新自动赋值
  * CreateAt 为创建时间 需要自己设置qmgo的插入事件或自行设置时间
  * DeleteAt 为删除时间 一般不需要设置 除非使用了悲观锁version 需要自行设置

外键
  * 配置项PK函数 需要返回数组的lookup stage阶段所需的bson  

参数操作符
  * 通过_[op] 或 _[op]_ 可进行操作符定义 eg: params: address__position_eq_="赵日天" 会转换成 {"address.position":{"$eq":"赵日天"}}
  * 支持的op有 `eq`, `gt`, `gte`, `lt`, `lte`, `ne` , `in`, `nin`,`exists`,`null`
  * `exists` 不是内容 而是指字段是否存在 例如 `name_exists_`:`true`|`false` 则表示`name`字段是否存在
  * `null` 表示内容是否存在 eg: `name_null_`:`true`|`false` 则表示判断`name`字段内容是否存在

  • 请一定要设置bson标签 若不设置则自动小写的蛇形
  • 修改成功后返回的是成功变更的字段序列
  • private context上下文传递的时候类型一定要同struct定义的一致
  • 仅新增是通过struct方式 所以可以触发qmgo的事件
  • 修改更新时会自动发现updated 自动赋值最新时间 使用的是 time.Now().Local()
  • 关于时间时区问题 默认UTC RFC3339Nano
  • 大量使用了反射 主要满足前期快速开发的业务需求 上一定量之后可以考虑深入优化
  • 各种mustFilters 虽然用的map string 但是只会考虑key value会被忽略 暂时..
  • 对于要进行比较的time 必须是utc时间!!!

限制

  • 暂未开放cache
  • 暂时使用本地化缓存 有需要的再加入集群缓存

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	DefaultStructDelimiter = "__"
)

Functions

func DiffBson

func DiffBson(oldData bson.M, wantData bson.M, reqSendData bson.M) (diff bson.M, eq bson.M)

DiffBson 两个bson.m 对比 获取异同

func IsNum

func IsNum(s string) bool

func LimitHandler

func LimitHandler(l *limiter.Limiter, errBack ...func(*errors.HTTPError, iris.Context)) iris.Handler

func ModelGetData

func ModelGetData(ctx iris.Context, sm *SingleModel, mdb *qmgo.Database, parse *CtxGetDataParse) ([]bson.M, iris.Map, error)

func ModelGetSingle

func ModelGetSingle(ctx iris.Context, sm *SingleModel, mdb *qmgo.Database, parse *CtxGetDataParse) (bson.M, error)

func UTCTrans

func UTCTrans(utcTime string) (time.Time, error)

Types

type AliasProcess

type AliasProcess interface {
	Alias() string
}

type Config

type Config struct {
	Party             iris.Party
	Mdb               *qmgo.Database
	Models            []*SingleModel
	ErrorTrace        func(err error, event, from, router string) // error trace func
	Generator         bool                                        // 生成器模式 若启用则只有一个入口
	PrivateContextKey string
	PrivateColName    string
	StructDelimiter   string   // 内联struct之间的分隔符 默认__ 因为.号会被转义 不要使用. _
	SensitiveUri      []string // 敏感词库
	SensitiveWords    []string // 敏感词列表
}

Config 配置文件 敏感词 用于国内的审核 可在model配置文件中配置需要验证的字段 每次数据新增/修改时会进行验证

type CtxGeoInfo

type CtxGeoInfo struct {
	Lng    float64
	Lat    float64
	GeoMax int64
	GeoMin int64
}

func CtxGeoParse

func CtxGeoParse(ctx iris.Context) (bool, *CtxGeoInfo, error)

type CtxGetDataParse

type CtxGetDataParse struct {
	OrBson      []bson.E // or
	FilterBson  []bson.E // and
	PrivateBson []bson.E // 私密
	ExtraBson   []bson.E // 额外附加
	SortDesc    []string // 降序
	SortAsc     []string // 升序
	SortList    []string // order by
	LastMid     primitive.ObjectID
	LastSort    string      // 最后mid排序方式 默认desc
	HasGeo      bool        // 是否包含geo信息
	GeoInfo     *CtxGeoInfo // geo信息
	Search      string      // 搜索词
	SearchBson  []bson.E    // 对应的搜索bson
	Pk          []bson.D    // 外键
	Page        int64
	PageSize    int64
}

func CtxDataParse

func CtxDataParse(ctx iris.Context, sm *SingleModel, delimiter string) (*CtxGetDataParse, error)

func CtxSingleDataParse

func CtxSingleDataParse(ctx iris.Context, sm *SingleModel, mid string, delimiter string) (*CtxGetDataParse, error)

type ModelInfo

type ModelInfo struct {
	MapName    string       `json:"map_name"`
	FullPath   string       `json:"full_path"`
	Alias      string       `json:"alias"`
	Group      string       `json:"group"`
	GroupLevel uint         `json:"group_level"`
	Level      uint         `json:"level"`
	FieldList  []StructInfo `json:"field_list"`
	FlatFields []StructInfo `json:"flat_fields"`
}

ModelInfo 模型信息

type RestApi

type RestApi struct {
	Cfg *Config
	// contains filtered or unexported fields
}

func New

func New(cfg *Config) *RestApi

func (*RestApi) AddData

func (rest *RestApi) AddData(ctx iris.Context)

AddData 新增数据 使用json序列化 并且新增的是一个struct对象 所以可以使用qmgo的事件 注意事项 传入数据一定要符合`json`格式的预期 因为是直接通过 `json.Unmarshal` 结构到 struct 示例 Inline `bson:"inline"` 传入 {"key":""} 没有定义类型则直接传入inline的子元素 示范 Inline any `bson:",inline"` 传入 {"Inline":{"key":""}} 未设置json标签则取字段名称 示范 Inline any `json:"inline" bson:"inline"` 传入数据 {"inline":{"key":""}} 示范 JsonInLine any `json:"json_in_line,inline" bson:"inline"` 传入数据 {"json_in_line":{"key":""}} json tag的inline标签在Unmarshal时候似乎无作用 推荐 对于inline层面的数据 不要设置类型 直接引入 加入bson inline的tag标记即可 eg: Inline `bson:",inline"`

func (*RestApi) DeleteData

func (rest *RestApi) DeleteData(ctx iris.Context)

DeleteData 删除数据 /{mid:string range(1,32)}

func (*RestApi) EditData

func (rest *RestApi) EditData(ctx iris.Context)

EditData 修改数据 /{mid:string range(1,32)} 因为修改是按需传入变更的字段 而且会存在着直接传入 bson tag inline的情况 所以会先分析传入值 进行解析 如果 bson 标签有 inline 但是 json 标签有指定字段名时 传入json命名会自动结构到平级 传入下级会自动归类到json命名中 如果 json没有指定字段名 但是bson指定了时 传入的是字段名也就是大写 则会自动生成一个 bson字段名的元素

func (*RestApi) ErrorResponse

func (rest *RestApi) ErrorResponse(err error, ctx iris.Context, msg ...string)

func (*RestApi) GetAllFunc

func (rest *RestApi) GetAllFunc(ctx iris.Context)

GetAllFunc 获取所有 page 控制页码 page_size 控制条数 最大均为100 100页 100条 _last mid 大页码通用 _o(asc) _od _s __在左右则为模糊 _s=__赵日天 [字段名] 进行过滤 id=1 最长64位请注意 and关系 _o_[字段名] 进行过滤 _o_id=2 最长64位 or关系

func (*RestApi) GetModelInfo

func (rest *RestApi) GetModelInfo(ctx iris.Context)

GetModelInfo 获取模型信息

func (*RestApi) GetModelInfoList

func (rest *RestApi) GetModelInfoList() []ModelInfo

GetModelInfoList 获取详细的模型列表

func (*RestApi) GetSingle

func (rest *RestApi) GetSingle(ctx iris.Context)

GetSingle 单个 /{mid:string range(1,32)}

func (*RestApi) NameGetModel

func (rest *RestApi) NameGetModel(pathname string) (*SingleModel, error)

NameGetModel 根据名称获取model

func (*RestApi) PathGetMid

func (rest *RestApi) PathGetMid(method string, uri string) (string, string)

PathGetMid 根据path提取出mid

func (*RestApi) PathGetModel

func (rest *RestApi) PathGetModel(pathUri string) *SingleModel

PathGetModel 通过路径获取对应的模型信息

func (*RestApi) UriGetMid

func (rest *RestApi) UriGetMid(uri string) (string, string)

UriGetMid 根据uri获取mid

type SingleModel

type SingleModel struct {
	Prefix       string // 路由前缀
	Suffix       string // 路由后缀
	Model        any    // xorm Model
	ShowCount    bool   // 显示搜索数量
	ShowDocCount bool   // 显示文档数量
	AllowGetInfo bool   // 允许获取表结构信息

	CustomModel func(ctx iris.Context, model *SingleModel) *SingleModel // 记住要进行指针值传递 返回一个新对象 否则会修改原始配置文件
	Pk          func() []bson.D                                         // 外键

	DisablePrivate    bool            // 禁用私密参数
	DisablePrivateMap map[string]bool // 禁用私密参数定制项 key为方法 value为启用与否 前提条件必须启用后才能禁用 而不能禁用后启用

	PrivateContextKey string // 上下文key string int uint
	PrivateColName    string // 数据库字段名 MapName or ColName is ok

	AllowMethods      []string // allow methods first
	DisableMethods    []string // get(all) get(single) post put delete
	MustSearch        bool     // 必须搜索模式 会忽略下面的搜索设置强制开启搜索 (非slice|struct|primitive.ObjectID)
	AllowSearchFields []string // 搜索的字段 struct名称

	InjectParams          func(ctx iris.Context) map[string]string                                                 // 注入params 用于get请求参数的自定义
	GetAllResponseFunc    func(ctx iris.Context, result iris.Map, dataList []bson.M) iris.Map                      // 返回内容替换的方法
	GetAllExtraFilters    func(ctx iris.Context) map[string]any                                                    // 额外的固定过滤 key(数据库列名) 和 value 若与请求过滤重复则覆盖 优先级最高
	GetAllMustFilters     map[string]string                                                                        // 获取全部必须拥有筛选
	GetAllCheck           func(ctx iris.Context, params *CtxGetDataParse) (bool, string)                           // 获取是否通过审核
	GetSingleResponseFunc func(ctx iris.Context, item bson.M) bson.M                                               // 获取单个返回内容替换的方法
	GetSingleExtraFilters func(ctx iris.Context) map[string]any                                                    // 额外的固定过滤 key(数据库列名) 和 value 若与请求过滤重复则覆盖 优先级最高
	GetSingleMustFilters  map[string]string                                                                        // 获取单个必须拥有筛选
	PostMustFilters       map[string]string                                                                        // 新增必须存在的参数
	PostResponseFunc      func(ctx iris.Context, mid string, item any) any                                         //
	PostDataParse         func(ctx iris.Context, raw any) any                                                      //
	PostDataCheck         func(ctx iris.Context, data any) (bool, string)                                          // 新增数据校验
	PutDataParse          func(ctx iris.Context, mid string, diff bson.M) bson.M                                   //
	PutQueryParse         func(ctx iris.Context, mid string, query bson.M, data any, privateValue any) bson.M      // 修改的时候query可以自定义修改
	PutResponseFunc       func(ctx iris.Context, mid string) iris.Map                                              // 在修改之前还可以变更一下数据
	PutDataCheck          func(ctx iris.Context, item any, reqData any, reqMap bson.M, diff bson.M) (bool, string) // 新增数据校验
	PutMustFilters        map[string]string                                                                        //
	DeleteDataCheck       func(ctx iris.Context, item any) (bool, string)                                          // 删除验证
	DeleteResponseFunc    func(ctx iris.Context, mid string, item bson.M, result iris.Map) iris.Map                //
	SensitiveFields       []string                                                                                 // 使用struct name 或者mapname 均可(map对象为bson:)

	CacheTime          time.Duration                          // full cache time
	GetAllCacheTime    time.Duration                          // get all cache time
	GetSingleCacheTime time.Duration                          // get single cache time
	DelayDeleteTime    time.Duration                          // 延迟多久双删 default 500ms
	MaxPageSize        int64                                  // max page size limit
	MaxPageCount       int64                                  // max page count limit
	RateErrorFunc      func(*tollerr.HTTPError, iris.Context) //
	Rate               *limiter.Limiter                       // all
	GetAllRate         *limiter.Limiter                       //
	GetSingleRate      *limiter.Limiter                       //
	AddRate            *limiter.Limiter                       //
	PutRate            *limiter.Limiter                       //
	DeleteRate         *limiter.Limiter                       //
	// contains filtered or unexported fields
}

SingleModel 单个模型实例 CustomModel 主要用来动态配置项 比如说context变更 pk变更等灵活使用 e.g:

	func(ctx iris.Context, Model *SingleModel) *SingleModel {
		newModel:= new(SingleModel)
     *newModel = *Model
     // 修改配置文件
     return newModel
	}

func (*SingleModel) Init

func (sm *SingleModel) Init(delimiter string, relPath string, privateContextKey string, PrivateColName string)

type SpAliasProcess

type SpAliasProcess interface {
	SpAlias() string
}

type StructInfo

type StructInfo struct {
	Name          string       `json:"name"`                   // 字段名 struct name
	MapName       string       `json:"map_name"`               // 转snake格式的名称
	FullName      string       `json:"full_name"`              // [parentStructName][structDelimiter]][structName]
	FullMapName   string       `json:"full_map_name"`          // [parentSnakeName][structDelimiter][snakeName]
	ParamsKey     string       `json:"params_key"`             // post form key name
	CustomTag     string       `json:"custom_tag"`             // 自定义标签信息 mab:
	ValidateTag   string       `json:"validate_tag,omitempty"` // 验证器标签信息
	DescTag       string       `json:"desc_tag,omitempty"`     // 描述标签信息
	Comment       string       `json:"comment,omitempty"`
	Level         string       `json:"level"` // parentIndex - .... - self index
	Kind          string       `json:"kind"`
	Bson          []string     `json:"bson"` // bson tag
	BsonName      string       `json:"bson_name"`
	JsonTag       []string     `json:"json_tag"` // json tag
	JsonName      string       `json:"json_name"`
	Types         string       `json:"types"`
	Index         int          `json:"index,omitempty"`
	IsDefaultWrap bool         `json:"is_default_wrap,omitempty"`
	IsTime        bool         `json:"is_time,omitempty"`
	IsPk          bool         `json:"is_pk,omitempty"`
	IsObjId       bool         `json:"is_obj_id,omitempty"`
	IsCreated     bool         `json:"is_created,omitempty"`
	IsUpdated     bool         `json:"is_updated,omitempty"`
	IsDeleted     bool         `json:"is_deleted,omitempty"`
	IsGeo         bool         `json:"is_geo,omitempty"`
	IsInline      bool         `json:"is_inline,omitempty"`
	Children      []StructInfo `json:"children,omitempty"`
	ChildrenKind  string       `json:"children_kind,omitempty"`
}

StructInfo 模型字段信息

func TableNameGetNestedStructMaps

func TableNameGetNestedStructMaps(r reflect.Type, parentStructName, parentMapName string, parentLevel string, structDelimiter string) []StructInfo

func TableNameReflectFieldsAndTypes

func TableNameReflectFieldsAndTypes(table interface{}, structDelimiter string) []StructInfo

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL