add: user accomplished

This commit is contained in:
wwweww
2026-02-27 05:42:13 +08:00
parent 659168fe32
commit a0c720eb2f
90 changed files with 9592 additions and 1180 deletions
@@ -7,6 +7,7 @@ import (
"context"
"encoding/json"
"fmt"
"juwan-backend/common/redisx"
"time"
"juwan-backend/app/email/api/internal/svc"
@@ -44,7 +45,7 @@ func (l *SendVerificationCodeLogic) SendVerificationCode(req *types.SendVerifica
code := utils.GenCode()
requestID := uuid.NewString()
redisKey := fmt.Sprintf("vcode:%s:%s:%s", requestID, req.Scene, req.Email)
redisKey := fmt.Sprintf(redisx.VCODE_KEY_PREFIX, requestID, req.Scene, req.Email)
if exists, getErr := l.svcCtx.RedisCluster.Get(l.ctx, redisKey).Result(); getErr == nil && exists != "" {
return nil, fmt.Errorf("verification code already sent, please wait before requesting a new one")
}
+28
View File
@@ -0,0 +1,28 @@
Name: pb.rpc
ListenOn: 0.0.0.0:8080
DataSource: "${DB_URI}?sslmode=disable"
SnowflakeRpcConf:
Target: k8s://juwan/snowflake-svc:8080
DB:
Master: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-rw.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable"
Slave: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@user-db-ro.juwan:${DB_PORT}/${DB_NAME}?sslmode=disable"
CacheConf:
- Host: "${REDIS_M_HOST}"
Type: node
Pass: "${REDIS_PASSWORD}"
User: "default"
- Host: "${REDIS_S_HOST}"
Type: node
Pass: "${REDIS_PASSWORD}"
User: "default"
Jwt:
SecretKey: "${JWT_SECRET_KEY}"
Issuer: "juwan-user-rpc"
Log:
Level: info
@@ -0,0 +1,7 @@
package config
import "github.com/zeromicro/go-zero/zrpc"
type Config struct {
zrpc.RpcServerConf
}
@@ -0,0 +1,31 @@
package logic
import (
"context"
"juwan-backend/app/user_verifications/rpc/internal/svc"
"juwan-backend/app/user_verifications/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type AddUserVerificationsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewAddUserVerificationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddUserVerificationsLogic {
return &AddUserVerificationsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// -----------------------userVerifications-----------------------
func (l *AddUserVerificationsLogic) AddUserVerifications(in *pb.AddUserVerificationsReq) (*pb.AddUserVerificationsResp, error) {
// todo: add your logic here and delete this line
return &pb.AddUserVerificationsResp{}, nil
}
@@ -0,0 +1,30 @@
package logic
import (
"context"
"juwan-backend/app/user_verifications/rpc/internal/svc"
"juwan-backend/app/user_verifications/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type DelUserVerificationsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewDelUserVerificationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelUserVerificationsLogic {
return &DelUserVerificationsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *DelUserVerificationsLogic) DelUserVerifications(in *pb.DelUserVerificationsReq) (*pb.DelUserVerificationsResp, error) {
// todo: add your logic here and delete this line
return &pb.DelUserVerificationsResp{}, nil
}
@@ -0,0 +1,30 @@
package logic
import (
"context"
"juwan-backend/app/user_verifications/rpc/internal/svc"
"juwan-backend/app/user_verifications/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type GetUserVerificationsByIdLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewGetUserVerificationsByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserVerificationsByIdLogic {
return &GetUserVerificationsByIdLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *GetUserVerificationsByIdLogic) GetUserVerificationsById(in *pb.GetUserVerificationsByIdReq) (*pb.GetUserVerificationsByIdResp, error) {
// todo: add your logic here and delete this line
return &pb.GetUserVerificationsByIdResp{}, nil
}
@@ -0,0 +1,30 @@
package logic
import (
"context"
"juwan-backend/app/user_verifications/rpc/internal/svc"
"juwan-backend/app/user_verifications/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type SearchUserVerificationsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewSearchUserVerificationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchUserVerificationsLogic {
return &SearchUserVerificationsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *SearchUserVerificationsLogic) SearchUserVerifications(in *pb.SearchUserVerificationsReq) (*pb.SearchUserVerificationsResp, error) {
// todo: add your logic here and delete this line
return &pb.SearchUserVerificationsResp{}, nil
}
@@ -0,0 +1,30 @@
package logic
import (
"context"
"juwan-backend/app/user_verifications/rpc/internal/svc"
"juwan-backend/app/user_verifications/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type UpdateUserVerificationsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewUpdateUserVerificationsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUserVerificationsLogic {
return &UpdateUserVerificationsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *UpdateUserVerificationsLogic) UpdateUserVerifications(in *pb.UpdateUserVerificationsReq) (*pb.UpdateUserVerificationsResp, error) {
// todo: add your logic here and delete this line
return &pb.UpdateUserVerificationsResp{}, nil
}
@@ -0,0 +1,50 @@
// Code generated by goctl. DO NOT EDIT.
// goctl 1.9.2
// Source: user_verifications.proto
package server
import (
"context"
"juwan-backend/app/user_verifications/rpc/internal/logic"
"juwan-backend/app/user_verifications/rpc/internal/svc"
"juwan-backend/app/user_verifications/rpc/pb"
)
type UserVerificationsServer struct {
svcCtx *svc.ServiceContext
pb.UnimplementedUserVerificationsServer
}
func NewUserVerificationsServer(svcCtx *svc.ServiceContext) *UserVerificationsServer {
return &UserVerificationsServer{
svcCtx: svcCtx,
}
}
// -----------------------userVerifications-----------------------
func (s *UserVerificationsServer) AddUserVerifications(ctx context.Context, in *pb.AddUserVerificationsReq) (*pb.AddUserVerificationsResp, error) {
l := logic.NewAddUserVerificationsLogic(ctx, s.svcCtx)
return l.AddUserVerifications(in)
}
func (s *UserVerificationsServer) UpdateUserVerifications(ctx context.Context, in *pb.UpdateUserVerificationsReq) (*pb.UpdateUserVerificationsResp, error) {
l := logic.NewUpdateUserVerificationsLogic(ctx, s.svcCtx)
return l.UpdateUserVerifications(in)
}
func (s *UserVerificationsServer) DelUserVerifications(ctx context.Context, in *pb.DelUserVerificationsReq) (*pb.DelUserVerificationsResp, error) {
l := logic.NewDelUserVerificationsLogic(ctx, s.svcCtx)
return l.DelUserVerifications(in)
}
func (s *UserVerificationsServer) GetUserVerificationsById(ctx context.Context, in *pb.GetUserVerificationsByIdReq) (*pb.GetUserVerificationsByIdResp, error) {
l := logic.NewGetUserVerificationsByIdLogic(ctx, s.svcCtx)
return l.GetUserVerificationsById(in)
}
func (s *UserVerificationsServer) SearchUserVerifications(ctx context.Context, in *pb.SearchUserVerificationsReq) (*pb.SearchUserVerificationsResp, error) {
l := logic.NewSearchUserVerificationsLogic(ctx, s.svcCtx)
return l.SearchUserVerifications(in)
}
@@ -0,0 +1,13 @@
package svc
import "juwan-backend/app/user_verifications/rpc/internal/config"
type ServiceContext struct {
Config config.Config
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
}
}
@@ -0,0 +1,27 @@
package svc
import (
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
var _ UserVerificationsModel = (*customUserVerificationsModel)(nil)
type (
// UserVerificationsModel is an interface to be customized, add more methods here,
// and implement the added methods in customUserVerificationsModel.
UserVerificationsModel interface {
userVerificationsModel
}
customUserVerificationsModel struct {
*defaultUserVerificationsModel
}
)
// NewUserVerificationsModel returns a model for the database table.
func NewUserVerificationsModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) UserVerificationsModel {
return &customUserVerificationsModel{
defaultUserVerificationsModel: newUserVerificationsModel(conn, c, opts...),
}
}
@@ -0,0 +1,154 @@
// Code generated by goctl. DO NOT EDIT.
// versions:
// goctl version: 1.9.2
package svc
import (
"context"
"database/sql"
"fmt"
"strings"
"time"
"github.com/zeromicro/go-zero/core/stores/builder"
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlc"
"github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stringx"
)
var (
userVerificationsFieldNames = builder.RawFieldNames(&UserVerifications{}, true)
userVerificationsRows = strings.Join(userVerificationsFieldNames, ",")
userVerificationsRowsExpectAutoSet = strings.Join(stringx.Remove(userVerificationsFieldNames, "create_at", "create_time", "created_at", "update_at", "update_time", "updated_at"), ",")
userVerificationsRowsWithPlaceHolder = builder.PostgreSqlJoin(stringx.Remove(userVerificationsFieldNames, "id", "create_at", "create_time", "created_at", "update_at", "update_time", "updated_at"))
cachePublicUserVerificationsIdPrefix = "cache:public:userVerifications:id:"
cachePublicUserVerificationsUserIdRolePrefix = "cache:public:userVerifications:userId:role:"
)
type (
userVerificationsModel interface {
Insert(ctx context.Context, data *UserVerifications) (sql.Result, error)
FindOne(ctx context.Context, id int64) (*UserVerifications, error)
FindOneByUserIdRole(ctx context.Context, userId int64, role string) (*UserVerifications, error)
Update(ctx context.Context, data *UserVerifications) error
Delete(ctx context.Context, id int64) error
}
defaultUserVerificationsModel struct {
sqlc.CachedConn
table string
}
UserVerifications struct {
Id int64 `db:"id"`
UserId int64 `db:"user_id"`
Role string `db:"role"`
Status string `db:"status"`
Materials string `db:"materials"`
RejectReason sql.NullString `db:"reject_reason"`
ReviewedBy sql.NullInt64 `db:"reviewed_by"`
ReviewedAt sql.NullTime `db:"reviewed_at"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
}
)
func newUserVerificationsModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) *defaultUserVerificationsModel {
return &defaultUserVerificationsModel{
CachedConn: sqlc.NewConn(conn, c, opts...),
table: `"public"."user_verifications"`,
}
}
func (m *defaultUserVerificationsModel) Delete(ctx context.Context, id int64) error {
data, err := m.FindOne(ctx, id)
if err != nil {
return err
}
publicUserVerificationsIdKey := fmt.Sprintf("%s%v", cachePublicUserVerificationsIdPrefix, id)
publicUserVerificationsUserIdRoleKey := fmt.Sprintf("%s%v:%v", cachePublicUserVerificationsUserIdRolePrefix, data.UserId, data.Role)
_, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("delete from %s where id = $1", m.table)
return conn.ExecCtx(ctx, query, id)
}, publicUserVerificationsIdKey, publicUserVerificationsUserIdRoleKey)
return err
}
func (m *defaultUserVerificationsModel) FindOne(ctx context.Context, id int64) (*UserVerifications, error) {
publicUserVerificationsIdKey := fmt.Sprintf("%s%v", cachePublicUserVerificationsIdPrefix, id)
var resp UserVerifications
err := m.QueryRowCtx(ctx, &resp, publicUserVerificationsIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
query := fmt.Sprintf("select %s from %s where id = $1 limit 1", userVerificationsRows, m.table)
return conn.QueryRowCtx(ctx, v, query, id)
})
switch err {
case nil:
return &resp, nil
case sqlc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultUserVerificationsModel) FindOneByUserIdRole(ctx context.Context, userId int64, role string) (*UserVerifications, error) {
publicUserVerificationsUserIdRoleKey := fmt.Sprintf("%s%v:%v", cachePublicUserVerificationsUserIdRolePrefix, userId, role)
var resp UserVerifications
err := m.QueryRowIndexCtx(ctx, &resp, publicUserVerificationsUserIdRoleKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v any) (i any, e error) {
query := fmt.Sprintf("select %s from %s where user_id = $1 and role = $2 limit 1", userVerificationsRows, m.table)
if err := conn.QueryRowCtx(ctx, &resp, query, userId, role); err != nil {
return nil, err
}
return resp.Id, nil
}, m.queryPrimary)
switch err {
case nil:
return &resp, nil
case sqlc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultUserVerificationsModel) Insert(ctx context.Context, data *UserVerifications) (sql.Result, error) {
publicUserVerificationsIdKey := fmt.Sprintf("%s%v", cachePublicUserVerificationsIdPrefix, data.Id)
publicUserVerificationsUserIdRoleKey := fmt.Sprintf("%s%v:%v", cachePublicUserVerificationsUserIdRolePrefix, data.UserId, data.Role)
ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("insert into %s (%s) values ($1, $2, $3, $4, $5, $6, $7, $8)", m.table, userVerificationsRowsExpectAutoSet)
return conn.ExecCtx(ctx, query, data.Id, data.UserId, data.Role, data.Status, data.Materials, data.RejectReason, data.ReviewedBy, data.ReviewedAt)
}, publicUserVerificationsIdKey, publicUserVerificationsUserIdRoleKey)
return ret, err
}
func (m *defaultUserVerificationsModel) Update(ctx context.Context, newData *UserVerifications) error {
data, err := m.FindOne(ctx, newData.Id)
if err != nil {
return err
}
publicUserVerificationsIdKey := fmt.Sprintf("%s%v", cachePublicUserVerificationsIdPrefix, data.Id)
publicUserVerificationsUserIdRoleKey := fmt.Sprintf("%s%v:%v", cachePublicUserVerificationsUserIdRolePrefix, data.UserId, data.Role)
_, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where id = $1", m.table, userVerificationsRowsWithPlaceHolder)
return conn.ExecCtx(ctx, query, newData.Id, newData.UserId, newData.Role, newData.Status, newData.Materials, newData.RejectReason, newData.ReviewedBy, newData.ReviewedAt)
}, publicUserVerificationsIdKey, publicUserVerificationsUserIdRoleKey)
return err
}
func (m *defaultUserVerificationsModel) formatPrimary(primary any) string {
return fmt.Sprintf("%s%v", cachePublicUserVerificationsIdPrefix, primary)
}
func (m *defaultUserVerificationsModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary any) error {
query := fmt.Sprintf("select %s from %s where id = $1 limit 1", userVerificationsRows, m.table)
return conn.QueryRowCtx(ctx, v, query, primary)
}
func (m *defaultUserVerificationsModel) tableName() string {
return m.table
}
@@ -1,4 +1,4 @@
package models
package svc
import "github.com/zeromicro/go-zero/core/stores/sqlx"
+39
View File
@@ -0,0 +1,39 @@
package main
import (
"flag"
"fmt"
"juwan-backend/app/user_verifications/rpc/internal/config"
"juwan-backend/app/user_verifications/rpc/internal/server"
"juwan-backend/app/user_verifications/rpc/internal/svc"
"juwan-backend/app/user_verifications/rpc/pb"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/core/service"
"github.com/zeromicro/go-zero/zrpc"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
var configFile = flag.String("f", "etc/pb.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
ctx := svc.NewServiceContext(c)
s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
pb.RegisterUserVerificationsServer(grpcServer, server.NewUserVerificationsServer(ctx))
if c.Mode == service.DevMode || c.Mode == service.TestMode {
reflection.Register(grpcServer)
}
})
defer s.Stop()
fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
s.Start()
}
@@ -0,0 +1,936 @@
// Code generated by protoc-gen-go. DO NOT EDIT.
// versions:
// protoc-gen-go v1.36.11
// protoc v5.29.6
// source: user_verifications.proto
package pb
import (
protoreflect "google.golang.org/protobuf/reflect/protoreflect"
protoimpl "google.golang.org/protobuf/runtime/protoimpl"
reflect "reflect"
sync "sync"
unsafe "unsafe"
)
const (
// Verify that this generated code is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
// Verify that runtime/protoimpl is sufficiently up-to-date.
_ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
)
// --------------------------------userVerifications--------------------------------
type UserVerifications struct {
state protoimpl.MessageState `protogen:"open.v1"`
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id
UserId int64 `protobuf:"varint,2,opt,name=userId,proto3" json:"userId,omitempty"` //userId
Role string `protobuf:"bytes,3,opt,name=role,proto3" json:"role,omitempty"` //role
Status string `protobuf:"bytes,4,opt,name=status,proto3" json:"status,omitempty"` //status
Materials string `protobuf:"bytes,5,opt,name=materials,proto3" json:"materials,omitempty"` //materials
RejectReason string `protobuf:"bytes,6,opt,name=rejectReason,proto3" json:"rejectReason,omitempty"` //rejectReason
ReviewedBy int64 `protobuf:"varint,7,opt,name=reviewedBy,proto3" json:"reviewedBy,omitempty"` //reviewedBy
ReviewedAt int64 `protobuf:"varint,8,opt,name=reviewedAt,proto3" json:"reviewedAt,omitempty"` //reviewedAt
CreatedAt int64 `protobuf:"varint,9,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt
UpdatedAt int64 `protobuf:"varint,10,opt,name=updatedAt,proto3" json:"updatedAt,omitempty"` //updatedAt
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *UserVerifications) Reset() {
*x = UserVerifications{}
mi := &file_user_verifications_proto_msgTypes[0]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *UserVerifications) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UserVerifications) ProtoMessage() {}
func (x *UserVerifications) ProtoReflect() protoreflect.Message {
mi := &file_user_verifications_proto_msgTypes[0]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UserVerifications.ProtoReflect.Descriptor instead.
func (*UserVerifications) Descriptor() ([]byte, []int) {
return file_user_verifications_proto_rawDescGZIP(), []int{0}
}
func (x *UserVerifications) GetId() int64 {
if x != nil {
return x.Id
}
return 0
}
func (x *UserVerifications) GetUserId() int64 {
if x != nil {
return x.UserId
}
return 0
}
func (x *UserVerifications) GetRole() string {
if x != nil {
return x.Role
}
return ""
}
func (x *UserVerifications) GetStatus() string {
if x != nil {
return x.Status
}
return ""
}
func (x *UserVerifications) GetMaterials() string {
if x != nil {
return x.Materials
}
return ""
}
func (x *UserVerifications) GetRejectReason() string {
if x != nil {
return x.RejectReason
}
return ""
}
func (x *UserVerifications) GetReviewedBy() int64 {
if x != nil {
return x.ReviewedBy
}
return 0
}
func (x *UserVerifications) GetReviewedAt() int64 {
if x != nil {
return x.ReviewedAt
}
return 0
}
func (x *UserVerifications) GetCreatedAt() int64 {
if x != nil {
return x.CreatedAt
}
return 0
}
func (x *UserVerifications) GetUpdatedAt() int64 {
if x != nil {
return x.UpdatedAt
}
return 0
}
type AddUserVerificationsReq struct {
state protoimpl.MessageState `protogen:"open.v1"`
UserId int64 `protobuf:"varint,1,opt,name=userId,proto3" json:"userId,omitempty"` //userId
Role string `protobuf:"bytes,2,opt,name=role,proto3" json:"role,omitempty"` //role
Status string `protobuf:"bytes,3,opt,name=status,proto3" json:"status,omitempty"` //status
Materials string `protobuf:"bytes,4,opt,name=materials,proto3" json:"materials,omitempty"` //materials
RejectReason string `protobuf:"bytes,5,opt,name=rejectReason,proto3" json:"rejectReason,omitempty"` //rejectReason
ReviewedBy int64 `protobuf:"varint,6,opt,name=reviewedBy,proto3" json:"reviewedBy,omitempty"` //reviewedBy
ReviewedAt int64 `protobuf:"varint,7,opt,name=reviewedAt,proto3" json:"reviewedAt,omitempty"` //reviewedAt
CreatedAt int64 `protobuf:"varint,8,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt
UpdatedAt int64 `protobuf:"varint,9,opt,name=updatedAt,proto3" json:"updatedAt,omitempty"` //updatedAt
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *AddUserVerificationsReq) Reset() {
*x = AddUserVerificationsReq{}
mi := &file_user_verifications_proto_msgTypes[1]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *AddUserVerificationsReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddUserVerificationsReq) ProtoMessage() {}
func (x *AddUserVerificationsReq) ProtoReflect() protoreflect.Message {
mi := &file_user_verifications_proto_msgTypes[1]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddUserVerificationsReq.ProtoReflect.Descriptor instead.
func (*AddUserVerificationsReq) Descriptor() ([]byte, []int) {
return file_user_verifications_proto_rawDescGZIP(), []int{1}
}
func (x *AddUserVerificationsReq) GetUserId() int64 {
if x != nil {
return x.UserId
}
return 0
}
func (x *AddUserVerificationsReq) GetRole() string {
if x != nil {
return x.Role
}
return ""
}
func (x *AddUserVerificationsReq) GetStatus() string {
if x != nil {
return x.Status
}
return ""
}
func (x *AddUserVerificationsReq) GetMaterials() string {
if x != nil {
return x.Materials
}
return ""
}
func (x *AddUserVerificationsReq) GetRejectReason() string {
if x != nil {
return x.RejectReason
}
return ""
}
func (x *AddUserVerificationsReq) GetReviewedBy() int64 {
if x != nil {
return x.ReviewedBy
}
return 0
}
func (x *AddUserVerificationsReq) GetReviewedAt() int64 {
if x != nil {
return x.ReviewedAt
}
return 0
}
func (x *AddUserVerificationsReq) GetCreatedAt() int64 {
if x != nil {
return x.CreatedAt
}
return 0
}
func (x *AddUserVerificationsReq) GetUpdatedAt() int64 {
if x != nil {
return x.UpdatedAt
}
return 0
}
type AddUserVerificationsResp struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *AddUserVerificationsResp) Reset() {
*x = AddUserVerificationsResp{}
mi := &file_user_verifications_proto_msgTypes[2]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *AddUserVerificationsResp) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*AddUserVerificationsResp) ProtoMessage() {}
func (x *AddUserVerificationsResp) ProtoReflect() protoreflect.Message {
mi := &file_user_verifications_proto_msgTypes[2]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use AddUserVerificationsResp.ProtoReflect.Descriptor instead.
func (*AddUserVerificationsResp) Descriptor() ([]byte, []int) {
return file_user_verifications_proto_rawDescGZIP(), []int{2}
}
type UpdateUserVerificationsReq struct {
state protoimpl.MessageState `protogen:"open.v1"`
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id
UserId int64 `protobuf:"varint,2,opt,name=userId,proto3" json:"userId,omitempty"` //userId
Role string `protobuf:"bytes,3,opt,name=role,proto3" json:"role,omitempty"` //role
Status string `protobuf:"bytes,4,opt,name=status,proto3" json:"status,omitempty"` //status
Materials string `protobuf:"bytes,5,opt,name=materials,proto3" json:"materials,omitempty"` //materials
RejectReason string `protobuf:"bytes,6,opt,name=rejectReason,proto3" json:"rejectReason,omitempty"` //rejectReason
ReviewedBy int64 `protobuf:"varint,7,opt,name=reviewedBy,proto3" json:"reviewedBy,omitempty"` //reviewedBy
ReviewedAt int64 `protobuf:"varint,8,opt,name=reviewedAt,proto3" json:"reviewedAt,omitempty"` //reviewedAt
CreatedAt int64 `protobuf:"varint,9,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt
UpdatedAt int64 `protobuf:"varint,10,opt,name=updatedAt,proto3" json:"updatedAt,omitempty"` //updatedAt
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *UpdateUserVerificationsReq) Reset() {
*x = UpdateUserVerificationsReq{}
mi := &file_user_verifications_proto_msgTypes[3]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *UpdateUserVerificationsReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UpdateUserVerificationsReq) ProtoMessage() {}
func (x *UpdateUserVerificationsReq) ProtoReflect() protoreflect.Message {
mi := &file_user_verifications_proto_msgTypes[3]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UpdateUserVerificationsReq.ProtoReflect.Descriptor instead.
func (*UpdateUserVerificationsReq) Descriptor() ([]byte, []int) {
return file_user_verifications_proto_rawDescGZIP(), []int{3}
}
func (x *UpdateUserVerificationsReq) GetId() int64 {
if x != nil {
return x.Id
}
return 0
}
func (x *UpdateUserVerificationsReq) GetUserId() int64 {
if x != nil {
return x.UserId
}
return 0
}
func (x *UpdateUserVerificationsReq) GetRole() string {
if x != nil {
return x.Role
}
return ""
}
func (x *UpdateUserVerificationsReq) GetStatus() string {
if x != nil {
return x.Status
}
return ""
}
func (x *UpdateUserVerificationsReq) GetMaterials() string {
if x != nil {
return x.Materials
}
return ""
}
func (x *UpdateUserVerificationsReq) GetRejectReason() string {
if x != nil {
return x.RejectReason
}
return ""
}
func (x *UpdateUserVerificationsReq) GetReviewedBy() int64 {
if x != nil {
return x.ReviewedBy
}
return 0
}
func (x *UpdateUserVerificationsReq) GetReviewedAt() int64 {
if x != nil {
return x.ReviewedAt
}
return 0
}
func (x *UpdateUserVerificationsReq) GetCreatedAt() int64 {
if x != nil {
return x.CreatedAt
}
return 0
}
func (x *UpdateUserVerificationsReq) GetUpdatedAt() int64 {
if x != nil {
return x.UpdatedAt
}
return 0
}
type UpdateUserVerificationsResp struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *UpdateUserVerificationsResp) Reset() {
*x = UpdateUserVerificationsResp{}
mi := &file_user_verifications_proto_msgTypes[4]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *UpdateUserVerificationsResp) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*UpdateUserVerificationsResp) ProtoMessage() {}
func (x *UpdateUserVerificationsResp) ProtoReflect() protoreflect.Message {
mi := &file_user_verifications_proto_msgTypes[4]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use UpdateUserVerificationsResp.ProtoReflect.Descriptor instead.
func (*UpdateUserVerificationsResp) Descriptor() ([]byte, []int) {
return file_user_verifications_proto_rawDescGZIP(), []int{4}
}
type DelUserVerificationsReq struct {
state protoimpl.MessageState `protogen:"open.v1"`
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *DelUserVerificationsReq) Reset() {
*x = DelUserVerificationsReq{}
mi := &file_user_verifications_proto_msgTypes[5]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *DelUserVerificationsReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DelUserVerificationsReq) ProtoMessage() {}
func (x *DelUserVerificationsReq) ProtoReflect() protoreflect.Message {
mi := &file_user_verifications_proto_msgTypes[5]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use DelUserVerificationsReq.ProtoReflect.Descriptor instead.
func (*DelUserVerificationsReq) Descriptor() ([]byte, []int) {
return file_user_verifications_proto_rawDescGZIP(), []int{5}
}
func (x *DelUserVerificationsReq) GetId() int64 {
if x != nil {
return x.Id
}
return 0
}
type DelUserVerificationsResp struct {
state protoimpl.MessageState `protogen:"open.v1"`
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *DelUserVerificationsResp) Reset() {
*x = DelUserVerificationsResp{}
mi := &file_user_verifications_proto_msgTypes[6]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *DelUserVerificationsResp) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*DelUserVerificationsResp) ProtoMessage() {}
func (x *DelUserVerificationsResp) ProtoReflect() protoreflect.Message {
mi := &file_user_verifications_proto_msgTypes[6]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use DelUserVerificationsResp.ProtoReflect.Descriptor instead.
func (*DelUserVerificationsResp) Descriptor() ([]byte, []int) {
return file_user_verifications_proto_rawDescGZIP(), []int{6}
}
type GetUserVerificationsByIdReq struct {
state protoimpl.MessageState `protogen:"open.v1"`
Id int64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty"` //id
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetUserVerificationsByIdReq) Reset() {
*x = GetUserVerificationsByIdReq{}
mi := &file_user_verifications_proto_msgTypes[7]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetUserVerificationsByIdReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetUserVerificationsByIdReq) ProtoMessage() {}
func (x *GetUserVerificationsByIdReq) ProtoReflect() protoreflect.Message {
mi := &file_user_verifications_proto_msgTypes[7]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetUserVerificationsByIdReq.ProtoReflect.Descriptor instead.
func (*GetUserVerificationsByIdReq) Descriptor() ([]byte, []int) {
return file_user_verifications_proto_rawDescGZIP(), []int{7}
}
func (x *GetUserVerificationsByIdReq) GetId() int64 {
if x != nil {
return x.Id
}
return 0
}
type GetUserVerificationsByIdResp struct {
state protoimpl.MessageState `protogen:"open.v1"`
UserVerifications *UserVerifications `protobuf:"bytes,1,opt,name=userVerifications,proto3" json:"userVerifications,omitempty"` //userVerifications
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *GetUserVerificationsByIdResp) Reset() {
*x = GetUserVerificationsByIdResp{}
mi := &file_user_verifications_proto_msgTypes[8]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *GetUserVerificationsByIdResp) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*GetUserVerificationsByIdResp) ProtoMessage() {}
func (x *GetUserVerificationsByIdResp) ProtoReflect() protoreflect.Message {
mi := &file_user_verifications_proto_msgTypes[8]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use GetUserVerificationsByIdResp.ProtoReflect.Descriptor instead.
func (*GetUserVerificationsByIdResp) Descriptor() ([]byte, []int) {
return file_user_verifications_proto_rawDescGZIP(), []int{8}
}
func (x *GetUserVerificationsByIdResp) GetUserVerifications() *UserVerifications {
if x != nil {
return x.UserVerifications
}
return nil
}
type SearchUserVerificationsReq struct {
state protoimpl.MessageState `protogen:"open.v1"`
Page int64 `protobuf:"varint,1,opt,name=page,proto3" json:"page,omitempty"` //page
Limit int64 `protobuf:"varint,2,opt,name=limit,proto3" json:"limit,omitempty"` //limit
Id int64 `protobuf:"varint,3,opt,name=id,proto3" json:"id,omitempty"` //id
UserId int64 `protobuf:"varint,4,opt,name=userId,proto3" json:"userId,omitempty"` //userId
Role string `protobuf:"bytes,5,opt,name=role,proto3" json:"role,omitempty"` //role
Status string `protobuf:"bytes,6,opt,name=status,proto3" json:"status,omitempty"` //status
Materials string `protobuf:"bytes,7,opt,name=materials,proto3" json:"materials,omitempty"` //materials
RejectReason string `protobuf:"bytes,8,opt,name=rejectReason,proto3" json:"rejectReason,omitempty"` //rejectReason
ReviewedBy int64 `protobuf:"varint,9,opt,name=reviewedBy,proto3" json:"reviewedBy,omitempty"` //reviewedBy
ReviewedAt int64 `protobuf:"varint,10,opt,name=reviewedAt,proto3" json:"reviewedAt,omitempty"` //reviewedAt
CreatedAt int64 `protobuf:"varint,11,opt,name=createdAt,proto3" json:"createdAt,omitempty"` //createdAt
UpdatedAt int64 `protobuf:"varint,12,opt,name=updatedAt,proto3" json:"updatedAt,omitempty"` //updatedAt
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *SearchUserVerificationsReq) Reset() {
*x = SearchUserVerificationsReq{}
mi := &file_user_verifications_proto_msgTypes[9]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *SearchUserVerificationsReq) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SearchUserVerificationsReq) ProtoMessage() {}
func (x *SearchUserVerificationsReq) ProtoReflect() protoreflect.Message {
mi := &file_user_verifications_proto_msgTypes[9]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SearchUserVerificationsReq.ProtoReflect.Descriptor instead.
func (*SearchUserVerificationsReq) Descriptor() ([]byte, []int) {
return file_user_verifications_proto_rawDescGZIP(), []int{9}
}
func (x *SearchUserVerificationsReq) GetPage() int64 {
if x != nil {
return x.Page
}
return 0
}
func (x *SearchUserVerificationsReq) GetLimit() int64 {
if x != nil {
return x.Limit
}
return 0
}
func (x *SearchUserVerificationsReq) GetId() int64 {
if x != nil {
return x.Id
}
return 0
}
func (x *SearchUserVerificationsReq) GetUserId() int64 {
if x != nil {
return x.UserId
}
return 0
}
func (x *SearchUserVerificationsReq) GetRole() string {
if x != nil {
return x.Role
}
return ""
}
func (x *SearchUserVerificationsReq) GetStatus() string {
if x != nil {
return x.Status
}
return ""
}
func (x *SearchUserVerificationsReq) GetMaterials() string {
if x != nil {
return x.Materials
}
return ""
}
func (x *SearchUserVerificationsReq) GetRejectReason() string {
if x != nil {
return x.RejectReason
}
return ""
}
func (x *SearchUserVerificationsReq) GetReviewedBy() int64 {
if x != nil {
return x.ReviewedBy
}
return 0
}
func (x *SearchUserVerificationsReq) GetReviewedAt() int64 {
if x != nil {
return x.ReviewedAt
}
return 0
}
func (x *SearchUserVerificationsReq) GetCreatedAt() int64 {
if x != nil {
return x.CreatedAt
}
return 0
}
func (x *SearchUserVerificationsReq) GetUpdatedAt() int64 {
if x != nil {
return x.UpdatedAt
}
return 0
}
type SearchUserVerificationsResp struct {
state protoimpl.MessageState `protogen:"open.v1"`
UserVerifications []*UserVerifications `protobuf:"bytes,1,rep,name=userVerifications,proto3" json:"userVerifications,omitempty"` //userVerifications
unknownFields protoimpl.UnknownFields
sizeCache protoimpl.SizeCache
}
func (x *SearchUserVerificationsResp) Reset() {
*x = SearchUserVerificationsResp{}
mi := &file_user_verifications_proto_msgTypes[10]
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
ms.StoreMessageInfo(mi)
}
func (x *SearchUserVerificationsResp) String() string {
return protoimpl.X.MessageStringOf(x)
}
func (*SearchUserVerificationsResp) ProtoMessage() {}
func (x *SearchUserVerificationsResp) ProtoReflect() protoreflect.Message {
mi := &file_user_verifications_proto_msgTypes[10]
if x != nil {
ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
if ms.LoadMessageInfo() == nil {
ms.StoreMessageInfo(mi)
}
return ms
}
return mi.MessageOf(x)
}
// Deprecated: Use SearchUserVerificationsResp.ProtoReflect.Descriptor instead.
func (*SearchUserVerificationsResp) Descriptor() ([]byte, []int) {
return file_user_verifications_proto_rawDescGZIP(), []int{10}
}
func (x *SearchUserVerificationsResp) GetUserVerifications() []*UserVerifications {
if x != nil {
return x.UserVerifications
}
return nil
}
var File_user_verifications_proto protoreflect.FileDescriptor
const file_user_verifications_proto_rawDesc = "" +
"\n" +
"\x18user_verifications.proto\x12\x02pb\"\xa5\x02\n" +
"\x11UserVerifications\x12\x0e\n" +
"\x02id\x18\x01 \x01(\x03R\x02id\x12\x16\n" +
"\x06userId\x18\x02 \x01(\x03R\x06userId\x12\x12\n" +
"\x04role\x18\x03 \x01(\tR\x04role\x12\x16\n" +
"\x06status\x18\x04 \x01(\tR\x06status\x12\x1c\n" +
"\tmaterials\x18\x05 \x01(\tR\tmaterials\x12\"\n" +
"\frejectReason\x18\x06 \x01(\tR\frejectReason\x12\x1e\n" +
"\n" +
"reviewedBy\x18\a \x01(\x03R\n" +
"reviewedBy\x12\x1e\n" +
"\n" +
"reviewedAt\x18\b \x01(\x03R\n" +
"reviewedAt\x12\x1c\n" +
"\tcreatedAt\x18\t \x01(\x03R\tcreatedAt\x12\x1c\n" +
"\tupdatedAt\x18\n" +
" \x01(\x03R\tupdatedAt\"\x9b\x02\n" +
"\x17AddUserVerificationsReq\x12\x16\n" +
"\x06userId\x18\x01 \x01(\x03R\x06userId\x12\x12\n" +
"\x04role\x18\x02 \x01(\tR\x04role\x12\x16\n" +
"\x06status\x18\x03 \x01(\tR\x06status\x12\x1c\n" +
"\tmaterials\x18\x04 \x01(\tR\tmaterials\x12\"\n" +
"\frejectReason\x18\x05 \x01(\tR\frejectReason\x12\x1e\n" +
"\n" +
"reviewedBy\x18\x06 \x01(\x03R\n" +
"reviewedBy\x12\x1e\n" +
"\n" +
"reviewedAt\x18\a \x01(\x03R\n" +
"reviewedAt\x12\x1c\n" +
"\tcreatedAt\x18\b \x01(\x03R\tcreatedAt\x12\x1c\n" +
"\tupdatedAt\x18\t \x01(\x03R\tupdatedAt\"\x1a\n" +
"\x18AddUserVerificationsResp\"\xae\x02\n" +
"\x1aUpdateUserVerificationsReq\x12\x0e\n" +
"\x02id\x18\x01 \x01(\x03R\x02id\x12\x16\n" +
"\x06userId\x18\x02 \x01(\x03R\x06userId\x12\x12\n" +
"\x04role\x18\x03 \x01(\tR\x04role\x12\x16\n" +
"\x06status\x18\x04 \x01(\tR\x06status\x12\x1c\n" +
"\tmaterials\x18\x05 \x01(\tR\tmaterials\x12\"\n" +
"\frejectReason\x18\x06 \x01(\tR\frejectReason\x12\x1e\n" +
"\n" +
"reviewedBy\x18\a \x01(\x03R\n" +
"reviewedBy\x12\x1e\n" +
"\n" +
"reviewedAt\x18\b \x01(\x03R\n" +
"reviewedAt\x12\x1c\n" +
"\tcreatedAt\x18\t \x01(\x03R\tcreatedAt\x12\x1c\n" +
"\tupdatedAt\x18\n" +
" \x01(\x03R\tupdatedAt\"\x1d\n" +
"\x1bUpdateUserVerificationsResp\")\n" +
"\x17DelUserVerificationsReq\x12\x0e\n" +
"\x02id\x18\x01 \x01(\x03R\x02id\"\x1a\n" +
"\x18DelUserVerificationsResp\"-\n" +
"\x1bGetUserVerificationsByIdReq\x12\x0e\n" +
"\x02id\x18\x01 \x01(\x03R\x02id\"c\n" +
"\x1cGetUserVerificationsByIdResp\x12C\n" +
"\x11userVerifications\x18\x01 \x01(\v2\x15.pb.UserVerificationsR\x11userVerifications\"\xd8\x02\n" +
"\x1aSearchUserVerificationsReq\x12\x12\n" +
"\x04page\x18\x01 \x01(\x03R\x04page\x12\x14\n" +
"\x05limit\x18\x02 \x01(\x03R\x05limit\x12\x0e\n" +
"\x02id\x18\x03 \x01(\x03R\x02id\x12\x16\n" +
"\x06userId\x18\x04 \x01(\x03R\x06userId\x12\x12\n" +
"\x04role\x18\x05 \x01(\tR\x04role\x12\x16\n" +
"\x06status\x18\x06 \x01(\tR\x06status\x12\x1c\n" +
"\tmaterials\x18\a \x01(\tR\tmaterials\x12\"\n" +
"\frejectReason\x18\b \x01(\tR\frejectReason\x12\x1e\n" +
"\n" +
"reviewedBy\x18\t \x01(\x03R\n" +
"reviewedBy\x12\x1e\n" +
"\n" +
"reviewedAt\x18\n" +
" \x01(\x03R\n" +
"reviewedAt\x12\x1c\n" +
"\tcreatedAt\x18\v \x01(\x03R\tcreatedAt\x12\x1c\n" +
"\tupdatedAt\x18\f \x01(\x03R\tupdatedAt\"b\n" +
"\x1bSearchUserVerificationsResp\x12C\n" +
"\x11userVerifications\x18\x01 \x03(\v2\x15.pb.UserVerificationsR\x11userVerifications2\xd1\x03\n" +
"\x12user_verifications\x12Q\n" +
"\x14AddUserVerifications\x12\x1b.pb.AddUserVerificationsReq\x1a\x1c.pb.AddUserVerificationsResp\x12Z\n" +
"\x17UpdateUserVerifications\x12\x1e.pb.UpdateUserVerificationsReq\x1a\x1f.pb.UpdateUserVerificationsResp\x12Q\n" +
"\x14DelUserVerifications\x12\x1b.pb.DelUserVerificationsReq\x1a\x1c.pb.DelUserVerificationsResp\x12]\n" +
"\x18GetUserVerificationsById\x12\x1f.pb.GetUserVerificationsByIdReq\x1a .pb.GetUserVerificationsByIdResp\x12Z\n" +
"\x17SearchUserVerifications\x12\x1e.pb.SearchUserVerificationsReq\x1a\x1f.pb.SearchUserVerificationsRespB\x06Z\x04./pbb\x06proto3"
var (
file_user_verifications_proto_rawDescOnce sync.Once
file_user_verifications_proto_rawDescData []byte
)
func file_user_verifications_proto_rawDescGZIP() []byte {
file_user_verifications_proto_rawDescOnce.Do(func() {
file_user_verifications_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_user_verifications_proto_rawDesc), len(file_user_verifications_proto_rawDesc)))
})
return file_user_verifications_proto_rawDescData
}
var file_user_verifications_proto_msgTypes = make([]protoimpl.MessageInfo, 11)
var file_user_verifications_proto_goTypes = []any{
(*UserVerifications)(nil), // 0: pb.UserVerifications
(*AddUserVerificationsReq)(nil), // 1: pb.AddUserVerificationsReq
(*AddUserVerificationsResp)(nil), // 2: pb.AddUserVerificationsResp
(*UpdateUserVerificationsReq)(nil), // 3: pb.UpdateUserVerificationsReq
(*UpdateUserVerificationsResp)(nil), // 4: pb.UpdateUserVerificationsResp
(*DelUserVerificationsReq)(nil), // 5: pb.DelUserVerificationsReq
(*DelUserVerificationsResp)(nil), // 6: pb.DelUserVerificationsResp
(*GetUserVerificationsByIdReq)(nil), // 7: pb.GetUserVerificationsByIdReq
(*GetUserVerificationsByIdResp)(nil), // 8: pb.GetUserVerificationsByIdResp
(*SearchUserVerificationsReq)(nil), // 9: pb.SearchUserVerificationsReq
(*SearchUserVerificationsResp)(nil), // 10: pb.SearchUserVerificationsResp
}
var file_user_verifications_proto_depIdxs = []int32{
0, // 0: pb.GetUserVerificationsByIdResp.userVerifications:type_name -> pb.UserVerifications
0, // 1: pb.SearchUserVerificationsResp.userVerifications:type_name -> pb.UserVerifications
1, // 2: pb.user_verifications.AddUserVerifications:input_type -> pb.AddUserVerificationsReq
3, // 3: pb.user_verifications.UpdateUserVerifications:input_type -> pb.UpdateUserVerificationsReq
5, // 4: pb.user_verifications.DelUserVerifications:input_type -> pb.DelUserVerificationsReq
7, // 5: pb.user_verifications.GetUserVerificationsById:input_type -> pb.GetUserVerificationsByIdReq
9, // 6: pb.user_verifications.SearchUserVerifications:input_type -> pb.SearchUserVerificationsReq
2, // 7: pb.user_verifications.AddUserVerifications:output_type -> pb.AddUserVerificationsResp
4, // 8: pb.user_verifications.UpdateUserVerifications:output_type -> pb.UpdateUserVerificationsResp
6, // 9: pb.user_verifications.DelUserVerifications:output_type -> pb.DelUserVerificationsResp
8, // 10: pb.user_verifications.GetUserVerificationsById:output_type -> pb.GetUserVerificationsByIdResp
10, // 11: pb.user_verifications.SearchUserVerifications:output_type -> pb.SearchUserVerificationsResp
7, // [7:12] is the sub-list for method output_type
2, // [2:7] is the sub-list for method input_type
2, // [2:2] is the sub-list for extension type_name
2, // [2:2] is the sub-list for extension extendee
0, // [0:2] is the sub-list for field type_name
}
func init() { file_user_verifications_proto_init() }
func file_user_verifications_proto_init() {
if File_user_verifications_proto != nil {
return
}
type x struct{}
out := protoimpl.TypeBuilder{
File: protoimpl.DescBuilder{
GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
RawDescriptor: unsafe.Slice(unsafe.StringData(file_user_verifications_proto_rawDesc), len(file_user_verifications_proto_rawDesc)),
NumEnums: 0,
NumMessages: 11,
NumExtensions: 0,
NumServices: 1,
},
GoTypes: file_user_verifications_proto_goTypes,
DependencyIndexes: file_user_verifications_proto_depIdxs,
MessageInfos: file_user_verifications_proto_msgTypes,
}.Build()
File_user_verifications_proto = out.File
file_user_verifications_proto_goTypes = nil
file_user_verifications_proto_depIdxs = nil
}
@@ -0,0 +1,275 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.1
// - protoc v5.29.6
// source: user_verifications.proto
package pb
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
UserVerifications_AddUserVerifications_FullMethodName = "/pb.user_verifications/AddUserVerifications"
UserVerifications_UpdateUserVerifications_FullMethodName = "/pb.user_verifications/UpdateUserVerifications"
UserVerifications_DelUserVerifications_FullMethodName = "/pb.user_verifications/DelUserVerifications"
UserVerifications_GetUserVerificationsById_FullMethodName = "/pb.user_verifications/GetUserVerificationsById"
UserVerifications_SearchUserVerifications_FullMethodName = "/pb.user_verifications/SearchUserVerifications"
)
// UserVerificationsClient is the client API for UserVerifications service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
type UserVerificationsClient interface {
// -----------------------userVerifications-----------------------
AddUserVerifications(ctx context.Context, in *AddUserVerificationsReq, opts ...grpc.CallOption) (*AddUserVerificationsResp, error)
UpdateUserVerifications(ctx context.Context, in *UpdateUserVerificationsReq, opts ...grpc.CallOption) (*UpdateUserVerificationsResp, error)
DelUserVerifications(ctx context.Context, in *DelUserVerificationsReq, opts ...grpc.CallOption) (*DelUserVerificationsResp, error)
GetUserVerificationsById(ctx context.Context, in *GetUserVerificationsByIdReq, opts ...grpc.CallOption) (*GetUserVerificationsByIdResp, error)
SearchUserVerifications(ctx context.Context, in *SearchUserVerificationsReq, opts ...grpc.CallOption) (*SearchUserVerificationsResp, error)
}
type userVerificationsClient struct {
cc grpc.ClientConnInterface
}
func NewUserVerificationsClient(cc grpc.ClientConnInterface) UserVerificationsClient {
return &userVerificationsClient{cc}
}
func (c *userVerificationsClient) AddUserVerifications(ctx context.Context, in *AddUserVerificationsReq, opts ...grpc.CallOption) (*AddUserVerificationsResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(AddUserVerificationsResp)
err := c.cc.Invoke(ctx, UserVerifications_AddUserVerifications_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *userVerificationsClient) UpdateUserVerifications(ctx context.Context, in *UpdateUserVerificationsReq, opts ...grpc.CallOption) (*UpdateUserVerificationsResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(UpdateUserVerificationsResp)
err := c.cc.Invoke(ctx, UserVerifications_UpdateUserVerifications_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *userVerificationsClient) DelUserVerifications(ctx context.Context, in *DelUserVerificationsReq, opts ...grpc.CallOption) (*DelUserVerificationsResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(DelUserVerificationsResp)
err := c.cc.Invoke(ctx, UserVerifications_DelUserVerifications_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *userVerificationsClient) GetUserVerificationsById(ctx context.Context, in *GetUserVerificationsByIdReq, opts ...grpc.CallOption) (*GetUserVerificationsByIdResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetUserVerificationsByIdResp)
err := c.cc.Invoke(ctx, UserVerifications_GetUserVerificationsById_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *userVerificationsClient) SearchUserVerifications(ctx context.Context, in *SearchUserVerificationsReq, opts ...grpc.CallOption) (*SearchUserVerificationsResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SearchUserVerificationsResp)
err := c.cc.Invoke(ctx, UserVerifications_SearchUserVerifications_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// UserVerificationsServer is the server API for UserVerifications service.
// All implementations must embed UnimplementedUserVerificationsServer
// for forward compatibility.
type UserVerificationsServer interface {
// -----------------------userVerifications-----------------------
AddUserVerifications(context.Context, *AddUserVerificationsReq) (*AddUserVerificationsResp, error)
UpdateUserVerifications(context.Context, *UpdateUserVerificationsReq) (*UpdateUserVerificationsResp, error)
DelUserVerifications(context.Context, *DelUserVerificationsReq) (*DelUserVerificationsResp, error)
GetUserVerificationsById(context.Context, *GetUserVerificationsByIdReq) (*GetUserVerificationsByIdResp, error)
SearchUserVerifications(context.Context, *SearchUserVerificationsReq) (*SearchUserVerificationsResp, error)
mustEmbedUnimplementedUserVerificationsServer()
}
// UnimplementedUserVerificationsServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedUserVerificationsServer struct{}
func (UnimplementedUserVerificationsServer) AddUserVerifications(context.Context, *AddUserVerificationsReq) (*AddUserVerificationsResp, error) {
return nil, status.Error(codes.Unimplemented, "method AddUserVerifications not implemented")
}
func (UnimplementedUserVerificationsServer) UpdateUserVerifications(context.Context, *UpdateUserVerificationsReq) (*UpdateUserVerificationsResp, error) {
return nil, status.Error(codes.Unimplemented, "method UpdateUserVerifications not implemented")
}
func (UnimplementedUserVerificationsServer) DelUserVerifications(context.Context, *DelUserVerificationsReq) (*DelUserVerificationsResp, error) {
return nil, status.Error(codes.Unimplemented, "method DelUserVerifications not implemented")
}
func (UnimplementedUserVerificationsServer) GetUserVerificationsById(context.Context, *GetUserVerificationsByIdReq) (*GetUserVerificationsByIdResp, error) {
return nil, status.Error(codes.Unimplemented, "method GetUserVerificationsById not implemented")
}
func (UnimplementedUserVerificationsServer) SearchUserVerifications(context.Context, *SearchUserVerificationsReq) (*SearchUserVerificationsResp, error) {
return nil, status.Error(codes.Unimplemented, "method SearchUserVerifications not implemented")
}
func (UnimplementedUserVerificationsServer) mustEmbedUnimplementedUserVerificationsServer() {}
func (UnimplementedUserVerificationsServer) testEmbeddedByValue() {}
// UnsafeUserVerificationsServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to UserVerificationsServer will
// result in compilation errors.
type UnsafeUserVerificationsServer interface {
mustEmbedUnimplementedUserVerificationsServer()
}
func RegisterUserVerificationsServer(s grpc.ServiceRegistrar, srv UserVerificationsServer) {
// If the following call panics, it indicates UnimplementedUserVerificationsServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&UserVerifications_ServiceDesc, srv)
}
func _UserVerifications_AddUserVerifications_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(AddUserVerificationsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UserVerificationsServer).AddUserVerifications(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: UserVerifications_AddUserVerifications_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UserVerificationsServer).AddUserVerifications(ctx, req.(*AddUserVerificationsReq))
}
return interceptor(ctx, in, info, handler)
}
func _UserVerifications_UpdateUserVerifications_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UpdateUserVerificationsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UserVerificationsServer).UpdateUserVerifications(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: UserVerifications_UpdateUserVerifications_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UserVerificationsServer).UpdateUserVerifications(ctx, req.(*UpdateUserVerificationsReq))
}
return interceptor(ctx, in, info, handler)
}
func _UserVerifications_DelUserVerifications_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(DelUserVerificationsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UserVerificationsServer).DelUserVerifications(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: UserVerifications_DelUserVerifications_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UserVerificationsServer).DelUserVerifications(ctx, req.(*DelUserVerificationsReq))
}
return interceptor(ctx, in, info, handler)
}
func _UserVerifications_GetUserVerificationsById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetUserVerificationsByIdReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UserVerificationsServer).GetUserVerificationsById(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: UserVerifications_GetUserVerificationsById_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UserVerificationsServer).GetUserVerificationsById(ctx, req.(*GetUserVerificationsByIdReq))
}
return interceptor(ctx, in, info, handler)
}
func _UserVerifications_SearchUserVerifications_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SearchUserVerificationsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UserVerificationsServer).SearchUserVerifications(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: UserVerifications_SearchUserVerifications_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UserVerificationsServer).SearchUserVerifications(ctx, req.(*SearchUserVerificationsReq))
}
return interceptor(ctx, in, info, handler)
}
// UserVerifications_ServiceDesc is the grpc.ServiceDesc for UserVerifications service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var UserVerifications_ServiceDesc = grpc.ServiceDesc{
ServiceName: "pb.user_verifications",
HandlerType: (*UserVerificationsServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "AddUserVerifications",
Handler: _UserVerifications_AddUserVerifications_Handler,
},
{
MethodName: "UpdateUserVerifications",
Handler: _UserVerifications_UpdateUserVerifications_Handler,
},
{
MethodName: "DelUserVerifications",
Handler: _UserVerifications_DelUserVerifications_Handler,
},
{
MethodName: "GetUserVerificationsById",
Handler: _UserVerifications_GetUserVerificationsById_Handler,
},
{
MethodName: "SearchUserVerifications",
Handler: _UserVerifications_SearchUserVerifications_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "user_verifications.proto",
}
@@ -0,0 +1,73 @@
// Code generated by goctl. DO NOT EDIT.
// goctl 1.9.2
// Source: user_verifications.proto
package userverifications
import (
"context"
"juwan-backend/app/user_verifications/rpc/pb"
"github.com/zeromicro/go-zero/zrpc"
"google.golang.org/grpc"
)
type (
AddUserVerificationsReq = pb.AddUserVerificationsReq
AddUserVerificationsResp = pb.AddUserVerificationsResp
DelUserVerificationsReq = pb.DelUserVerificationsReq
DelUserVerificationsResp = pb.DelUserVerificationsResp
GetUserVerificationsByIdReq = pb.GetUserVerificationsByIdReq
GetUserVerificationsByIdResp = pb.GetUserVerificationsByIdResp
SearchUserVerificationsReq = pb.SearchUserVerificationsReq
SearchUserVerificationsResp = pb.SearchUserVerificationsResp
UpdateUserVerificationsReq = pb.UpdateUserVerificationsReq
UpdateUserVerificationsResp = pb.UpdateUserVerificationsResp
UserVerifications = pb.UserVerifications
UserVerificationsZrpcClient interface {
// -----------------------userVerifications-----------------------
AddUserVerifications(ctx context.Context, in *AddUserVerificationsReq, opts ...grpc.CallOption) (*AddUserVerificationsResp, error)
UpdateUserVerifications(ctx context.Context, in *UpdateUserVerificationsReq, opts ...grpc.CallOption) (*UpdateUserVerificationsResp, error)
DelUserVerifications(ctx context.Context, in *DelUserVerificationsReq, opts ...grpc.CallOption) (*DelUserVerificationsResp, error)
GetUserVerificationsById(ctx context.Context, in *GetUserVerificationsByIdReq, opts ...grpc.CallOption) (*GetUserVerificationsByIdResp, error)
SearchUserVerifications(ctx context.Context, in *SearchUserVerificationsReq, opts ...grpc.CallOption) (*SearchUserVerificationsResp, error)
}
defaultUserVerificationsZrpcClient struct {
cli zrpc.Client
}
)
func NewUserVerificationsZrpcClient(cli zrpc.Client) UserVerificationsZrpcClient {
return &defaultUserVerificationsZrpcClient{
cli: cli,
}
}
// -----------------------userVerifications-----------------------
func (m *defaultUserVerificationsZrpcClient) AddUserVerifications(ctx context.Context, in *AddUserVerificationsReq, opts ...grpc.CallOption) (*AddUserVerificationsResp, error) {
client := pb.NewUserVerificationsClient(m.cli.Conn())
return client.AddUserVerifications(ctx, in, opts...)
}
func (m *defaultUserVerificationsZrpcClient) UpdateUserVerifications(ctx context.Context, in *UpdateUserVerificationsReq, opts ...grpc.CallOption) (*UpdateUserVerificationsResp, error) {
client := pb.NewUserVerificationsClient(m.cli.Conn())
return client.UpdateUserVerifications(ctx, in, opts...)
}
func (m *defaultUserVerificationsZrpcClient) DelUserVerifications(ctx context.Context, in *DelUserVerificationsReq, opts ...grpc.CallOption) (*DelUserVerificationsResp, error) {
client := pb.NewUserVerificationsClient(m.cli.Conn())
return client.DelUserVerifications(ctx, in, opts...)
}
func (m *defaultUserVerificationsZrpcClient) GetUserVerificationsById(ctx context.Context, in *GetUserVerificationsByIdReq, opts ...grpc.CallOption) (*GetUserVerificationsByIdResp, error) {
client := pb.NewUserVerificationsClient(m.cli.Conn())
return client.GetUserVerificationsById(ctx, in, opts...)
}
func (m *defaultUserVerificationsZrpcClient) SearchUserVerifications(ctx context.Context, in *SearchUserVerificationsReq, opts ...grpc.CallOption) (*SearchUserVerificationsResp, error) {
client := pb.NewUserVerificationsClient(m.cli.Conn())
return client.SearchUserVerifications(ctx, in, opts...)
}
@@ -28,3 +28,27 @@ func TokenFrom(c context.Context) (string, error) {
}
return token, nil
}
func WithUserID(c context.Context, id int64) context.Context {
return context.WithValue(c, "user_id", id)
}
func UserIDFrom(c context.Context) (int64, error) {
if userID, ok := c.Value("user_id").(int64); !ok {
return 0, errors.New("user_id not found in context")
} else {
return userID, nil
}
}
func WithRequestID(c context.Context, requestID string) context.Context {
return context.WithValue(c, "request_id", requestID)
}
func RequestIDFrom(c context.Context) (string, error) {
if requestID, ok := c.Value("request_id").(string); !ok {
return "", errors.New("request_id not found in context")
} else {
return requestID, nil
}
}
+40 -13
View File
@@ -17,18 +17,6 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
rest.WithMiddlewares(
[]rest.Middleware{serverCtx.Logger},
[]rest.Route{
{
// 获取用户信息
Method: http.MethodGet,
Path: "/:userId",
Handler: user.GetUserInfoHandler(serverCtx),
},
{
// 修改用户信息
Method: http.MethodPut,
Path: "/:userId",
Handler: user.UpdateUserInfoHandler(serverCtx),
},
{
// 用户登出
Method: http.MethodPost,
@@ -41,6 +29,12 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
Path: "/:userId/password",
Handler: user.UpdatePasswordHandler(serverCtx),
},
{
// 修改密码-使用验证码
Method: http.MethodPut,
Path: "/forgot-password/reset",
Handler: user.UpdatePasswordByVcodeHandler(serverCtx),
},
{
// 用户登录接口
Method: http.MethodPost,
@@ -55,6 +49,39 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
},
}...,
),
rest.WithPrefix("/api/users"),
rest.WithPrefix("/api/v1/auth"),
)
server.AddRoutes(
rest.WithMiddlewares(
[]rest.Middleware{serverCtx.Logger},
[]rest.Route{
{
// 获取用户信息
Method: http.MethodGet,
Path: "/:userId",
Handler: user.GetUserInfoHandler(serverCtx),
},
{
// 修改用户信息
Method: http.MethodPut,
Path: "/:userId",
Handler: user.UpdateUserInfoHandler(serverCtx),
},
{
// 获取当前登录用户信息
Method: http.MethodGet,
Path: "/me",
Handler: user.GetMeHandler(serverCtx),
},
{
// 更改当前登录用户信息
Method: http.MethodPut,
Path: "/me",
Handler: user.UpdateMeHandler(serverCtx),
},
}...,
),
rest.WithPrefix("/api/v1/user"),
)
}
@@ -0,0 +1,30 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package user
import (
"net/http"
"juwan-backend/app/users/api/internal/logic/user"
"juwan-backend/app/users/api/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/rest/httpx"
)
// 获取当前登录用户信息
func GetMeHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
l := user.NewGetMeLogic(r.Context(), svcCtx)
resp, err := l.GetMe()
logx.Infof("req header: %v", r.Header)
logx.Infof("cookies: %v", r.Cookies())
//r.Cookie()
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}
@@ -7,6 +7,7 @@ import (
"juwan-backend/app/users/api/internal/logic/user"
"juwan-backend/app/users/api/internal/svc"
"juwan-backend/app/users/api/internal/types"
"juwan-backend/common/utils"
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
@@ -25,7 +26,7 @@ func LoginHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
resp, err := l.Login(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
httpx.ErrorCtx(r.Context(), w, utils.NewErrorResp(400, err))
} else {
token := resp.Token
resp.Token = ""
@@ -0,0 +1,32 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package user
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"juwan-backend/app/users/api/internal/logic/user"
"juwan-backend/app/users/api/internal/svc"
"juwan-backend/app/users/api/internal/types"
)
// 更改当前登录用户信息
func UpdateMeHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.UpdateUserInfoReq
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := user.NewUpdateMeLogic(r.Context(), svcCtx)
resp, err := l.UpdateMe(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}
@@ -0,0 +1,32 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package user
import (
"net/http"
"github.com/zeromicro/go-zero/rest/httpx"
"juwan-backend/app/users/api/internal/logic/user"
"juwan-backend/app/users/api/internal/svc"
"juwan-backend/app/users/api/internal/types"
)
// 修改密码-使用验证码
func UpdatePasswordByVcodeHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.ResetPasswordByVcode
if err := httpx.Parse(r, &req); err != nil {
httpx.ErrorCtx(r.Context(), w, err)
return
}
l := user.NewUpdatePasswordByVcodeLogic(r.Context(), svcCtx)
resp, err := l.UpdatePasswordByVcode(&req)
if err != nil {
httpx.ErrorCtx(r.Context(), w, err)
} else {
httpx.OkJsonCtx(r.Context(), w, resp)
}
}
}
@@ -0,0 +1,50 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package user
import (
"context"
"errors"
"juwan-backend/app/users/api/internal/contextx"
"juwan-backend/app/users/rpc/usercenter"
"juwan-backend/common/converter"
"juwan-backend/app/users/api/internal/svc"
"juwan-backend/app/users/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type GetMeLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// 获取当前登录用户信息
func NewGetMeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMeLogic {
return &GetMeLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *GetMeLogic) GetMe() (resp *types.UserInfo, err error) {
userId, err := contextx.UserIDFrom(l.ctx)
if err != nil {
return nil, errors.New("illegal id")
}
user, err := l.svcCtx.UserRpc.GetUsersById(l.ctx, &usercenter.GetUsersByIdReq{
Id: userId,
})
if err != nil {
return nil, errors.New("get user by id error")
}
err = converter.StructToStruct(user, &resp)
if err != nil {
return nil, errors.New("to struct error")
}
return
}
@@ -31,7 +31,7 @@ func NewGetUserInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUs
}
func (l *GetUserInfoLogic) GetUserInfo(req *types.GetUserInfoReq) (resp types.UserInfo, err error) {
// todo: add your logic here and delete this line
pbUser, err := l.svcCtx.UserRpc.GetUsersById(l.ctx, &usercenter.GetUsersByIdReq{
Id: req.UserId,
})
@@ -30,7 +30,7 @@ func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic
}
func (l *LoginLogic) Login(req *types.LoginReq) (resp *types.LoginResp, err error) {
if len(req.Username) < 3 || len(req.Password) > 20 || len(req.Password) < 8 || len(req.Password) > 20 {
if len(req.Username) < 3 || len(req.Password) < 8 || len(req.Password) > 20 {
return nil, errors.New("the information is illegal")
}
@@ -0,0 +1,55 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package user
import (
"context"
"errors"
"juwan-backend/app/users/api/internal/contextx"
"juwan-backend/app/users/rpc/usercenter"
"juwan-backend/common/converter"
"juwan-backend/app/users/api/internal/svc"
"juwan-backend/app/users/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type UpdateMeLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// 更改当前登录用户信息
func NewUpdateMeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateMeLogic {
return &UpdateMeLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *UpdateMeLogic) UpdateMe(req *types.UpdateUserInfoReq) (resp *types.UserInfo, err error) {
userId, err := contextx.UserIDFrom(l.ctx)
if err != nil {
return nil, err
}
res, err := l.svcCtx.UserRpc.UpdateUsers(l.ctx, &usercenter.UpdateUsersReq{
Id: userId,
Nickname: req.Nickname,
Avatar: req.Avatar,
Bio: req.Bio,
VerifiedRoles: nil,
})
if err != nil {
return nil, errors.New("update info failed")
}
err = converter.StructToStruct(res, &resp)
if err != nil {
logx.Errorf("unmarshal user info failed, err:%v.", err)
return nil, errors.New("unmarshal user info failed")
}
return
}
@@ -0,0 +1,58 @@
// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.2
package user
import (
"context"
"errors"
"juwan-backend/app/users/api/internal/contextx"
"juwan-backend/app/users/rpc/usercenter"
"juwan-backend/common/utils"
"juwan-backend/app/users/api/internal/svc"
"juwan-backend/app/users/api/internal/types"
"github.com/zeromicro/go-zero/core/logx"
)
type UpdatePasswordByVcodeLogic struct {
logx.Logger
ctx context.Context
svcCtx *svc.ServiceContext
}
// 修改密码-使用验证码
func NewUpdatePasswordByVcodeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdatePasswordByVcodeLogic {
return &UpdatePasswordByVcodeLogic{
Logger: logx.WithContext(ctx),
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *UpdatePasswordByVcodeLogic) UpdatePasswordByVcode(req *types.ResetPasswordByVcode) (resp *types.EmptyResp, err error) {
// todo: add your logic here and delete this line
requestId, err := contextx.RequestIdFrom(l.ctx)
if err != nil {
logx.Errorf("get request id from context failed, err:%v.", err)
return nil, errors.New("bad request")
}
hashedPassword, err := utils.HashPassword(req.Password)
if err != nil {
logx.Errorf("hash password failed, err:%v.", err)
return nil, errors.New("bad password")
}
_, err = l.svcCtx.UserRpc.ResetPassword(l.ctx, &usercenter.ResetPasswordReq{
NewPassword: hashedPassword,
Email: req.Email,
RequestId: requestId,
Vcode: req.Vcode,
})
if err != nil {
logx.Errorf("reset password failed, err:%v.", err)
return nil, errors.New("reset password failed")
}
return
}
@@ -5,6 +5,10 @@ package user
import (
"context"
"errors"
"juwan-backend/app/users/api/internal/contextx"
"juwan-backend/app/users/rpc/usercenter"
"juwan-backend/common/utils"
"juwan-backend/app/users/api/internal/svc"
"juwan-backend/app/users/api/internal/types"
@@ -12,6 +16,8 @@ import (
"github.com/zeromicro/go-zero/core/logx"
)
var ChangeUserPassFailed = errors.New("change user pass failed")
type UpdatePasswordLogic struct {
logx.Logger
ctx context.Context
@@ -29,6 +35,38 @@ func NewUpdatePasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Up
func (l *UpdatePasswordLogic) UpdatePassword(req *types.UpdatePasswordReq) (resp *types.UpdatePasswordResp, err error) {
// todo: add your logic here and delete this line
userId, err := contextx.UserIDFrom(l.ctx)
if err != nil {
logx.Errorf("get user id from context failed, err:%v.", err)
return nil, ChangeUserPassFailed
}
user, err := l.svcCtx.UserRpc.GetUsersById(l.ctx, &usercenter.GetUsersByIdReq{
Id: userId,
})
if err != nil {
logx.Errorf("get user info failed, err:%v.", err)
return nil, ChangeUserPassFailed
}
oldPasswd, err := utils.HashPassword(req.OldPassword)
if err != nil {
logx.Errorf("hash old password failed, err:%v.", err)
return nil, ChangeUserPassFailed
}
if oldPasswd != user.Users.PasswordHash {
return nil, ChangeUserPassFailed
}
_, err = l.svcCtx.UserRpc.UpdateUsers(l.ctx, &usercenter.UpdateUsersReq{
Id: userId,
Username: &user.Users.Username,
PasswordHash: &req.NewPassword,
})
if err != nil {
logx.Errorf("update user password failed, err:%v.", err)
return nil, ChangeUserPassFailed
}
return
}
@@ -5,6 +5,9 @@ package user
import (
"context"
"errors"
"juwan-backend/app/users/api/internal/contextx"
"juwan-backend/app/users/rpc/usercenter"
"juwan-backend/app/users/api/internal/svc"
"juwan-backend/app/users/api/internal/types"
@@ -28,7 +31,18 @@ func NewUpdateUserInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Up
}
func (l *UpdateUserInfoLogic) UpdateUserInfo(req *types.UpdateUserInfoReq) (resp *types.UpdateUserInfoResp, err error) {
// todo: add your logic here and delete this line
userId, err := contextx.UserIDFrom(l.ctx)
if err != nil {
return nil, errors.New("user not found")
}
_, err = l.svcCtx.UserRpc.UpdateUsers(l.ctx, &usercenter.UpdateUsersReq{
Id: userId,
Nickname: req.Nickname,
Avatar: req.Avatar,
Bio: req.Bio,
})
if err != nil {
return nil, errors.New("update user info failed")
}
return
}
+12 -4
View File
@@ -3,6 +3,9 @@
package types
type EmptyResp struct {
}
type ErrorResp struct {
Code int `json:"code"`
Message string `json:"message"`
@@ -49,6 +52,12 @@ type RegisterResp struct {
Message string `json:"message"`
}
type ResetPasswordByVcode struct {
Email string `json:"email"`
Password string `json:"password"`
Vcode string `json:"vcode"`
}
type UpdatePasswordReq struct {
UserId int64 `path:"userId" binding:"required,gt=0"`
OldPassword string `json:"oldPassword" binding:"required"`
@@ -60,10 +69,9 @@ type UpdatePasswordResp struct {
}
type UpdateUserInfoReq struct {
UserId int64 `path:"userId" binding:"required,gt=0"`
Email string `json:"email" binding:"omitempty,email"`
Phone string `json:"phone" binding:"omitempty,len=11"`
Avatar string `json:"avatar" binding:"omitempty,url"`
Nickname *string `json:"nickname,omitempty"`
Avatar *string `json:"avatar,omitempty"`
Bio *string `json:"bio,omitempty"`
}
type UpdateUserInfoResp struct {
@@ -2,6 +2,7 @@ package logic
import (
"context"
"juwan-backend/app/users/rpc/internal/models/users"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
@@ -25,9 +26,10 @@ func NewGetUserByUsernameLogic(ctx context.Context, svcCtx *svc.ServiceContext)
}
func (l *GetUserByUsernameLogic) GetUserByUsername(in *pb.GetUserByUsernameReq) (*pb.GetUserByUsernameResp, error) {
user, err := l.svcCtx.UsersModelRO.FindOneByUsername(l.ctx, in.Username)
pbUsers := &pb.Users{}
converter.StructToStruct(user, pbUsers)
//user, err := l.svcCtx.UsersModelRO.FindOneByUsername(l.ctx, in.Username)
user, err := l.svcCtx.UsersModelRO.Query().Where(users.UsernameEQ(in.Username)).First(l.ctx)
if err == nil || user != nil {
return &pb.GetUserByUsernameResp{
Users: pbUsers,
@@ -36,5 +38,10 @@ func (l *GetUserByUsernameLogic) GetUserByUsername(in *pb.GetUserByUsernameReq)
if err.Error() != "not found" {
return nil, err
}
err = converter.StructToStruct(user, pbUsers)
if err != nil {
return nil, err
}
return &pb.GetUserByUsernameResp{}, nil
}
@@ -2,6 +2,7 @@ package logic
import (
"context"
"juwan-backend/app/users/rpc/internal/models/users"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
@@ -26,12 +27,16 @@ func NewGetUsersByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetU
func (l *GetUsersByIdLogic) GetUsersById(in *pb.GetUsersByIdReq) (*pb.GetUsersByIdResp, error) {
// todo: add your logic here and delete this line
user, err := l.svcCtx.UsersModelRO.FindOne(l.ctx, in.Id)
//user, err := l.svcCtx.UsersModelRO.FindOne(l.ctx, in.Id)
user, err := l.svcCtx.UsersModelRO.Query().Where(users.IDEQ(in.Id)).All(l.ctx)
if err != nil {
return nil, err
}
pbUser := &pb.Users{}
converter.StructToStruct(&user, &pbUser)
err = converter.StructToStruct(&user, &pbUser)
if err != nil {
return nil, err
}
return &pb.GetUsersByIdResp{Users: pbUser}, nil
}
+9 -5
View File
@@ -3,6 +3,7 @@ package logic
import (
"context"
"errors"
"juwan-backend/app/users/rpc/internal/models/users"
"juwan-backend/app/users/rpc/internal/svc"
utils2 "juwan-backend/app/users/rpc/internal/utils"
"juwan-backend/app/users/rpc/pb"
@@ -11,6 +12,8 @@ import (
"github.com/zeromicro/go-zero/core/logx"
)
//var UserNotFound = errors.New("user not Found")
type LoginLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
@@ -26,23 +29,24 @@ func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic
}
func (l *LoginLogic) Login(in *pb.LoginReq) (*pb.LoginResp, error) {
user, err := l.svcCtx.UsersModelRO.FindOneByUsername(l.ctx, in.Username)
//user, err := l.svcCtx.UsersModelRO.FindOneByUsername(l.ctx, in.Username)
user, err := l.svcCtx.UsersModelRO.Query().Where(users.NicknameEQ(in.Username)).First(l.ctx)
if err != nil {
logx.WithContext(l.ctx).Errorf("LoginLogic.Login error:%v", err)
return nil, err
}
logx.Infof("user:%v", user)
if !utils.VerifyPassword(user.Passwd, in.Passwd) {
if !utils.VerifyPassword(user.PasswordHash, in.Passwd) {
logx.WithContext(l.ctx).Errorf("User %s Login failed", user.Username)
return nil, errors.New("incorrect password")
}
token, err := l.svcCtx.JwtManager.New(l.ctx, &utils2.TokenPayload{
UserId: user.UserId,
UserId: user.ID,
IsAdmin: false,
})
if err != nil {
logx.Errorf("LoginLogic.Login gen jwt for user %v error:%v", user.UserId, err)
logx.Errorf("LoginLogic.Login gen jwt for user %v error:%v", user.ID, err)
return nil, err
}
@@ -50,6 +54,6 @@ func (l *LoginLogic) Login(in *pb.LoginReq) (*pb.LoginResp, error) {
Token: token,
Username: user.Username,
Email: user.Email,
Id: user.UserId,
Id: user.ID,
}, nil
}
+15 -21
View File
@@ -6,13 +6,12 @@ import (
"encoding/hex"
"errors"
"fmt"
"strconv"
"strings"
"juwan-backend/app/snowflake/rpc/snowflake"
"juwan-backend/app/users/rpc/internal/models"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
"juwan-backend/common/redisx"
"strconv"
"strings"
"github.com/zeromicro/go-zero/core/logx"
)
@@ -44,13 +43,12 @@ func mustNewRandomNickname() string {
}
func (l *RegisterLogic) Register(in *pb.RegisterReq) (*pb.RegisterResp, error) {
// todo: add your logic here and delete this line
if in.Phone == "" || in.Username == "" || in.Passwd == "" {
if in.Username == "" || in.Passwd == "" {
logx.Error("invalid input")
return nil, errors.New("invalid input")
}
redisKey := fmt.Sprintf("vcode:%s:%s:%s", in.RequestId, "register", in.Email)
redisKey := fmt.Sprintf(redisx.VCODE_KEY_PREFIX, in.RequestId, redisx.SCENE_REG, in.Email)
vcode, err := l.svcCtx.RedisCluster.Get(l.ctx, redisKey).Result()
logx.Infof("vcode:%s, err:%v", vcode, err)
if err != nil {
@@ -69,21 +67,17 @@ func (l *RegisterLogic) Register(in *pb.RegisterReq) (*pb.RegisterResp, error) {
return nil, errors.New("generate user ID failed")
}
user := models.Users{
UserId: resp.Id,
Username: in.Username,
Nickname: mustNewRandomNickname(),
Passwd: in.Passwd,
Phone: in.Phone,
Email: in.Email,
RoleType: 0,
IsVerified: false,
}
_, err = l.svcCtx.UsersModelRW.Insert(l.ctx, &user)
_, err = l.svcCtx.UsersModelRW.Create().
SetID(resp.Id).
SetUsername(in.Username).
SetPasswordHash(in.Passwd).
SetPhone(in.Phone).
SetEmail(in.Email).
SetNickname(mustNewRandomNickname()).
Save(l.ctx)
if err != nil {
logx.Error("failed to create user: ", err)
return nil, errors.New("failed to create user")
logx.Errorf("create user err:%v", err)
return nil, err
}
return &pb.RegisterResp{
@@ -0,0 +1,49 @@
package logic
import (
"context"
"errors"
"fmt"
"juwan-backend/app/users/rpc/internal/models/users"
"juwan-backend/common/redisx"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type ResetPasswordLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewResetPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ResetPasswordLogic {
return &ResetPasswordLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *ResetPasswordLogic) ResetPassword(in *pb.ResetPasswordReq) (*pb.ResetPasswordResp, error) {
// todo: add your logic here and delete this line
redisKey := fmt.Sprintf(redisx.VCODE_KEY_PREFIX, in.RequestId, redisx.SCENE_REG, in.Email)
vcode, err := l.svcCtx.RedisCluster.Get(l.ctx, redisKey).Result()
if err != nil {
logx.Errorf("get reset password vcode from redis failed, err:%v.", err)
return nil, err
}
if vcode != in.Vcode {
return nil, errors.New(fmt.Sprintf("user %v reset password failed, invalid vcode.", in.Email))
}
err = l.svcCtx.UsersModelRW.Update().Where(users.EmailEQ(in.Email)).
SetPasswordHash(in.NewPassword).
Exec(l.ctx)
if err != nil {
logx.Errorf("reset password failed, err:%v.", err)
return nil, errors.New("reset password failed")
}
return &pb.ResetPasswordResp{}, nil
}
@@ -2,10 +2,14 @@ package logic
import (
"context"
"encoding/json"
"errors"
"juwan-backend/app/users/rpc/internal/models"
"juwan-backend/app/users/rpc/internal/models/users"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
"github.com/jinzhu/copier"
"github.com/zeromicro/go-zero/core/logx"
)
@@ -23,8 +27,58 @@ func NewSearchUsersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Searc
}
}
func (l *SearchUsersLogic) SearchUsers(in *pb.SearchUsersReq) (*pb.SearchUsersResp, error) {
// todo: add your logic here and delete this line
var SearUsersErr = errors.New("search users failed")
return &pb.SearchUsersResp{}, nil
func (l *SearchUsersLogic) SearchUsers(in *pb.SearchUsersReq) (out *pb.SearchUsersResp, err error) {
user, err := l.svcCtx.UsersModelRO.Query().
Where(users.Or(
users.UsernameContainsFold(*in.Username),
users.NicknameContainsFold(*in.Username),
users.EmailContainsFold(*in.Username),
users.CurrentRole(*in.CurrentRole),
)).
All(l.ctx)
if err != nil {
logx.Errorf("search users failed, err:%v.", err)
return nil, SearUsersErr
}
out = &pb.SearchUsersResp{
Users: ConvertEntUsersToProto(user),
}
return
}
func ConvertEntUserToProto(entUser *models.Users) *pb.Users {
if entUser == nil {
return nil
}
out := &pb.Users{}
err := copier.Copy(out, entUser)
if err != nil {
return out
}
out.CreatedAt = entUser.CreatedAt.Unix()
out.UpdatedAt = entUser.UpdatedAt.Unix()
if !entUser.DeletedAt.IsZero() {
out.DeletedAt = entUser.DeletedAt.Unix()
}
verificationStatus, err := json.Marshal(entUser.VerificationStatus)
if err != nil {
return nil
}
out.VerificationStatus = string(verificationStatus)
out.VerifiedRoles = entUser.VerifiedRoles
out.PasswordHash = "" // 手动清空敏感字段
return out
}
func ConvertEntUsersToProto(users []*models.Users) []*pb.Users {
list := make([]*pb.Users, 0, len(users))
for _, u := range users {
list = append(list, ConvertEntUserToProto(u))
}
return list
}
@@ -2,7 +2,6 @@ package logic
import (
"context"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
@@ -24,7 +23,18 @@ func NewUpdateUsersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Updat
}
func (l *UpdateUsersLogic) UpdateUsers(in *pb.UpdateUsersReq) (*pb.UpdateUsersResp, error) {
// todo: add your logic here and delete this line
updater := l.svcCtx.UsersModelRW.UpdateOneID(in.Id).
SetNillableNickname(in.Nickname).
SetNillableAvatar(in.Avatar).
SetNillableBio(in.Bio).
SetNillableCurrentRole(in.CurrentRole).
SetNillablePasswordHash(in.PasswordHash)
if len(in.VerifiedRoles) > 0 {
updater.SetVerifiedRoles(in.VerifiedRoles)
}
err := updater.Exec(l.ctx)
if err != nil {
return nil, err
}
return &pb.UpdateUsersResp{}, nil
}
@@ -2,6 +2,7 @@ package logic
import (
"context"
"juwan-backend/app/users/rpc/internal/models/users"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
@@ -31,7 +32,8 @@ func (l *ValidateTokenLogic) ValidateToken(in *pb.ValidateTokenReq) (*pb.Validat
if err != nil {
return nil, err
}
users, err := l.svcCtx.UsersModelRO.FindOne(l.ctx, in.UserId)
//users, err := l.svcCtx.UsersModelRO.FindOne(l.ctx, in.UserId)
user, err := l.svcCtx.UsersModelRO.Query().Where(users.IDEQ(in.UserId)).First(l.ctx)
if err != nil {
return nil, err
}
@@ -40,6 +42,6 @@ func (l *ValidateTokenLogic) ValidateToken(in *pb.ValidateTokenReq) (*pb.Validat
Valid: true,
Message: "OK",
UserId: in.UserId,
RoleType: users.RoleType,
RoleType: user.CurrentRole,
}, nil
}
+341
View File
@@ -0,0 +1,341 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"errors"
"fmt"
"log"
"reflect"
"juwan-backend/app/users/rpc/internal/models/migrate"
"juwan-backend/app/users/rpc/internal/models/users"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
)
// Client is the client that holds all ent builders.
type Client struct {
config
// Schema is the client for creating, migrating and dropping schema.
Schema *migrate.Schema
// Users is the client for interacting with the Users builders.
Users *UsersClient
}
// NewClient creates a new client configured with the given options.
func NewClient(opts ...Option) *Client {
client := &Client{config: newConfig(opts...)}
client.init()
return client
}
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
c.Users = NewUsersClient(c.config)
}
type (
// config is the configuration for the client and its builder.
config struct {
// driver used for executing database requests.
driver dialect.Driver
// debug enable a debug logging.
debug bool
// log used for logging on debug mode.
log func(...any)
// hooks to execute on mutations.
hooks *hooks
// interceptors to execute on queries.
inters *inters
}
// Option function to configure the client.
Option func(*config)
)
// newConfig creates a new config for the client.
func newConfig(opts ...Option) config {
cfg := config{log: log.Println, hooks: &hooks{}, inters: &inters{}}
cfg.options(opts...)
return cfg
}
// options applies the options on the config object.
func (c *config) options(opts ...Option) {
for _, opt := range opts {
opt(c)
}
if c.debug {
c.driver = dialect.Debug(c.driver, c.log)
}
}
// Debug enables debug logging on the ent.Driver.
func Debug() Option {
return func(c *config) {
c.debug = true
}
}
// Log sets the logging function for debug mode.
func Log(fn func(...any)) Option {
return func(c *config) {
c.log = fn
}
}
// Driver configures the client driver.
func Driver(driver dialect.Driver) Option {
return func(c *config) {
c.driver = driver
}
}
// Open opens a database/sql.DB specified by the driver name and
// the data source name, and returns a new client attached to it.
// Optional parameters can be added for configuring the client.
func Open(driverName, dataSourceName string, options ...Option) (*Client, error) {
switch driverName {
case dialect.MySQL, dialect.Postgres, dialect.SQLite:
drv, err := sql.Open(driverName, dataSourceName)
if err != nil {
return nil, err
}
return NewClient(append(options, Driver(drv))...), nil
default:
return nil, fmt.Errorf("unsupported driver: %q", driverName)
}
}
// ErrTxStarted is returned when trying to start a new transaction from a transactional client.
var ErrTxStarted = errors.New("models: cannot start a transaction within a transaction")
// Tx returns a new transactional client. The provided context
// is used until the transaction is committed or rolled back.
func (c *Client) Tx(ctx context.Context) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, ErrTxStarted
}
tx, err := newTx(ctx, c.driver)
if err != nil {
return nil, fmt.Errorf("models: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = tx
return &Tx{
ctx: ctx,
config: cfg,
Users: NewUsersClient(cfg),
}, nil
}
// BeginTx returns a transactional client with specified options.
func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error) {
if _, ok := c.driver.(*txDriver); ok {
return nil, errors.New("ent: cannot start a transaction within a transaction")
}
tx, err := c.driver.(interface {
BeginTx(context.Context, *sql.TxOptions) (dialect.Tx, error)
}).BeginTx(ctx, opts)
if err != nil {
return nil, fmt.Errorf("ent: starting a transaction: %w", err)
}
cfg := c.config
cfg.driver = &txDriver{tx: tx, drv: c.driver}
return &Tx{
ctx: ctx,
config: cfg,
Users: NewUsersClient(cfg),
}, nil
}
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// Users.
// Query().
// Count(ctx)
func (c *Client) Debug() *Client {
if c.debug {
return c
}
cfg := c.config
cfg.driver = dialect.Debug(c.driver, c.log)
client := &Client{config: cfg}
client.init()
return client
}
// Close closes the database connection and prevents new queries from starting.
func (c *Client) Close() error {
return c.driver.Close()
}
// Use adds the mutation hooks to all the entity clients.
// In order to add hooks to a specific client, call: `client.Node.Use(...)`.
func (c *Client) Use(hooks ...Hook) {
c.Users.Use(hooks...)
}
// Intercept adds the query interceptors to all the entity clients.
// In order to add interceptors to a specific client, call: `client.Node.Intercept(...)`.
func (c *Client) Intercept(interceptors ...Interceptor) {
c.Users.Intercept(interceptors...)
}
// Mutate implements the ent.Mutator interface.
func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
switch m := m.(type) {
case *UsersMutation:
return c.Users.mutate(ctx, m)
default:
return nil, fmt.Errorf("models: unknown mutation type %T", m)
}
}
// UsersClient is a client for the Users schema.
type UsersClient struct {
config
}
// NewUsersClient returns a client for the Users from the given config.
func NewUsersClient(c config) *UsersClient {
return &UsersClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `users.Hooks(f(g(h())))`.
func (c *UsersClient) Use(hooks ...Hook) {
c.hooks.Users = append(c.hooks.Users, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `users.Intercept(f(g(h())))`.
func (c *UsersClient) Intercept(interceptors ...Interceptor) {
c.inters.Users = append(c.inters.Users, interceptors...)
}
// Create returns a builder for creating a Users entity.
func (c *UsersClient) Create() *UsersCreate {
mutation := newUsersMutation(c.config, OpCreate)
return &UsersCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Users entities.
func (c *UsersClient) CreateBulk(builders ...*UsersCreate) *UsersCreateBulk {
return &UsersCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *UsersClient) MapCreateBulk(slice any, setFunc func(*UsersCreate, int)) *UsersCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &UsersCreateBulk{err: fmt.Errorf("calling to UsersClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*UsersCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &UsersCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Users.
func (c *UsersClient) Update() *UsersUpdate {
mutation := newUsersMutation(c.config, OpUpdate)
return &UsersUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *UsersClient) UpdateOne(_m *Users) *UsersUpdateOne {
mutation := newUsersMutation(c.config, OpUpdateOne, withUsers(_m))
return &UsersUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *UsersClient) UpdateOneID(id int64) *UsersUpdateOne {
mutation := newUsersMutation(c.config, OpUpdateOne, withUsersID(id))
return &UsersUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Users.
func (c *UsersClient) Delete() *UsersDelete {
mutation := newUsersMutation(c.config, OpDelete)
return &UsersDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *UsersClient) DeleteOne(_m *Users) *UsersDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *UsersClient) DeleteOneID(id int64) *UsersDeleteOne {
builder := c.Delete().Where(users.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &UsersDeleteOne{builder}
}
// Query returns a query builder for Users.
func (c *UsersClient) Query() *UsersQuery {
return &UsersQuery{
config: c.config,
ctx: &QueryContext{Type: TypeUsers},
inters: c.Interceptors(),
}
}
// Get returns a Users entity by its id.
func (c *UsersClient) Get(ctx context.Context, id int64) (*Users, error) {
return c.Query().Where(users.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *UsersClient) GetX(ctx context.Context, id int64) *Users {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *UsersClient) Hooks() []Hook {
return c.hooks.Users
}
// Interceptors returns the client interceptors.
func (c *UsersClient) Interceptors() []Interceptor {
return c.inters.Users
}
func (c *UsersClient) mutate(ctx context.Context, m *UsersMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&UsersCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&UsersUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&UsersUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&UsersDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("models: unknown Users mutation op: %q", m.Op())
}
}
// hooks and interceptors per client, for fast access.
type (
hooks struct {
Users []ent.Hook
}
inters struct {
Users []ent.Interceptor
}
)
+608
View File
@@ -0,0 +1,608 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"errors"
"fmt"
"juwan-backend/app/users/rpc/internal/models/users"
"reflect"
"sync"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
)
// ent aliases to avoid import conflicts in user's code.
type (
Op = ent.Op
Hook = ent.Hook
Value = ent.Value
Query = ent.Query
QueryContext = ent.QueryContext
Querier = ent.Querier
QuerierFunc = ent.QuerierFunc
Interceptor = ent.Interceptor
InterceptFunc = ent.InterceptFunc
Traverser = ent.Traverser
TraverseFunc = ent.TraverseFunc
Policy = ent.Policy
Mutator = ent.Mutator
Mutation = ent.Mutation
MutateFunc = ent.MutateFunc
)
type clientCtxKey struct{}
// FromContext returns a Client stored inside a context, or nil if there isn't one.
func FromContext(ctx context.Context) *Client {
c, _ := ctx.Value(clientCtxKey{}).(*Client)
return c
}
// NewContext returns a new context with the given Client attached.
func NewContext(parent context.Context, c *Client) context.Context {
return context.WithValue(parent, clientCtxKey{}, c)
}
type txCtxKey struct{}
// TxFromContext returns a Tx stored inside a context, or nil if there isn't one.
func TxFromContext(ctx context.Context) *Tx {
tx, _ := ctx.Value(txCtxKey{}).(*Tx)
return tx
}
// NewTxContext returns a new context with the given Tx attached.
func NewTxContext(parent context.Context, tx *Tx) context.Context {
return context.WithValue(parent, txCtxKey{}, tx)
}
// OrderFunc applies an ordering on the sql selector.
// Deprecated: Use Asc/Desc functions or the package builders instead.
type OrderFunc func(*sql.Selector)
var (
initCheck sync.Once
columnCheck sql.ColumnCheck
)
// checkColumn checks if the column exists in the given table.
func checkColumn(t, c string) error {
initCheck.Do(func() {
columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
users.Table: users.ValidColumn,
})
})
return columnCheck(t, c)
}
// Asc applies the given fields in ASC order.
func Asc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("models: %w", err)})
}
s.OrderBy(sql.Asc(s.C(f)))
}
}
}
// Desc applies the given fields in DESC order.
func Desc(fields ...string) func(*sql.Selector) {
return func(s *sql.Selector) {
for _, f := range fields {
if err := checkColumn(s.TableName(), f); err != nil {
s.AddError(&ValidationError{Name: f, err: fmt.Errorf("models: %w", err)})
}
s.OrderBy(sql.Desc(s.C(f)))
}
}
}
// AggregateFunc applies an aggregation step on the group-by traversal/selector.
type AggregateFunc func(*sql.Selector) string
// As is a pseudo aggregation function for renaming another other functions with custom names. For example:
//
// GroupBy(field1, field2).
// Aggregate(models.As(models.Sum(field1), "sum_field1"), (models.As(models.Sum(field2), "sum_field2")).
// Scan(ctx, &v)
func As(fn AggregateFunc, end string) AggregateFunc {
return func(s *sql.Selector) string {
return sql.As(fn(s), end)
}
}
// Count applies the "count" aggregation function on each group.
func Count() AggregateFunc {
return func(s *sql.Selector) string {
return sql.Count("*")
}
}
// Max applies the "max" aggregation function on the given field of each group.
func Max(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)})
return ""
}
return sql.Max(s.C(field))
}
}
// Mean applies the "mean" aggregation function on the given field of each group.
func Mean(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)})
return ""
}
return sql.Avg(s.C(field))
}
}
// Min applies the "min" aggregation function on the given field of each group.
func Min(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)})
return ""
}
return sql.Min(s.C(field))
}
}
// Sum applies the "sum" aggregation function on the given field of each group.
func Sum(field string) AggregateFunc {
return func(s *sql.Selector) string {
if err := checkColumn(s.TableName(), field); err != nil {
s.AddError(&ValidationError{Name: field, err: fmt.Errorf("models: %w", err)})
return ""
}
return sql.Sum(s.C(field))
}
}
// ValidationError returns when validating a field or edge fails.
type ValidationError struct {
Name string // Field or edge name.
err error
}
// Error implements the error interface.
func (e *ValidationError) Error() string {
return e.err.Error()
}
// Unwrap implements the errors.Wrapper interface.
func (e *ValidationError) Unwrap() error {
return e.err
}
// IsValidationError returns a boolean indicating whether the error is a validation error.
func IsValidationError(err error) bool {
if err == nil {
return false
}
var e *ValidationError
return errors.As(err, &e)
}
// NotFoundError returns when trying to fetch a specific entity and it was not found in the database.
type NotFoundError struct {
label string
}
// Error implements the error interface.
func (e *NotFoundError) Error() string {
return "models: " + e.label + " not found"
}
// IsNotFound returns a boolean indicating whether the error is a not found error.
func IsNotFound(err error) bool {
if err == nil {
return false
}
var e *NotFoundError
return errors.As(err, &e)
}
// MaskNotFound masks not found error.
func MaskNotFound(err error) error {
if IsNotFound(err) {
return nil
}
return err
}
// NotSingularError returns when trying to fetch a singular entity and more then one was found in the database.
type NotSingularError struct {
label string
}
// Error implements the error interface.
func (e *NotSingularError) Error() string {
return "models: " + e.label + " not singular"
}
// IsNotSingular returns a boolean indicating whether the error is a not singular error.
func IsNotSingular(err error) bool {
if err == nil {
return false
}
var e *NotSingularError
return errors.As(err, &e)
}
// NotLoadedError returns when trying to get a node that was not loaded by the query.
type NotLoadedError struct {
edge string
}
// Error implements the error interface.
func (e *NotLoadedError) Error() string {
return "models: " + e.edge + " edge was not loaded"
}
// IsNotLoaded returns a boolean indicating whether the error is a not loaded error.
func IsNotLoaded(err error) bool {
if err == nil {
return false
}
var e *NotLoadedError
return errors.As(err, &e)
}
// ConstraintError returns when trying to create/update one or more entities and
// one or more of their constraints failed. For example, violation of edge or
// field uniqueness.
type ConstraintError struct {
msg string
wrap error
}
// Error implements the error interface.
func (e ConstraintError) Error() string {
return "models: constraint failed: " + e.msg
}
// Unwrap implements the errors.Wrapper interface.
func (e *ConstraintError) Unwrap() error {
return e.wrap
}
// IsConstraintError returns a boolean indicating whether the error is a constraint failure.
func IsConstraintError(err error) bool {
if err == nil {
return false
}
var e *ConstraintError
return errors.As(err, &e)
}
// selector embedded by the different Select/GroupBy builders.
type selector struct {
label string
flds *[]string
fns []AggregateFunc
scan func(context.Context, any) error
}
// ScanX is like Scan, but panics if an error occurs.
func (s *selector) ScanX(ctx context.Context, v any) {
if err := s.scan(ctx, v); err != nil {
panic(err)
}
}
// Strings returns list of strings from a selector. It is only allowed when selecting one field.
func (s *selector) Strings(ctx context.Context) ([]string, error) {
if len(*s.flds) > 1 {
return nil, errors.New("models: Strings is not achievable when selecting more than 1 field")
}
var v []string
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// StringsX is like Strings, but panics if an error occurs.
func (s *selector) StringsX(ctx context.Context) []string {
v, err := s.Strings(ctx)
if err != nil {
panic(err)
}
return v
}
// String returns a single string from a selector. It is only allowed when selecting one field.
func (s *selector) String(ctx context.Context) (_ string, err error) {
var v []string
if v, err = s.Strings(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("models: Strings returned %d results when one was expected", len(v))
}
return
}
// StringX is like String, but panics if an error occurs.
func (s *selector) StringX(ctx context.Context) string {
v, err := s.String(ctx)
if err != nil {
panic(err)
}
return v
}
// Ints returns list of ints from a selector. It is only allowed when selecting one field.
func (s *selector) Ints(ctx context.Context) ([]int, error) {
if len(*s.flds) > 1 {
return nil, errors.New("models: Ints is not achievable when selecting more than 1 field")
}
var v []int
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// IntsX is like Ints, but panics if an error occurs.
func (s *selector) IntsX(ctx context.Context) []int {
v, err := s.Ints(ctx)
if err != nil {
panic(err)
}
return v
}
// Int returns a single int from a selector. It is only allowed when selecting one field.
func (s *selector) Int(ctx context.Context) (_ int, err error) {
var v []int
if v, err = s.Ints(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("models: Ints returned %d results when one was expected", len(v))
}
return
}
// IntX is like Int, but panics if an error occurs.
func (s *selector) IntX(ctx context.Context) int {
v, err := s.Int(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64s returns list of float64s from a selector. It is only allowed when selecting one field.
func (s *selector) Float64s(ctx context.Context) ([]float64, error) {
if len(*s.flds) > 1 {
return nil, errors.New("models: Float64s is not achievable when selecting more than 1 field")
}
var v []float64
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// Float64sX is like Float64s, but panics if an error occurs.
func (s *selector) Float64sX(ctx context.Context) []float64 {
v, err := s.Float64s(ctx)
if err != nil {
panic(err)
}
return v
}
// Float64 returns a single float64 from a selector. It is only allowed when selecting one field.
func (s *selector) Float64(ctx context.Context) (_ float64, err error) {
var v []float64
if v, err = s.Float64s(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("models: Float64s returned %d results when one was expected", len(v))
}
return
}
// Float64X is like Float64, but panics if an error occurs.
func (s *selector) Float64X(ctx context.Context) float64 {
v, err := s.Float64(ctx)
if err != nil {
panic(err)
}
return v
}
// Bools returns list of bools from a selector. It is only allowed when selecting one field.
func (s *selector) Bools(ctx context.Context) ([]bool, error) {
if len(*s.flds) > 1 {
return nil, errors.New("models: Bools is not achievable when selecting more than 1 field")
}
var v []bool
if err := s.scan(ctx, &v); err != nil {
return nil, err
}
return v, nil
}
// BoolsX is like Bools, but panics if an error occurs.
func (s *selector) BoolsX(ctx context.Context) []bool {
v, err := s.Bools(ctx)
if err != nil {
panic(err)
}
return v
}
// Bool returns a single bool from a selector. It is only allowed when selecting one field.
func (s *selector) Bool(ctx context.Context) (_ bool, err error) {
var v []bool
if v, err = s.Bools(ctx); err != nil {
return
}
switch len(v) {
case 1:
return v[0], nil
case 0:
err = &NotFoundError{s.label}
default:
err = fmt.Errorf("models: Bools returned %d results when one was expected", len(v))
}
return
}
// BoolX is like Bool, but panics if an error occurs.
func (s *selector) BoolX(ctx context.Context) bool {
v, err := s.Bool(ctx)
if err != nil {
panic(err)
}
return v
}
// withHooks invokes the builder operation with the given hooks, if any.
func withHooks[V Value, M any, PM interface {
*M
Mutation
}](ctx context.Context, exec func(context.Context) (V, error), mutation PM, hooks []Hook) (value V, err error) {
if len(hooks) == 0 {
return exec(ctx)
}
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutationT, ok := any(m).(PM)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
// Set the mutation to the builder.
*mutation = *mutationT
return exec(ctx)
})
for i := len(hooks) - 1; i >= 0; i-- {
if hooks[i] == nil {
return value, fmt.Errorf("ent: uninitialized hook (forgotten import ent/runtime?)")
}
mut = hooks[i](mut)
}
v, err := mut.Mutate(ctx, mutation)
if err != nil {
return value, err
}
nv, ok := v.(V)
if !ok {
return value, fmt.Errorf("unexpected node type %T returned from %T", v, mutation)
}
return nv, nil
}
// setContextOp returns a new context with the given QueryContext attached (including its op) in case it does not exist.
func setContextOp(ctx context.Context, qc *QueryContext, op string) context.Context {
if ent.QueryFromContext(ctx) == nil {
qc.Op = op
ctx = ent.NewQueryContext(ctx, qc)
}
return ctx
}
func querierAll[V Value, Q interface {
sqlAll(context.Context, ...queryHook) (V, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlAll(ctx)
})
}
func querierCount[Q interface {
sqlCount(context.Context) (int, error)
}]() Querier {
return QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
return query.sqlCount(ctx)
})
}
func withInterceptors[V Value](ctx context.Context, q Query, qr Querier, inters []Interceptor) (v V, err error) {
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
rv, err := qr.Query(ctx, q)
if err != nil {
return v, err
}
vt, ok := rv.(V)
if !ok {
return v, fmt.Errorf("unexpected type %T returned from %T. expected type: %T", vt, q, v)
}
return vt, nil
}
func scanWithInterceptors[Q1 ent.Query, Q2 interface {
sqlScan(context.Context, Q1, any) error
}](ctx context.Context, rootQuery Q1, selectOrGroup Q2, inters []Interceptor, v any) error {
rv := reflect.ValueOf(v)
var qr Querier = QuerierFunc(func(ctx context.Context, q Query) (Value, error) {
query, ok := q.(Q1)
if !ok {
return nil, fmt.Errorf("unexpected query type %T", q)
}
if err := selectOrGroup.sqlScan(ctx, query, v); err != nil {
return nil, err
}
if k := rv.Kind(); k == reflect.Pointer && rv.Elem().CanInterface() {
return rv.Elem().Interface(), nil
}
return v, nil
})
for i := len(inters) - 1; i >= 0; i-- {
qr = inters[i].Intercept(qr)
}
vv, err := qr.Query(ctx, rootQuery)
if err != nil {
return err
}
switch rv2 := reflect.ValueOf(vv); {
case rv.IsNil(), rv2.IsNil(), rv.Kind() != reflect.Pointer:
case rv.Type() == rv2.Type():
rv.Elem().Set(rv2.Elem())
case rv.Elem().Type() == rv2.Type():
rv.Elem().Set(rv2)
}
return nil
}
// queryHook describes an internal hook for the different sqlAll methods.
type queryHook func(context.Context, *sqlgraph.QuerySpec)
@@ -0,0 +1,85 @@
// Code generated by ent, DO NOT EDIT.
package enttest
import (
"context"
"juwan-backend/app/users/rpc/internal/models"
// required by schema hooks.
_ "juwan-backend/app/users/rpc/internal/models/runtime"
"juwan-backend/app/users/rpc/internal/models/migrate"
"entgo.io/ent/dialect/sql/schema"
)
type (
// TestingT is the interface that is shared between
// testing.T and testing.B and used by enttest.
TestingT interface {
FailNow()
Error(...any)
}
// Option configures client creation.
Option func(*options)
options struct {
opts []models.Option
migrateOpts []schema.MigrateOption
}
)
// WithOptions forwards options to client creation.
func WithOptions(opts ...models.Option) Option {
return func(o *options) {
o.opts = append(o.opts, opts...)
}
}
// WithMigrateOptions forwards options to auto migration.
func WithMigrateOptions(opts ...schema.MigrateOption) Option {
return func(o *options) {
o.migrateOpts = append(o.migrateOpts, opts...)
}
}
func newOptions(opts []Option) *options {
o := &options{}
for _, opt := range opts {
opt(o)
}
return o
}
// Open calls models.Open and auto-run migration.
func Open(t TestingT, driverName, dataSourceName string, opts ...Option) *models.Client {
o := newOptions(opts)
c, err := models.Open(driverName, dataSourceName, o.opts...)
if err != nil {
t.Error(err)
t.FailNow()
}
migrateSchema(t, c, o)
return c
}
// NewClient calls models.NewClient and auto-run migration.
func NewClient(t TestingT, opts ...Option) *models.Client {
o := newOptions(opts)
c := models.NewClient(o.opts...)
migrateSchema(t, c, o)
return c
}
func migrateSchema(t TestingT, c *models.Client, o *options) {
tables, err := schema.CopyTables(migrate.Tables)
if err != nil {
t.Error(err)
t.FailNow()
}
if err := migrate.Create(context.Background(), c.Schema, tables, o.migrateOpts...); err != nil {
t.Error(err)
t.FailNow()
}
}
@@ -0,0 +1,3 @@
package models
//go:generate go run -mod=mod entgo.io/ent/cmd/ent generate ./schema
+198
View File
@@ -0,0 +1,198 @@
// Code generated by ent, DO NOT EDIT.
package hook
import (
"context"
"fmt"
"juwan-backend/app/users/rpc/internal/models"
)
// The UsersFunc type is an adapter to allow the use of ordinary
// function as Users mutator.
type UsersFunc func(context.Context, *models.UsersMutation) (models.Value, error)
// Mutate calls f(ctx, m).
func (f UsersFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) {
if mv, ok := m.(*models.UsersMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *models.UsersMutation", m)
}
// Condition is a hook condition function.
type Condition func(context.Context, models.Mutation) bool
// And groups conditions with the AND operator.
func And(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m models.Mutation) bool {
if !first(ctx, m) || !second(ctx, m) {
return false
}
for _, cond := range rest {
if !cond(ctx, m) {
return false
}
}
return true
}
}
// Or groups conditions with the OR operator.
func Or(first, second Condition, rest ...Condition) Condition {
return func(ctx context.Context, m models.Mutation) bool {
if first(ctx, m) || second(ctx, m) {
return true
}
for _, cond := range rest {
if cond(ctx, m) {
return true
}
}
return false
}
}
// Not negates a given condition.
func Not(cond Condition) Condition {
return func(ctx context.Context, m models.Mutation) bool {
return !cond(ctx, m)
}
}
// HasOp is a condition testing mutation operation.
func HasOp(op models.Op) Condition {
return func(_ context.Context, m models.Mutation) bool {
return m.Op().Is(op)
}
}
// HasAddedFields is a condition validating `.AddedField` on fields.
func HasAddedFields(field string, fields ...string) Condition {
return func(_ context.Context, m models.Mutation) bool {
if _, exists := m.AddedField(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.AddedField(field); !exists {
return false
}
}
return true
}
}
// HasClearedFields is a condition validating `.FieldCleared` on fields.
func HasClearedFields(field string, fields ...string) Condition {
return func(_ context.Context, m models.Mutation) bool {
if exists := m.FieldCleared(field); !exists {
return false
}
for _, field := range fields {
if exists := m.FieldCleared(field); !exists {
return false
}
}
return true
}
}
// HasFields is a condition validating `.Field` on fields.
func HasFields(field string, fields ...string) Condition {
return func(_ context.Context, m models.Mutation) bool {
if _, exists := m.Field(field); !exists {
return false
}
for _, field := range fields {
if _, exists := m.Field(field); !exists {
return false
}
}
return true
}
}
// If executes the given hook under condition.
//
// hook.If(ComputeAverage, And(HasFields(...), HasAddedFields(...)))
func If(hk models.Hook, cond Condition) models.Hook {
return func(next models.Mutator) models.Mutator {
return models.MutateFunc(func(ctx context.Context, m models.Mutation) (models.Value, error) {
if cond(ctx, m) {
return hk(next).Mutate(ctx, m)
}
return next.Mutate(ctx, m)
})
}
}
// On executes the given hook only for the given operation.
//
// hook.On(Log, models.Delete|models.Create)
func On(hk models.Hook, op models.Op) models.Hook {
return If(hk, HasOp(op))
}
// Unless skips the given hook only for the given operation.
//
// hook.Unless(Log, models.Update|models.UpdateOne)
func Unless(hk models.Hook, op models.Op) models.Hook {
return If(hk, Not(HasOp(op)))
}
// FixedError is a hook returning a fixed error.
func FixedError(err error) models.Hook {
return func(models.Mutator) models.Mutator {
return models.MutateFunc(func(context.Context, models.Mutation) (models.Value, error) {
return nil, err
})
}
}
// Reject returns a hook that rejects all operations that match op.
//
// func (T) Hooks() []models.Hook {
// return []models.Hook{
// Reject(models.Delete|models.Update),
// }
// }
func Reject(op models.Op) models.Hook {
hk := FixedError(fmt.Errorf("%s operation is not allowed", op))
return On(hk, op)
}
// Chain acts as a list of hooks and is effectively immutable.
// Once created, it will always hold the same set of hooks in the same order.
type Chain struct {
hooks []models.Hook
}
// NewChain creates a new chain of hooks.
func NewChain(hooks ...models.Hook) Chain {
return Chain{append([]models.Hook(nil), hooks...)}
}
// Hook chains the list of hooks and returns the final hook.
func (c Chain) Hook() models.Hook {
return func(mutator models.Mutator) models.Mutator {
for i := len(c.hooks) - 1; i >= 0; i-- {
mutator = c.hooks[i](mutator)
}
return mutator
}
}
// Append extends a chain, adding the specified hook
// as the last ones in the mutation flow.
func (c Chain) Append(hooks ...models.Hook) Chain {
newHooks := make([]models.Hook, 0, len(c.hooks)+len(hooks))
newHooks = append(newHooks, c.hooks...)
newHooks = append(newHooks, hooks...)
return Chain{newHooks}
}
// Extend extends a chain, adding the specified chain
// as the last ones in the mutation flow.
func (c Chain) Extend(chain Chain) Chain {
return c.Append(chain.hooks...)
}
@@ -0,0 +1,64 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"context"
"fmt"
"io"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql/schema"
)
var (
// WithGlobalUniqueID sets the universal ids options to the migration.
// If this option is enabled, ent migration will allocate a 1<<32 range
// for the ids of each entity (table).
// Note that this option cannot be applied on tables that already exist.
WithGlobalUniqueID = schema.WithGlobalUniqueID
// WithDropColumn sets the drop column option to the migration.
// If this option is enabled, ent migration will drop old columns
// that were used for both fields and edges. This defaults to false.
WithDropColumn = schema.WithDropColumn
// WithDropIndex sets the drop index option to the migration.
// If this option is enabled, ent migration will drop old indexes
// that were defined in the schema. This defaults to false.
// Note that unique constraints are defined using `UNIQUE INDEX`,
// and therefore, it's recommended to enable this option to get more
// flexibility in the schema changes.
WithDropIndex = schema.WithDropIndex
// WithForeignKeys enables creating foreign-key in schema DDL. This defaults to true.
WithForeignKeys = schema.WithForeignKeys
)
// Schema is the API for creating, migrating and dropping a schema.
type Schema struct {
drv dialect.Driver
}
// NewSchema creates a new schema client.
func NewSchema(drv dialect.Driver) *Schema { return &Schema{drv: drv} }
// Create creates all schema resources.
func (s *Schema) Create(ctx context.Context, opts ...schema.MigrateOption) error {
return Create(ctx, s, Tables, opts...)
}
// Create creates all table resources using the given schema driver.
func Create(ctx context.Context, s *Schema, tables []*schema.Table, opts ...schema.MigrateOption) error {
migrate, err := schema.NewMigrate(s.drv, opts...)
if err != nil {
return fmt.Errorf("ent/migrate: %w", err)
}
return migrate.Create(ctx, tables...)
}
// WriteTo writes the schema changes to w instead of running them against the database.
//
// if err := client.Schema.WriteTo(context.Background(), os.Stdout); err != nil {
// log.Fatal(err)
// }
func (s *Schema) WriteTo(ctx context.Context, w io.Writer, opts ...schema.MigrateOption) error {
return Create(ctx, &Schema{drv: &schema.WriteDriver{Writer: w, Driver: s.drv}}, Tables, opts...)
}
@@ -0,0 +1,42 @@
// Code generated by ent, DO NOT EDIT.
package migrate
import (
"entgo.io/ent/dialect/sql/schema"
"entgo.io/ent/schema/field"
)
var (
// UsersColumns holds the columns for the "users" table.
UsersColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt64, Increment: true},
{Name: "username", Type: field.TypeString, Unique: true},
{Name: "password_hash", Type: field.TypeString},
{Name: "email", Type: field.TypeString, Unique: true},
{Name: "phone", Type: field.TypeString, Unique: true},
{Name: "nickname", Type: field.TypeString},
{Name: "avatar", Type: field.TypeString},
{Name: "bio", Type: field.TypeString},
{Name: "current_role", Type: field.TypeString},
{Name: "verified_roles", Type: field.TypeJSON},
{Name: "verification_status", Type: field.TypeJSON},
{Name: "is_admin", Type: field.TypeBool, Default: false},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "deleted_at", Type: field.TypeTime},
}
// UsersTable holds the schema information for the "users" table.
UsersTable = &schema.Table{
Name: "users",
Columns: UsersColumns,
PrimaryKey: []*schema.Column{UsersColumns[0]},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
UsersTable,
}
)
func init() {
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,10 @@
// Code generated by ent, DO NOT EDIT.
package predicate
import (
"entgo.io/ent/dialect/sql"
)
// Users is the predicate function for users builders.
type Users func(*sql.Selector)
+29
View File
@@ -0,0 +1,29 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"juwan-backend/app/users/rpc/internal/models/schema"
"juwan-backend/app/users/rpc/internal/models/users"
"time"
)
// The init function reads all schema descriptors with runtime code
// (default values, validators, hooks and policies) and stitches it
// to their package variables.
func init() {
usersFields := schema.Users{}.Fields()
_ = usersFields
// usersDescIsAdmin is the schema descriptor for is_admin field.
usersDescIsAdmin := usersFields[11].Descriptor()
// users.DefaultIsAdmin holds the default value on creation for the is_admin field.
users.DefaultIsAdmin = usersDescIsAdmin.Default.(bool)
// usersDescCreatedAt is the schema descriptor for created_at field.
usersDescCreatedAt := usersFields[12].Descriptor()
// users.DefaultCreatedAt holds the default value on creation for the created_at field.
users.DefaultCreatedAt = usersDescCreatedAt.Default.(func() time.Time)
// usersDescUpdatedAt is the schema descriptor for updated_at field.
usersDescUpdatedAt := usersFields[13].Descriptor()
// users.DefaultUpdatedAt holds the default value on creation for the updated_at field.
users.DefaultUpdatedAt = usersDescUpdatedAt.Default.(func() time.Time)
}
@@ -0,0 +1,10 @@
// Code generated by ent, DO NOT EDIT.
package runtime
// The schema-stitching logic is generated in juwan-backend/app/users/rpc/internal/models/runtime.go
const (
Version = "v0.14.5" // Version of ent codegen.
Sum = "h1:Rj2WOYJtCkWyFo6a+5wB3EfBRP0rnx1fMk6gGA0UUe4=" // Sum of ent codegen.
)
@@ -0,0 +1,45 @@
package schema
import (
"time"
"entgo.io/ent"
"entgo.io/ent/schema/field"
)
// Users holds the schema definition for the Users entity.
type Users struct {
ent.Schema
}
type VerificationStatusStruct struct {
Player string `json:"player" validate:"oneof:pending rejected approved"`
Owner string `json:"owner" validate:"oneof:pending rejected approved"`
Consumer string `json:"consumer" validate:"oneof:pending rejected approved"`
}
// Fields of the Users.
func (Users) Fields() []ent.Field {
return []ent.Field{
field.Int64("id").Unique().Immutable(),
field.String("username").Unique(),
field.String("password_hash"),
field.String("email").Unique(),
field.String("phone").Unique(),
field.String("nickname"),
field.String("avatar"),
field.String("bio"),
field.String("current_role"),
field.Strings("verified_roles"),
field.JSON("verificationStatus", VerificationStatusStruct{}),
field.Bool("is_admin").Default(false),
field.Time("created_at").Default(time.Now),
field.Time("updated_at").Default(time.Now),
field.Time("deleted_at"),
}
}
// Edges of the Users.
func (Users) Edges() []ent.Edge {
return nil
}
+210
View File
@@ -0,0 +1,210 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"sync"
"entgo.io/ent/dialect"
)
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// Users is the client for interacting with the Users builders.
Users *UsersClient
// lazily loaded.
client *Client
clientOnce sync.Once
// ctx lives for the life of the transaction. It is
// the same context used by the underlying connection.
ctx context.Context
}
type (
// Committer is the interface that wraps the Commit method.
Committer interface {
Commit(context.Context, *Tx) error
}
// The CommitFunc type is an adapter to allow the use of ordinary
// function as a Committer. If f is a function with the appropriate
// signature, CommitFunc(f) is a Committer that calls f.
CommitFunc func(context.Context, *Tx) error
// CommitHook defines the "commit middleware". A function that gets a Committer
// and returns a Committer. For example:
//
// hook := func(next ent.Committer) ent.Committer {
// return ent.CommitFunc(func(ctx context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Commit(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
CommitHook func(Committer) Committer
)
// Commit calls f(ctx, m).
func (f CommitFunc) Commit(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Commit commits the transaction.
func (tx *Tx) Commit() error {
txDriver := tx.config.driver.(*txDriver)
var fn Committer = CommitFunc(func(context.Context, *Tx) error {
return txDriver.tx.Commit()
})
txDriver.mu.Lock()
hooks := append([]CommitHook(nil), txDriver.onCommit...)
txDriver.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Commit(tx.ctx, tx)
}
// OnCommit adds a hook to call on commit.
func (tx *Tx) OnCommit(f CommitHook) {
txDriver := tx.config.driver.(*txDriver)
txDriver.mu.Lock()
txDriver.onCommit = append(txDriver.onCommit, f)
txDriver.mu.Unlock()
}
type (
// Rollbacker is the interface that wraps the Rollback method.
Rollbacker interface {
Rollback(context.Context, *Tx) error
}
// The RollbackFunc type is an adapter to allow the use of ordinary
// function as a Rollbacker. If f is a function with the appropriate
// signature, RollbackFunc(f) is a Rollbacker that calls f.
RollbackFunc func(context.Context, *Tx) error
// RollbackHook defines the "rollback middleware". A function that gets a Rollbacker
// and returns a Rollbacker. For example:
//
// hook := func(next ent.Rollbacker) ent.Rollbacker {
// return ent.RollbackFunc(func(ctx context.Context, tx *ent.Tx) error {
// // Do some stuff before.
// if err := next.Rollback(ctx, tx); err != nil {
// return err
// }
// // Do some stuff after.
// return nil
// })
// }
//
RollbackHook func(Rollbacker) Rollbacker
)
// Rollback calls f(ctx, m).
func (f RollbackFunc) Rollback(ctx context.Context, tx *Tx) error {
return f(ctx, tx)
}
// Rollback rollbacks the transaction.
func (tx *Tx) Rollback() error {
txDriver := tx.config.driver.(*txDriver)
var fn Rollbacker = RollbackFunc(func(context.Context, *Tx) error {
return txDriver.tx.Rollback()
})
txDriver.mu.Lock()
hooks := append([]RollbackHook(nil), txDriver.onRollback...)
txDriver.mu.Unlock()
for i := len(hooks) - 1; i >= 0; i-- {
fn = hooks[i](fn)
}
return fn.Rollback(tx.ctx, tx)
}
// OnRollback adds a hook to call on rollback.
func (tx *Tx) OnRollback(f RollbackHook) {
txDriver := tx.config.driver.(*txDriver)
txDriver.mu.Lock()
txDriver.onRollback = append(txDriver.onRollback, f)
txDriver.mu.Unlock()
}
// Client returns a Client that binds to current transaction.
func (tx *Tx) Client() *Client {
tx.clientOnce.Do(func() {
tx.client = &Client{config: tx.config}
tx.client.init()
})
return tx.client
}
func (tx *Tx) init() {
tx.Users = NewUsersClient(tx.config)
}
// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.
// The idea is to support transactions without adding any extra code to the builders.
// When a builder calls to driver.Tx(), it gets the same dialect.Tx instance.
// Commit and Rollback are nop for the internal builders and the user must call one
// of them in order to commit or rollback the transaction.
//
// If a closed transaction is embedded in one of the generated entities, and the entity
// applies a query, for example: Users.QueryXXX(), the query will be executed
// through the driver which created this transaction.
//
// Note that txDriver is not goroutine safe.
type txDriver struct {
// the driver we started the transaction from.
drv dialect.Driver
// tx is the underlying transaction.
tx dialect.Tx
// completion hooks.
mu sync.Mutex
onCommit []CommitHook
onRollback []RollbackHook
}
// newTx creates a new transactional driver.
func newTx(ctx context.Context, drv dialect.Driver) (*txDriver, error) {
tx, err := drv.Tx(ctx)
if err != nil {
return nil, err
}
return &txDriver{tx: tx, drv: drv}, nil
}
// Tx returns the transaction wrapper (txDriver) to avoid Commit or Rollback calls
// from the internal builders. Should be called only by the internal builders.
func (tx *txDriver) Tx(context.Context) (dialect.Tx, error) { return tx, nil }
// Dialect returns the dialect of the driver we started the transaction from.
func (tx *txDriver) Dialect() string { return tx.drv.Dialect() }
// Close is a nop close.
func (*txDriver) Close() error { return nil }
// Commit is a nop commit for the internal builders.
// User must call `Tx.Commit` in order to commit the transaction.
func (*txDriver) Commit() error { return nil }
// Rollback is a nop rollback for the internal builders.
// User must call `Tx.Rollback` in order to rollback the transaction.
func (*txDriver) Rollback() error { return nil }
// Exec calls tx.Exec.
func (tx *txDriver) Exec(ctx context.Context, query string, args, v any) error {
return tx.tx.Exec(ctx, query, args, v)
}
// Query calls tx.Query.
func (tx *txDriver) Query(ctx context.Context, query string, args, v any) error {
return tx.tx.Query(ctx, query, args, v)
}
var _ dialect.Driver = (*txDriver)(nil)
+259
View File
@@ -0,0 +1,259 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"encoding/json"
"fmt"
"juwan-backend/app/users/rpc/internal/models/schema"
"juwan-backend/app/users/rpc/internal/models/users"
"strings"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
)
// Users is the model entity for the Users schema.
type Users struct {
config `json:"-"`
// ID of the ent.
ID int64 `json:"id,omitempty"`
// Username holds the value of the "username" field.
Username string `json:"username,omitempty"`
// PasswordHash holds the value of the "password_hash" field.
PasswordHash string `json:"password_hash,omitempty"`
// Email holds the value of the "email" field.
Email string `json:"email,omitempty"`
// Phone holds the value of the "phone" field.
Phone string `json:"phone,omitempty"`
// Nickname holds the value of the "nickname" field.
Nickname string `json:"nickname,omitempty"`
// Avatar holds the value of the "avatar" field.
Avatar string `json:"avatar,omitempty"`
// Bio holds the value of the "bio" field.
Bio string `json:"bio,omitempty"`
// CurrentRole holds the value of the "current_role" field.
CurrentRole string `json:"current_role,omitempty"`
// VerifiedRoles holds the value of the "verified_roles" field.
VerifiedRoles []string `json:"verified_roles,omitempty"`
// VerificationStatus holds the value of the "verificationStatus" field.
VerificationStatus schema.VerificationStatusStruct `json:"verificationStatus,omitempty"`
// IsAdmin holds the value of the "is_admin" field.
IsAdmin bool `json:"is_admin,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt time.Time `json:"updated_at,omitempty"`
// DeletedAt holds the value of the "deleted_at" field.
DeletedAt time.Time `json:"deleted_at,omitempty"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Users) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case users.FieldVerifiedRoles, users.FieldVerificationStatus:
values[i] = new([]byte)
case users.FieldIsAdmin:
values[i] = new(sql.NullBool)
case users.FieldID:
values[i] = new(sql.NullInt64)
case users.FieldUsername, users.FieldPasswordHash, users.FieldEmail, users.FieldPhone, users.FieldNickname, users.FieldAvatar, users.FieldBio, users.FieldCurrentRole:
values[i] = new(sql.NullString)
case users.FieldCreatedAt, users.FieldUpdatedAt, users.FieldDeletedAt:
values[i] = new(sql.NullTime)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Users fields.
func (_m *Users) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case users.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
_m.ID = int64(value.Int64)
case users.FieldUsername:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field username", values[i])
} else if value.Valid {
_m.Username = value.String
}
case users.FieldPasswordHash:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field password_hash", values[i])
} else if value.Valid {
_m.PasswordHash = value.String
}
case users.FieldEmail:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field email", values[i])
} else if value.Valid {
_m.Email = value.String
}
case users.FieldPhone:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field phone", values[i])
} else if value.Valid {
_m.Phone = value.String
}
case users.FieldNickname:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field nickname", values[i])
} else if value.Valid {
_m.Nickname = value.String
}
case users.FieldAvatar:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field avatar", values[i])
} else if value.Valid {
_m.Avatar = value.String
}
case users.FieldBio:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field bio", values[i])
} else if value.Valid {
_m.Bio = value.String
}
case users.FieldCurrentRole:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field current_role", values[i])
} else if value.Valid {
_m.CurrentRole = value.String
}
case users.FieldVerifiedRoles:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field verified_roles", values[i])
} else if value != nil && len(*value) > 0 {
if err := json.Unmarshal(*value, &_m.VerifiedRoles); err != nil {
return fmt.Errorf("unmarshal field verified_roles: %w", err)
}
}
case users.FieldVerificationStatus:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field verificationStatus", values[i])
} else if value != nil && len(*value) > 0 {
if err := json.Unmarshal(*value, &_m.VerificationStatus); err != nil {
return fmt.Errorf("unmarshal field verificationStatus: %w", err)
}
}
case users.FieldIsAdmin:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field is_admin", values[i])
} else if value.Valid {
_m.IsAdmin = value.Bool
}
case users.FieldCreatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
_m.CreatedAt = value.Time
}
case users.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
_m.UpdatedAt = value.Time
}
case users.FieldDeletedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field deleted_at", values[i])
} else if value.Valid {
_m.DeletedAt = value.Time
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Users.
// This includes values selected through modifiers, order, etc.
func (_m *Users) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// Update returns a builder for updating this Users.
// Note that you need to call Users.Unwrap() before calling this method if this Users
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *Users) Update() *UsersUpdateOne {
return NewUsersClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the Users entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (_m *Users) Unwrap() *Users {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("models: Users is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *Users) String() string {
var builder strings.Builder
builder.WriteString("Users(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("username=")
builder.WriteString(_m.Username)
builder.WriteString(", ")
builder.WriteString("password_hash=")
builder.WriteString(_m.PasswordHash)
builder.WriteString(", ")
builder.WriteString("email=")
builder.WriteString(_m.Email)
builder.WriteString(", ")
builder.WriteString("phone=")
builder.WriteString(_m.Phone)
builder.WriteString(", ")
builder.WriteString("nickname=")
builder.WriteString(_m.Nickname)
builder.WriteString(", ")
builder.WriteString("avatar=")
builder.WriteString(_m.Avatar)
builder.WriteString(", ")
builder.WriteString("bio=")
builder.WriteString(_m.Bio)
builder.WriteString(", ")
builder.WriteString("current_role=")
builder.WriteString(_m.CurrentRole)
builder.WriteString(", ")
builder.WriteString("verified_roles=")
builder.WriteString(fmt.Sprintf("%v", _m.VerifiedRoles))
builder.WriteString(", ")
builder.WriteString("verificationStatus=")
builder.WriteString(fmt.Sprintf("%v", _m.VerificationStatus))
builder.WriteString(", ")
builder.WriteString("is_admin=")
builder.WriteString(fmt.Sprintf("%v", _m.IsAdmin))
builder.WriteString(", ")
builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(_m.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("deleted_at=")
builder.WriteString(_m.DeletedAt.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// UsersSlice is a parsable slice of Users.
type UsersSlice []*Users
@@ -0,0 +1,152 @@
// Code generated by ent, DO NOT EDIT.
package users
import (
"time"
"entgo.io/ent/dialect/sql"
)
const (
// Label holds the string label denoting the users type in the database.
Label = "users"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldUsername holds the string denoting the username field in the database.
FieldUsername = "username"
// FieldPasswordHash holds the string denoting the password_hash field in the database.
FieldPasswordHash = "password_hash"
// FieldEmail holds the string denoting the email field in the database.
FieldEmail = "email"
// FieldPhone holds the string denoting the phone field in the database.
FieldPhone = "phone"
// FieldNickname holds the string denoting the nickname field in the database.
FieldNickname = "nickname"
// FieldAvatar holds the string denoting the avatar field in the database.
FieldAvatar = "avatar"
// FieldBio holds the string denoting the bio field in the database.
FieldBio = "bio"
// FieldCurrentRole holds the string denoting the current_role field in the database.
FieldCurrentRole = "current_role"
// FieldVerifiedRoles holds the string denoting the verified_roles field in the database.
FieldVerifiedRoles = "verified_roles"
// FieldVerificationStatus holds the string denoting the verificationstatus field in the database.
FieldVerificationStatus = "verification_status"
// FieldIsAdmin holds the string denoting the is_admin field in the database.
FieldIsAdmin = "is_admin"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// FieldDeletedAt holds the string denoting the deleted_at field in the database.
FieldDeletedAt = "deleted_at"
// Table holds the table name of the users in the database.
Table = "users"
)
// Columns holds all SQL columns for users fields.
var Columns = []string{
FieldID,
FieldUsername,
FieldPasswordHash,
FieldEmail,
FieldPhone,
FieldNickname,
FieldAvatar,
FieldBio,
FieldCurrentRole,
FieldVerifiedRoles,
FieldVerificationStatus,
FieldIsAdmin,
FieldCreatedAt,
FieldUpdatedAt,
FieldDeletedAt,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
var (
// DefaultIsAdmin holds the default value on creation for the "is_admin" field.
DefaultIsAdmin bool
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
)
// OrderOption defines the ordering options for the Users queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByUsername orders the results by the username field.
func ByUsername(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUsername, opts...).ToFunc()
}
// ByPasswordHash orders the results by the password_hash field.
func ByPasswordHash(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPasswordHash, opts...).ToFunc()
}
// ByEmail orders the results by the email field.
func ByEmail(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldEmail, opts...).ToFunc()
}
// ByPhone orders the results by the phone field.
func ByPhone(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPhone, opts...).ToFunc()
}
// ByNickname orders the results by the nickname field.
func ByNickname(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldNickname, opts...).ToFunc()
}
// ByAvatar orders the results by the avatar field.
func ByAvatar(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldAvatar, opts...).ToFunc()
}
// ByBio orders the results by the bio field.
func ByBio(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldBio, opts...).ToFunc()
}
// ByCurrentRole orders the results by the current_role field.
func ByCurrentRole(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCurrentRole, opts...).ToFunc()
}
// ByIsAdmin orders the results by the is_admin field.
func ByIsAdmin(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldIsAdmin, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
// ByUpdatedAt orders the results by the updated_at field.
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
}
// ByDeletedAt orders the results by the deleted_at field.
func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDeletedAt, opts...).ToFunc()
}
@@ -0,0 +1,780 @@
// Code generated by ent, DO NOT EDIT.
package users
import (
"juwan-backend/app/users/rpc/internal/models/predicate"
"time"
"entgo.io/ent/dialect/sql"
)
// ID filters vertices based on their ID field.
func ID(id int64) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int64) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int64) predicate.Users {
return predicate.Users(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int64) predicate.Users {
return predicate.Users(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int64) predicate.Users {
return predicate.Users(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int64) predicate.Users {
return predicate.Users(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int64) predicate.Users {
return predicate.Users(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int64) predicate.Users {
return predicate.Users(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int64) predicate.Users {
return predicate.Users(sql.FieldLTE(FieldID, id))
}
// Username applies equality check predicate on the "username" field. It's identical to UsernameEQ.
func Username(v string) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldUsername, v))
}
// PasswordHash applies equality check predicate on the "password_hash" field. It's identical to PasswordHashEQ.
func PasswordHash(v string) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldPasswordHash, v))
}
// Email applies equality check predicate on the "email" field. It's identical to EmailEQ.
func Email(v string) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldEmail, v))
}
// Phone applies equality check predicate on the "phone" field. It's identical to PhoneEQ.
func Phone(v string) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldPhone, v))
}
// Nickname applies equality check predicate on the "nickname" field. It's identical to NicknameEQ.
func Nickname(v string) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldNickname, v))
}
// Avatar applies equality check predicate on the "avatar" field. It's identical to AvatarEQ.
func Avatar(v string) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldAvatar, v))
}
// Bio applies equality check predicate on the "bio" field. It's identical to BioEQ.
func Bio(v string) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldBio, v))
}
// CurrentRole applies equality check predicate on the "current_role" field. It's identical to CurrentRoleEQ.
func CurrentRole(v string) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldCurrentRole, v))
}
// IsAdmin applies equality check predicate on the "is_admin" field. It's identical to IsAdminEQ.
func IsAdmin(v bool) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldIsAdmin, v))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldCreatedAt, v))
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v time.Time) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldUpdatedAt, v))
}
// DeletedAt applies equality check predicate on the "deleted_at" field. It's identical to DeletedAtEQ.
func DeletedAt(v time.Time) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldDeletedAt, v))
}
// UsernameEQ applies the EQ predicate on the "username" field.
func UsernameEQ(v string) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldUsername, v))
}
// UsernameNEQ applies the NEQ predicate on the "username" field.
func UsernameNEQ(v string) predicate.Users {
return predicate.Users(sql.FieldNEQ(FieldUsername, v))
}
// UsernameIn applies the In predicate on the "username" field.
func UsernameIn(vs ...string) predicate.Users {
return predicate.Users(sql.FieldIn(FieldUsername, vs...))
}
// UsernameNotIn applies the NotIn predicate on the "username" field.
func UsernameNotIn(vs ...string) predicate.Users {
return predicate.Users(sql.FieldNotIn(FieldUsername, vs...))
}
// UsernameGT applies the GT predicate on the "username" field.
func UsernameGT(v string) predicate.Users {
return predicate.Users(sql.FieldGT(FieldUsername, v))
}
// UsernameGTE applies the GTE predicate on the "username" field.
func UsernameGTE(v string) predicate.Users {
return predicate.Users(sql.FieldGTE(FieldUsername, v))
}
// UsernameLT applies the LT predicate on the "username" field.
func UsernameLT(v string) predicate.Users {
return predicate.Users(sql.FieldLT(FieldUsername, v))
}
// UsernameLTE applies the LTE predicate on the "username" field.
func UsernameLTE(v string) predicate.Users {
return predicate.Users(sql.FieldLTE(FieldUsername, v))
}
// UsernameContains applies the Contains predicate on the "username" field.
func UsernameContains(v string) predicate.Users {
return predicate.Users(sql.FieldContains(FieldUsername, v))
}
// UsernameHasPrefix applies the HasPrefix predicate on the "username" field.
func UsernameHasPrefix(v string) predicate.Users {
return predicate.Users(sql.FieldHasPrefix(FieldUsername, v))
}
// UsernameHasSuffix applies the HasSuffix predicate on the "username" field.
func UsernameHasSuffix(v string) predicate.Users {
return predicate.Users(sql.FieldHasSuffix(FieldUsername, v))
}
// UsernameEqualFold applies the EqualFold predicate on the "username" field.
func UsernameEqualFold(v string) predicate.Users {
return predicate.Users(sql.FieldEqualFold(FieldUsername, v))
}
// UsernameContainsFold applies the ContainsFold predicate on the "username" field.
func UsernameContainsFold(v string) predicate.Users {
return predicate.Users(sql.FieldContainsFold(FieldUsername, v))
}
// PasswordHashEQ applies the EQ predicate on the "password_hash" field.
func PasswordHashEQ(v string) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldPasswordHash, v))
}
// PasswordHashNEQ applies the NEQ predicate on the "password_hash" field.
func PasswordHashNEQ(v string) predicate.Users {
return predicate.Users(sql.FieldNEQ(FieldPasswordHash, v))
}
// PasswordHashIn applies the In predicate on the "password_hash" field.
func PasswordHashIn(vs ...string) predicate.Users {
return predicate.Users(sql.FieldIn(FieldPasswordHash, vs...))
}
// PasswordHashNotIn applies the NotIn predicate on the "password_hash" field.
func PasswordHashNotIn(vs ...string) predicate.Users {
return predicate.Users(sql.FieldNotIn(FieldPasswordHash, vs...))
}
// PasswordHashGT applies the GT predicate on the "password_hash" field.
func PasswordHashGT(v string) predicate.Users {
return predicate.Users(sql.FieldGT(FieldPasswordHash, v))
}
// PasswordHashGTE applies the GTE predicate on the "password_hash" field.
func PasswordHashGTE(v string) predicate.Users {
return predicate.Users(sql.FieldGTE(FieldPasswordHash, v))
}
// PasswordHashLT applies the LT predicate on the "password_hash" field.
func PasswordHashLT(v string) predicate.Users {
return predicate.Users(sql.FieldLT(FieldPasswordHash, v))
}
// PasswordHashLTE applies the LTE predicate on the "password_hash" field.
func PasswordHashLTE(v string) predicate.Users {
return predicate.Users(sql.FieldLTE(FieldPasswordHash, v))
}
// PasswordHashContains applies the Contains predicate on the "password_hash" field.
func PasswordHashContains(v string) predicate.Users {
return predicate.Users(sql.FieldContains(FieldPasswordHash, v))
}
// PasswordHashHasPrefix applies the HasPrefix predicate on the "password_hash" field.
func PasswordHashHasPrefix(v string) predicate.Users {
return predicate.Users(sql.FieldHasPrefix(FieldPasswordHash, v))
}
// PasswordHashHasSuffix applies the HasSuffix predicate on the "password_hash" field.
func PasswordHashHasSuffix(v string) predicate.Users {
return predicate.Users(sql.FieldHasSuffix(FieldPasswordHash, v))
}
// PasswordHashEqualFold applies the EqualFold predicate on the "password_hash" field.
func PasswordHashEqualFold(v string) predicate.Users {
return predicate.Users(sql.FieldEqualFold(FieldPasswordHash, v))
}
// PasswordHashContainsFold applies the ContainsFold predicate on the "password_hash" field.
func PasswordHashContainsFold(v string) predicate.Users {
return predicate.Users(sql.FieldContainsFold(FieldPasswordHash, v))
}
// EmailEQ applies the EQ predicate on the "email" field.
func EmailEQ(v string) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldEmail, v))
}
// EmailNEQ applies the NEQ predicate on the "email" field.
func EmailNEQ(v string) predicate.Users {
return predicate.Users(sql.FieldNEQ(FieldEmail, v))
}
// EmailIn applies the In predicate on the "email" field.
func EmailIn(vs ...string) predicate.Users {
return predicate.Users(sql.FieldIn(FieldEmail, vs...))
}
// EmailNotIn applies the NotIn predicate on the "email" field.
func EmailNotIn(vs ...string) predicate.Users {
return predicate.Users(sql.FieldNotIn(FieldEmail, vs...))
}
// EmailGT applies the GT predicate on the "email" field.
func EmailGT(v string) predicate.Users {
return predicate.Users(sql.FieldGT(FieldEmail, v))
}
// EmailGTE applies the GTE predicate on the "email" field.
func EmailGTE(v string) predicate.Users {
return predicate.Users(sql.FieldGTE(FieldEmail, v))
}
// EmailLT applies the LT predicate on the "email" field.
func EmailLT(v string) predicate.Users {
return predicate.Users(sql.FieldLT(FieldEmail, v))
}
// EmailLTE applies the LTE predicate on the "email" field.
func EmailLTE(v string) predicate.Users {
return predicate.Users(sql.FieldLTE(FieldEmail, v))
}
// EmailContains applies the Contains predicate on the "email" field.
func EmailContains(v string) predicate.Users {
return predicate.Users(sql.FieldContains(FieldEmail, v))
}
// EmailHasPrefix applies the HasPrefix predicate on the "email" field.
func EmailHasPrefix(v string) predicate.Users {
return predicate.Users(sql.FieldHasPrefix(FieldEmail, v))
}
// EmailHasSuffix applies the HasSuffix predicate on the "email" field.
func EmailHasSuffix(v string) predicate.Users {
return predicate.Users(sql.FieldHasSuffix(FieldEmail, v))
}
// EmailEqualFold applies the EqualFold predicate on the "email" field.
func EmailEqualFold(v string) predicate.Users {
return predicate.Users(sql.FieldEqualFold(FieldEmail, v))
}
// EmailContainsFold applies the ContainsFold predicate on the "email" field.
func EmailContainsFold(v string) predicate.Users {
return predicate.Users(sql.FieldContainsFold(FieldEmail, v))
}
// PhoneEQ applies the EQ predicate on the "phone" field.
func PhoneEQ(v string) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldPhone, v))
}
// PhoneNEQ applies the NEQ predicate on the "phone" field.
func PhoneNEQ(v string) predicate.Users {
return predicate.Users(sql.FieldNEQ(FieldPhone, v))
}
// PhoneIn applies the In predicate on the "phone" field.
func PhoneIn(vs ...string) predicate.Users {
return predicate.Users(sql.FieldIn(FieldPhone, vs...))
}
// PhoneNotIn applies the NotIn predicate on the "phone" field.
func PhoneNotIn(vs ...string) predicate.Users {
return predicate.Users(sql.FieldNotIn(FieldPhone, vs...))
}
// PhoneGT applies the GT predicate on the "phone" field.
func PhoneGT(v string) predicate.Users {
return predicate.Users(sql.FieldGT(FieldPhone, v))
}
// PhoneGTE applies the GTE predicate on the "phone" field.
func PhoneGTE(v string) predicate.Users {
return predicate.Users(sql.FieldGTE(FieldPhone, v))
}
// PhoneLT applies the LT predicate on the "phone" field.
func PhoneLT(v string) predicate.Users {
return predicate.Users(sql.FieldLT(FieldPhone, v))
}
// PhoneLTE applies the LTE predicate on the "phone" field.
func PhoneLTE(v string) predicate.Users {
return predicate.Users(sql.FieldLTE(FieldPhone, v))
}
// PhoneContains applies the Contains predicate on the "phone" field.
func PhoneContains(v string) predicate.Users {
return predicate.Users(sql.FieldContains(FieldPhone, v))
}
// PhoneHasPrefix applies the HasPrefix predicate on the "phone" field.
func PhoneHasPrefix(v string) predicate.Users {
return predicate.Users(sql.FieldHasPrefix(FieldPhone, v))
}
// PhoneHasSuffix applies the HasSuffix predicate on the "phone" field.
func PhoneHasSuffix(v string) predicate.Users {
return predicate.Users(sql.FieldHasSuffix(FieldPhone, v))
}
// PhoneEqualFold applies the EqualFold predicate on the "phone" field.
func PhoneEqualFold(v string) predicate.Users {
return predicate.Users(sql.FieldEqualFold(FieldPhone, v))
}
// PhoneContainsFold applies the ContainsFold predicate on the "phone" field.
func PhoneContainsFold(v string) predicate.Users {
return predicate.Users(sql.FieldContainsFold(FieldPhone, v))
}
// NicknameEQ applies the EQ predicate on the "nickname" field.
func NicknameEQ(v string) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldNickname, v))
}
// NicknameNEQ applies the NEQ predicate on the "nickname" field.
func NicknameNEQ(v string) predicate.Users {
return predicate.Users(sql.FieldNEQ(FieldNickname, v))
}
// NicknameIn applies the In predicate on the "nickname" field.
func NicknameIn(vs ...string) predicate.Users {
return predicate.Users(sql.FieldIn(FieldNickname, vs...))
}
// NicknameNotIn applies the NotIn predicate on the "nickname" field.
func NicknameNotIn(vs ...string) predicate.Users {
return predicate.Users(sql.FieldNotIn(FieldNickname, vs...))
}
// NicknameGT applies the GT predicate on the "nickname" field.
func NicknameGT(v string) predicate.Users {
return predicate.Users(sql.FieldGT(FieldNickname, v))
}
// NicknameGTE applies the GTE predicate on the "nickname" field.
func NicknameGTE(v string) predicate.Users {
return predicate.Users(sql.FieldGTE(FieldNickname, v))
}
// NicknameLT applies the LT predicate on the "nickname" field.
func NicknameLT(v string) predicate.Users {
return predicate.Users(sql.FieldLT(FieldNickname, v))
}
// NicknameLTE applies the LTE predicate on the "nickname" field.
func NicknameLTE(v string) predicate.Users {
return predicate.Users(sql.FieldLTE(FieldNickname, v))
}
// NicknameContains applies the Contains predicate on the "nickname" field.
func NicknameContains(v string) predicate.Users {
return predicate.Users(sql.FieldContains(FieldNickname, v))
}
// NicknameHasPrefix applies the HasPrefix predicate on the "nickname" field.
func NicknameHasPrefix(v string) predicate.Users {
return predicate.Users(sql.FieldHasPrefix(FieldNickname, v))
}
// NicknameHasSuffix applies the HasSuffix predicate on the "nickname" field.
func NicknameHasSuffix(v string) predicate.Users {
return predicate.Users(sql.FieldHasSuffix(FieldNickname, v))
}
// NicknameEqualFold applies the EqualFold predicate on the "nickname" field.
func NicknameEqualFold(v string) predicate.Users {
return predicate.Users(sql.FieldEqualFold(FieldNickname, v))
}
// NicknameContainsFold applies the ContainsFold predicate on the "nickname" field.
func NicknameContainsFold(v string) predicate.Users {
return predicate.Users(sql.FieldContainsFold(FieldNickname, v))
}
// AvatarEQ applies the EQ predicate on the "avatar" field.
func AvatarEQ(v string) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldAvatar, v))
}
// AvatarNEQ applies the NEQ predicate on the "avatar" field.
func AvatarNEQ(v string) predicate.Users {
return predicate.Users(sql.FieldNEQ(FieldAvatar, v))
}
// AvatarIn applies the In predicate on the "avatar" field.
func AvatarIn(vs ...string) predicate.Users {
return predicate.Users(sql.FieldIn(FieldAvatar, vs...))
}
// AvatarNotIn applies the NotIn predicate on the "avatar" field.
func AvatarNotIn(vs ...string) predicate.Users {
return predicate.Users(sql.FieldNotIn(FieldAvatar, vs...))
}
// AvatarGT applies the GT predicate on the "avatar" field.
func AvatarGT(v string) predicate.Users {
return predicate.Users(sql.FieldGT(FieldAvatar, v))
}
// AvatarGTE applies the GTE predicate on the "avatar" field.
func AvatarGTE(v string) predicate.Users {
return predicate.Users(sql.FieldGTE(FieldAvatar, v))
}
// AvatarLT applies the LT predicate on the "avatar" field.
func AvatarLT(v string) predicate.Users {
return predicate.Users(sql.FieldLT(FieldAvatar, v))
}
// AvatarLTE applies the LTE predicate on the "avatar" field.
func AvatarLTE(v string) predicate.Users {
return predicate.Users(sql.FieldLTE(FieldAvatar, v))
}
// AvatarContains applies the Contains predicate on the "avatar" field.
func AvatarContains(v string) predicate.Users {
return predicate.Users(sql.FieldContains(FieldAvatar, v))
}
// AvatarHasPrefix applies the HasPrefix predicate on the "avatar" field.
func AvatarHasPrefix(v string) predicate.Users {
return predicate.Users(sql.FieldHasPrefix(FieldAvatar, v))
}
// AvatarHasSuffix applies the HasSuffix predicate on the "avatar" field.
func AvatarHasSuffix(v string) predicate.Users {
return predicate.Users(sql.FieldHasSuffix(FieldAvatar, v))
}
// AvatarEqualFold applies the EqualFold predicate on the "avatar" field.
func AvatarEqualFold(v string) predicate.Users {
return predicate.Users(sql.FieldEqualFold(FieldAvatar, v))
}
// AvatarContainsFold applies the ContainsFold predicate on the "avatar" field.
func AvatarContainsFold(v string) predicate.Users {
return predicate.Users(sql.FieldContainsFold(FieldAvatar, v))
}
// BioEQ applies the EQ predicate on the "bio" field.
func BioEQ(v string) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldBio, v))
}
// BioNEQ applies the NEQ predicate on the "bio" field.
func BioNEQ(v string) predicate.Users {
return predicate.Users(sql.FieldNEQ(FieldBio, v))
}
// BioIn applies the In predicate on the "bio" field.
func BioIn(vs ...string) predicate.Users {
return predicate.Users(sql.FieldIn(FieldBio, vs...))
}
// BioNotIn applies the NotIn predicate on the "bio" field.
func BioNotIn(vs ...string) predicate.Users {
return predicate.Users(sql.FieldNotIn(FieldBio, vs...))
}
// BioGT applies the GT predicate on the "bio" field.
func BioGT(v string) predicate.Users {
return predicate.Users(sql.FieldGT(FieldBio, v))
}
// BioGTE applies the GTE predicate on the "bio" field.
func BioGTE(v string) predicate.Users {
return predicate.Users(sql.FieldGTE(FieldBio, v))
}
// BioLT applies the LT predicate on the "bio" field.
func BioLT(v string) predicate.Users {
return predicate.Users(sql.FieldLT(FieldBio, v))
}
// BioLTE applies the LTE predicate on the "bio" field.
func BioLTE(v string) predicate.Users {
return predicate.Users(sql.FieldLTE(FieldBio, v))
}
// BioContains applies the Contains predicate on the "bio" field.
func BioContains(v string) predicate.Users {
return predicate.Users(sql.FieldContains(FieldBio, v))
}
// BioHasPrefix applies the HasPrefix predicate on the "bio" field.
func BioHasPrefix(v string) predicate.Users {
return predicate.Users(sql.FieldHasPrefix(FieldBio, v))
}
// BioHasSuffix applies the HasSuffix predicate on the "bio" field.
func BioHasSuffix(v string) predicate.Users {
return predicate.Users(sql.FieldHasSuffix(FieldBio, v))
}
// BioEqualFold applies the EqualFold predicate on the "bio" field.
func BioEqualFold(v string) predicate.Users {
return predicate.Users(sql.FieldEqualFold(FieldBio, v))
}
// BioContainsFold applies the ContainsFold predicate on the "bio" field.
func BioContainsFold(v string) predicate.Users {
return predicate.Users(sql.FieldContainsFold(FieldBio, v))
}
// CurrentRoleEQ applies the EQ predicate on the "current_role" field.
func CurrentRoleEQ(v string) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldCurrentRole, v))
}
// CurrentRoleNEQ applies the NEQ predicate on the "current_role" field.
func CurrentRoleNEQ(v string) predicate.Users {
return predicate.Users(sql.FieldNEQ(FieldCurrentRole, v))
}
// CurrentRoleIn applies the In predicate on the "current_role" field.
func CurrentRoleIn(vs ...string) predicate.Users {
return predicate.Users(sql.FieldIn(FieldCurrentRole, vs...))
}
// CurrentRoleNotIn applies the NotIn predicate on the "current_role" field.
func CurrentRoleNotIn(vs ...string) predicate.Users {
return predicate.Users(sql.FieldNotIn(FieldCurrentRole, vs...))
}
// CurrentRoleGT applies the GT predicate on the "current_role" field.
func CurrentRoleGT(v string) predicate.Users {
return predicate.Users(sql.FieldGT(FieldCurrentRole, v))
}
// CurrentRoleGTE applies the GTE predicate on the "current_role" field.
func CurrentRoleGTE(v string) predicate.Users {
return predicate.Users(sql.FieldGTE(FieldCurrentRole, v))
}
// CurrentRoleLT applies the LT predicate on the "current_role" field.
func CurrentRoleLT(v string) predicate.Users {
return predicate.Users(sql.FieldLT(FieldCurrentRole, v))
}
// CurrentRoleLTE applies the LTE predicate on the "current_role" field.
func CurrentRoleLTE(v string) predicate.Users {
return predicate.Users(sql.FieldLTE(FieldCurrentRole, v))
}
// CurrentRoleContains applies the Contains predicate on the "current_role" field.
func CurrentRoleContains(v string) predicate.Users {
return predicate.Users(sql.FieldContains(FieldCurrentRole, v))
}
// CurrentRoleHasPrefix applies the HasPrefix predicate on the "current_role" field.
func CurrentRoleHasPrefix(v string) predicate.Users {
return predicate.Users(sql.FieldHasPrefix(FieldCurrentRole, v))
}
// CurrentRoleHasSuffix applies the HasSuffix predicate on the "current_role" field.
func CurrentRoleHasSuffix(v string) predicate.Users {
return predicate.Users(sql.FieldHasSuffix(FieldCurrentRole, v))
}
// CurrentRoleEqualFold applies the EqualFold predicate on the "current_role" field.
func CurrentRoleEqualFold(v string) predicate.Users {
return predicate.Users(sql.FieldEqualFold(FieldCurrentRole, v))
}
// CurrentRoleContainsFold applies the ContainsFold predicate on the "current_role" field.
func CurrentRoleContainsFold(v string) predicate.Users {
return predicate.Users(sql.FieldContainsFold(FieldCurrentRole, v))
}
// IsAdminEQ applies the EQ predicate on the "is_admin" field.
func IsAdminEQ(v bool) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldIsAdmin, v))
}
// IsAdminNEQ applies the NEQ predicate on the "is_admin" field.
func IsAdminNEQ(v bool) predicate.Users {
return predicate.Users(sql.FieldNEQ(FieldIsAdmin, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.Users {
return predicate.Users(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.Users {
return predicate.Users(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.Users {
return predicate.Users(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.Users {
return predicate.Users(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.Users {
return predicate.Users(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.Users {
return predicate.Users(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.Users {
return predicate.Users(sql.FieldLTE(FieldCreatedAt, v))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldUpdatedAt, v))
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.Users {
return predicate.Users(sql.FieldNEQ(FieldUpdatedAt, v))
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.Users {
return predicate.Users(sql.FieldIn(FieldUpdatedAt, vs...))
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.Users {
return predicate.Users(sql.FieldNotIn(FieldUpdatedAt, vs...))
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.Users {
return predicate.Users(sql.FieldGT(FieldUpdatedAt, v))
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.Users {
return predicate.Users(sql.FieldGTE(FieldUpdatedAt, v))
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.Users {
return predicate.Users(sql.FieldLT(FieldUpdatedAt, v))
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.Users {
return predicate.Users(sql.FieldLTE(FieldUpdatedAt, v))
}
// DeletedAtEQ applies the EQ predicate on the "deleted_at" field.
func DeletedAtEQ(v time.Time) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldDeletedAt, v))
}
// DeletedAtNEQ applies the NEQ predicate on the "deleted_at" field.
func DeletedAtNEQ(v time.Time) predicate.Users {
return predicate.Users(sql.FieldNEQ(FieldDeletedAt, v))
}
// DeletedAtIn applies the In predicate on the "deleted_at" field.
func DeletedAtIn(vs ...time.Time) predicate.Users {
return predicate.Users(sql.FieldIn(FieldDeletedAt, vs...))
}
// DeletedAtNotIn applies the NotIn predicate on the "deleted_at" field.
func DeletedAtNotIn(vs ...time.Time) predicate.Users {
return predicate.Users(sql.FieldNotIn(FieldDeletedAt, vs...))
}
// DeletedAtGT applies the GT predicate on the "deleted_at" field.
func DeletedAtGT(v time.Time) predicate.Users {
return predicate.Users(sql.FieldGT(FieldDeletedAt, v))
}
// DeletedAtGTE applies the GTE predicate on the "deleted_at" field.
func DeletedAtGTE(v time.Time) predicate.Users {
return predicate.Users(sql.FieldGTE(FieldDeletedAt, v))
}
// DeletedAtLT applies the LT predicate on the "deleted_at" field.
func DeletedAtLT(v time.Time) predicate.Users {
return predicate.Users(sql.FieldLT(FieldDeletedAt, v))
}
// DeletedAtLTE applies the LTE predicate on the "deleted_at" field.
func DeletedAtLTE(v time.Time) predicate.Users {
return predicate.Users(sql.FieldLTE(FieldDeletedAt, v))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Users) predicate.Users {
return predicate.Users(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Users) predicate.Users {
return predicate.Users(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Users) predicate.Users {
return predicate.Users(sql.NotPredicates(p))
}
@@ -1,27 +0,0 @@
package models
import (
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
var _ UsersModel = (*customUsersModel)(nil)
type (
// UsersModel is an interface to be customized, add more methods here,
// and implement the added methods in customUsersModel.
UsersModel interface {
usersModel
}
customUsersModel struct {
*defaultUsersModel
}
)
// NewUsersModel returns a model for the database table.
func NewUsersModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) UsersModel {
return &customUsersModel{
defaultUsersModel: newUsersModel(conn, c, opts...),
}
}
@@ -1,206 +0,0 @@
// Code generated by goctl. DO NOT EDIT.
// versions:
// goctl version: 1.9.2
package models
import (
"context"
"database/sql"
"fmt"
"strings"
"time"
"github.com/zeromicro/go-zero/core/stores/builder"
"github.com/zeromicro/go-zero/core/stores/cache"
"github.com/zeromicro/go-zero/core/stores/sqlc"
"github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stringx"
)
var (
usersFieldNames = builder.RawFieldNames(&Users{}, true)
usersRows = strings.Join(usersFieldNames, ",")
usersRowsExpectAutoSet = strings.Join(stringx.Remove(usersFieldNames, "create_at", "create_time", "created_at", "update_at", "update_time", "updated_at"), ",")
usersRowsWithPlaceHolder = builder.PostgreSqlJoin(stringx.Remove(usersFieldNames, "user_id", "create_at", "create_time", "created_at", "update_at", "update_time", "updated_at"))
cachePublicUsersUserIdPrefix = "cache:public:users:userId:"
cachePublicUsersEmailPrefix = "cache:public:users:email:"
cachePublicUsersPhonePrefix = "cache:public:users:phone:"
cachePublicUsersUsernamePrefix = "cache:public:users:username:"
)
type (
usersModel interface {
Insert(ctx context.Context, data *Users) (sql.Result, error)
FindOne(ctx context.Context, userId int64) (*Users, error)
FindOneByEmail(ctx context.Context, email string) (*Users, error)
FindOneByPhone(ctx context.Context, phone string) (*Users, error)
FindOneByUsername(ctx context.Context, username string) (*Users, error)
Update(ctx context.Context, data *Users) error
Delete(ctx context.Context, userId int64) error
}
defaultUsersModel struct {
sqlc.CachedConn
table string
}
Users struct {
UserId int64 `db:"user_id"`
Username string `db:"username"`
Passwd string `db:"passwd"`
Nickname string `db:"nickname"`
Phone string `db:"phone"`
RoleType int64 `db:"role_type"`
IsVerified bool `db:"is_verified"`
State bool `db:"state"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt time.Time `db:"updated_at"`
DeletedAt sql.NullTime `db:"deleted_at"`
Email string `db:"email"`
}
)
func newUsersModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) *defaultUsersModel {
return &defaultUsersModel{
CachedConn: sqlc.NewConn(conn, c, opts...),
table: `"public"."users"`,
}
}
func (m *defaultUsersModel) Delete(ctx context.Context, userId int64) error {
data, err := m.FindOne(ctx, userId)
if err != nil {
return err
}
publicUsersEmailKey := fmt.Sprintf("%s%v", cachePublicUsersEmailPrefix, data.Email)
publicUsersPhoneKey := fmt.Sprintf("%s%v", cachePublicUsersPhonePrefix, data.Phone)
publicUsersUserIdKey := fmt.Sprintf("%s%v", cachePublicUsersUserIdPrefix, userId)
publicUsersUsernameKey := fmt.Sprintf("%s%v", cachePublicUsersUsernamePrefix, data.Username)
_, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("delete from %s where user_id = $1", m.table)
return conn.ExecCtx(ctx, query, userId)
}, publicUsersEmailKey, publicUsersPhoneKey, publicUsersUserIdKey, publicUsersUsernameKey)
return err
}
func (m *defaultUsersModel) FindOne(ctx context.Context, userId int64) (*Users, error) {
publicUsersUserIdKey := fmt.Sprintf("%s%v", cachePublicUsersUserIdPrefix, userId)
var resp Users
err := m.QueryRowCtx(ctx, &resp, publicUsersUserIdKey, func(ctx context.Context, conn sqlx.SqlConn, v any) error {
query := fmt.Sprintf("select %s from %s where user_id = $1 limit 1", usersRows, m.table)
return conn.QueryRowCtx(ctx, v, query, userId)
})
switch err {
case nil:
return &resp, nil
case sqlc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultUsersModel) FindOneByEmail(ctx context.Context, email string) (*Users, error) {
publicUsersEmailKey := fmt.Sprintf("%s%v", cachePublicUsersEmailPrefix, email)
var resp Users
err := m.QueryRowIndexCtx(ctx, &resp, publicUsersEmailKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v any) (i any, e error) {
query := fmt.Sprintf("select %s from %s where email = $1 limit 1", usersRows, m.table)
if err := conn.QueryRowCtx(ctx, &resp, query, email); err != nil {
return nil, err
}
return resp.UserId, nil
}, m.queryPrimary)
switch err {
case nil:
return &resp, nil
case sqlc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultUsersModel) FindOneByPhone(ctx context.Context, phone string) (*Users, error) {
publicUsersPhoneKey := fmt.Sprintf("%s%v", cachePublicUsersPhonePrefix, phone)
var resp Users
err := m.QueryRowIndexCtx(ctx, &resp, publicUsersPhoneKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v any) (i any, e error) {
query := fmt.Sprintf("select %s from %s where phone = $1 limit 1", usersRows, m.table)
if err := conn.QueryRowCtx(ctx, &resp, query, phone); err != nil {
return nil, err
}
return resp.UserId, nil
}, m.queryPrimary)
switch err {
case nil:
return &resp, nil
case sqlc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultUsersModel) FindOneByUsername(ctx context.Context, username string) (*Users, error) {
publicUsersUsernameKey := fmt.Sprintf("%s%v", cachePublicUsersUsernamePrefix, username)
var resp Users
err := m.QueryRowIndexCtx(ctx, &resp, publicUsersUsernameKey, m.formatPrimary, func(ctx context.Context, conn sqlx.SqlConn, v any) (i any, e error) {
query := fmt.Sprintf("select %s from %s where username = $1 limit 1", usersRows, m.table)
if err := conn.QueryRowCtx(ctx, &resp, query, username); err != nil {
return nil, err
}
return resp.UserId, nil
}, m.queryPrimary)
switch err {
case nil:
return &resp, nil
case sqlc.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultUsersModel) Insert(ctx context.Context, data *Users) (sql.Result, error) {
publicUsersEmailKey := fmt.Sprintf("%s%v", cachePublicUsersEmailPrefix, data.Email)
publicUsersPhoneKey := fmt.Sprintf("%s%v", cachePublicUsersPhonePrefix, data.Phone)
publicUsersUserIdKey := fmt.Sprintf("%s%v", cachePublicUsersUserIdPrefix, data.UserId)
publicUsersUsernameKey := fmt.Sprintf("%s%v", cachePublicUsersUsernamePrefix, data.Username)
ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("insert into %s (%s) values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)", m.table, usersRowsExpectAutoSet)
return conn.ExecCtx(ctx, query, data.UserId, data.Username, data.Passwd, data.Nickname, data.Phone, data.RoleType, data.IsVerified, data.State, data.DeletedAt, data.Email)
}, publicUsersEmailKey, publicUsersPhoneKey, publicUsersUserIdKey, publicUsersUsernameKey)
return ret, err
}
func (m *defaultUsersModel) Update(ctx context.Context, newData *Users) error {
data, err := m.FindOne(ctx, newData.UserId)
if err != nil {
return err
}
publicUsersEmailKey := fmt.Sprintf("%s%v", cachePublicUsersEmailPrefix, data.Email)
publicUsersPhoneKey := fmt.Sprintf("%s%v", cachePublicUsersPhonePrefix, data.Phone)
publicUsersUserIdKey := fmt.Sprintf("%s%v", cachePublicUsersUserIdPrefix, data.UserId)
publicUsersUsernameKey := fmt.Sprintf("%s%v", cachePublicUsersUsernamePrefix, data.Username)
_, err = m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
query := fmt.Sprintf("update %s set %s where user_id = $1", m.table, usersRowsWithPlaceHolder)
return conn.ExecCtx(ctx, query, newData.UserId, newData.Username, newData.Passwd, newData.Nickname, newData.Phone, newData.RoleType, newData.IsVerified, newData.State, newData.DeletedAt, newData.Email)
}, publicUsersEmailKey, publicUsersPhoneKey, publicUsersUserIdKey, publicUsersUsernameKey)
return err
}
func (m *defaultUsersModel) formatPrimary(primary any) string {
return fmt.Sprintf("%s%v", cachePublicUsersUserIdPrefix, primary)
}
func (m *defaultUsersModel) queryPrimary(ctx context.Context, conn sqlx.SqlConn, v, primary any) error {
query := fmt.Sprintf("select %s from %s where user_id = $1 limit 1", usersRows, m.table)
return conn.QueryRowCtx(ctx, v, query, primary)
}
func (m *defaultUsersModel) tableName() string {
return m.table
}
@@ -0,0 +1,408 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"errors"
"fmt"
"juwan-backend/app/users/rpc/internal/models/schema"
"juwan-backend/app/users/rpc/internal/models/users"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// UsersCreate is the builder for creating a Users entity.
type UsersCreate struct {
config
mutation *UsersMutation
hooks []Hook
}
// SetUsername sets the "username" field.
func (_c *UsersCreate) SetUsername(v string) *UsersCreate {
_c.mutation.SetUsername(v)
return _c
}
// SetPasswordHash sets the "password_hash" field.
func (_c *UsersCreate) SetPasswordHash(v string) *UsersCreate {
_c.mutation.SetPasswordHash(v)
return _c
}
// SetEmail sets the "email" field.
func (_c *UsersCreate) SetEmail(v string) *UsersCreate {
_c.mutation.SetEmail(v)
return _c
}
// SetPhone sets the "phone" field.
func (_c *UsersCreate) SetPhone(v string) *UsersCreate {
_c.mutation.SetPhone(v)
return _c
}
// SetNickname sets the "nickname" field.
func (_c *UsersCreate) SetNickname(v string) *UsersCreate {
_c.mutation.SetNickname(v)
return _c
}
// SetAvatar sets the "avatar" field.
func (_c *UsersCreate) SetAvatar(v string) *UsersCreate {
_c.mutation.SetAvatar(v)
return _c
}
// SetBio sets the "bio" field.
func (_c *UsersCreate) SetBio(v string) *UsersCreate {
_c.mutation.SetBio(v)
return _c
}
// SetCurrentRole sets the "current_role" field.
func (_c *UsersCreate) SetCurrentRole(v string) *UsersCreate {
_c.mutation.SetCurrentRole(v)
return _c
}
// SetVerifiedRoles sets the "verified_roles" field.
func (_c *UsersCreate) SetVerifiedRoles(v []string) *UsersCreate {
_c.mutation.SetVerifiedRoles(v)
return _c
}
// SetVerificationStatus sets the "verificationStatus" field.
func (_c *UsersCreate) SetVerificationStatus(v schema.VerificationStatusStruct) *UsersCreate {
_c.mutation.SetVerificationStatus(v)
return _c
}
// SetIsAdmin sets the "is_admin" field.
func (_c *UsersCreate) SetIsAdmin(v bool) *UsersCreate {
_c.mutation.SetIsAdmin(v)
return _c
}
// SetNillableIsAdmin sets the "is_admin" field if the given value is not nil.
func (_c *UsersCreate) SetNillableIsAdmin(v *bool) *UsersCreate {
if v != nil {
_c.SetIsAdmin(*v)
}
return _c
}
// SetCreatedAt sets the "created_at" field.
func (_c *UsersCreate) SetCreatedAt(v time.Time) *UsersCreate {
_c.mutation.SetCreatedAt(v)
return _c
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_c *UsersCreate) SetNillableCreatedAt(v *time.Time) *UsersCreate {
if v != nil {
_c.SetCreatedAt(*v)
}
return _c
}
// SetUpdatedAt sets the "updated_at" field.
func (_c *UsersCreate) SetUpdatedAt(v time.Time) *UsersCreate {
_c.mutation.SetUpdatedAt(v)
return _c
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_c *UsersCreate) SetNillableUpdatedAt(v *time.Time) *UsersCreate {
if v != nil {
_c.SetUpdatedAt(*v)
}
return _c
}
// SetDeletedAt sets the "deleted_at" field.
func (_c *UsersCreate) SetDeletedAt(v time.Time) *UsersCreate {
_c.mutation.SetDeletedAt(v)
return _c
}
// SetID sets the "id" field.
func (_c *UsersCreate) SetID(v int64) *UsersCreate {
_c.mutation.SetID(v)
return _c
}
// Mutation returns the UsersMutation object of the builder.
func (_c *UsersCreate) Mutation() *UsersMutation {
return _c.mutation
}
// Save creates the Users in the database.
func (_c *UsersCreate) Save(ctx context.Context) (*Users, error) {
_c.defaults()
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *UsersCreate) SaveX(ctx context.Context) *Users {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *UsersCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *UsersCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// defaults sets the default values of the builder before save.
func (_c *UsersCreate) defaults() {
if _, ok := _c.mutation.IsAdmin(); !ok {
v := users.DefaultIsAdmin
_c.mutation.SetIsAdmin(v)
}
if _, ok := _c.mutation.CreatedAt(); !ok {
v := users.DefaultCreatedAt()
_c.mutation.SetCreatedAt(v)
}
if _, ok := _c.mutation.UpdatedAt(); !ok {
v := users.DefaultUpdatedAt()
_c.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *UsersCreate) check() error {
if _, ok := _c.mutation.Username(); !ok {
return &ValidationError{Name: "username", err: errors.New(`models: missing required field "Users.username"`)}
}
if _, ok := _c.mutation.PasswordHash(); !ok {
return &ValidationError{Name: "password_hash", err: errors.New(`models: missing required field "Users.password_hash"`)}
}
if _, ok := _c.mutation.Email(); !ok {
return &ValidationError{Name: "email", err: errors.New(`models: missing required field "Users.email"`)}
}
if _, ok := _c.mutation.Phone(); !ok {
return &ValidationError{Name: "phone", err: errors.New(`models: missing required field "Users.phone"`)}
}
if _, ok := _c.mutation.Nickname(); !ok {
return &ValidationError{Name: "nickname", err: errors.New(`models: missing required field "Users.nickname"`)}
}
if _, ok := _c.mutation.Avatar(); !ok {
return &ValidationError{Name: "avatar", err: errors.New(`models: missing required field "Users.avatar"`)}
}
if _, ok := _c.mutation.Bio(); !ok {
return &ValidationError{Name: "bio", err: errors.New(`models: missing required field "Users.bio"`)}
}
if _, ok := _c.mutation.CurrentRole(); !ok {
return &ValidationError{Name: "current_role", err: errors.New(`models: missing required field "Users.current_role"`)}
}
if _, ok := _c.mutation.VerifiedRoles(); !ok {
return &ValidationError{Name: "verified_roles", err: errors.New(`models: missing required field "Users.verified_roles"`)}
}
if _, ok := _c.mutation.VerificationStatus(); !ok {
return &ValidationError{Name: "verificationStatus", err: errors.New(`models: missing required field "Users.verificationStatus"`)}
}
if _, ok := _c.mutation.IsAdmin(); !ok {
return &ValidationError{Name: "is_admin", err: errors.New(`models: missing required field "Users.is_admin"`)}
}
if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`models: missing required field "Users.created_at"`)}
}
if _, ok := _c.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`models: missing required field "Users.updated_at"`)}
}
if _, ok := _c.mutation.DeletedAt(); !ok {
return &ValidationError{Name: "deleted_at", err: errors.New(`models: missing required field "Users.deleted_at"`)}
}
return nil
}
func (_c *UsersCreate) sqlSave(ctx context.Context) (*Users, error) {
if err := _c.check(); err != nil {
return nil, err
}
_node, _spec := _c.createSpec()
if err := sqlgraph.CreateNode(ctx, _c.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
if _spec.ID.Value != _node.ID {
id := _spec.ID.Value.(int64)
_node.ID = int64(id)
}
_c.mutation.id = &_node.ID
_c.mutation.done = true
return _node, nil
}
func (_c *UsersCreate) createSpec() (*Users, *sqlgraph.CreateSpec) {
var (
_node = &Users{config: _c.config}
_spec = sqlgraph.NewCreateSpec(users.Table, sqlgraph.NewFieldSpec(users.FieldID, field.TypeInt64))
)
if id, ok := _c.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = id
}
if value, ok := _c.mutation.Username(); ok {
_spec.SetField(users.FieldUsername, field.TypeString, value)
_node.Username = value
}
if value, ok := _c.mutation.PasswordHash(); ok {
_spec.SetField(users.FieldPasswordHash, field.TypeString, value)
_node.PasswordHash = value
}
if value, ok := _c.mutation.Email(); ok {
_spec.SetField(users.FieldEmail, field.TypeString, value)
_node.Email = value
}
if value, ok := _c.mutation.Phone(); ok {
_spec.SetField(users.FieldPhone, field.TypeString, value)
_node.Phone = value
}
if value, ok := _c.mutation.Nickname(); ok {
_spec.SetField(users.FieldNickname, field.TypeString, value)
_node.Nickname = value
}
if value, ok := _c.mutation.Avatar(); ok {
_spec.SetField(users.FieldAvatar, field.TypeString, value)
_node.Avatar = value
}
if value, ok := _c.mutation.Bio(); ok {
_spec.SetField(users.FieldBio, field.TypeString, value)
_node.Bio = value
}
if value, ok := _c.mutation.CurrentRole(); ok {
_spec.SetField(users.FieldCurrentRole, field.TypeString, value)
_node.CurrentRole = value
}
if value, ok := _c.mutation.VerifiedRoles(); ok {
_spec.SetField(users.FieldVerifiedRoles, field.TypeJSON, value)
_node.VerifiedRoles = value
}
if value, ok := _c.mutation.VerificationStatus(); ok {
_spec.SetField(users.FieldVerificationStatus, field.TypeJSON, value)
_node.VerificationStatus = value
}
if value, ok := _c.mutation.IsAdmin(); ok {
_spec.SetField(users.FieldIsAdmin, field.TypeBool, value)
_node.IsAdmin = value
}
if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(users.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = value
}
if value, ok := _c.mutation.UpdatedAt(); ok {
_spec.SetField(users.FieldUpdatedAt, field.TypeTime, value)
_node.UpdatedAt = value
}
if value, ok := _c.mutation.DeletedAt(); ok {
_spec.SetField(users.FieldDeletedAt, field.TypeTime, value)
_node.DeletedAt = value
}
return _node, _spec
}
// UsersCreateBulk is the builder for creating many Users entities in bulk.
type UsersCreateBulk struct {
config
err error
builders []*UsersCreate
}
// Save creates the Users entities in the database.
func (_c *UsersCreateBulk) Save(ctx context.Context) ([]*Users, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*Users, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
builder.defaults()
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*UsersMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, _c.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, _c.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil && nodes[i].ID == 0 {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int64(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, _c.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (_c *UsersCreateBulk) SaveX(ctx context.Context) []*Users {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *UsersCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *UsersCreateBulk) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
@@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"juwan-backend/app/users/rpc/internal/models/predicate"
"juwan-backend/app/users/rpc/internal/models/users"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// UsersDelete is the builder for deleting a Users entity.
type UsersDelete struct {
config
hooks []Hook
mutation *UsersMutation
}
// Where appends a list predicates to the UsersDelete builder.
func (_d *UsersDelete) Where(ps ...predicate.Users) *UsersDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *UsersDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, _d.sqlExec, _d.mutation, _d.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *UsersDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *UsersDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(users.Table, sqlgraph.NewFieldSpec(users.FieldID, field.TypeInt64))
if ps := _d.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, _d.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
_d.mutation.done = true
return affected, err
}
// UsersDeleteOne is the builder for deleting a single Users entity.
type UsersDeleteOne struct {
_d *UsersDelete
}
// Where appends a list predicates to the UsersDelete builder.
func (_d *UsersDeleteOne) Where(ps ...predicate.Users) *UsersDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *UsersDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{users.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *UsersDeleteOne) ExecX(ctx context.Context) {
if err := _d.Exec(ctx); err != nil {
panic(err)
}
}
@@ -0,0 +1,527 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"fmt"
"juwan-backend/app/users/rpc/internal/models/predicate"
"juwan-backend/app/users/rpc/internal/models/users"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// UsersQuery is the builder for querying Users entities.
type UsersQuery struct {
config
ctx *QueryContext
order []users.OrderOption
inters []Interceptor
predicates []predicate.Users
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the UsersQuery builder.
func (_q *UsersQuery) Where(ps ...predicate.Users) *UsersQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *UsersQuery) Limit(limit int) *UsersQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *UsersQuery) Offset(offset int) *UsersQuery {
_q.ctx.Offset = &offset
return _q
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (_q *UsersQuery) Unique(unique bool) *UsersQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *UsersQuery) Order(o ...users.OrderOption) *UsersQuery {
_q.order = append(_q.order, o...)
return _q
}
// First returns the first Users entity from the query.
// Returns a *NotFoundError when no Users was found.
func (_q *UsersQuery) First(ctx context.Context) (*Users, error) {
nodes, err := _q.Limit(1).All(setContextOp(ctx, _q.ctx, ent.OpQueryFirst))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{users.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *UsersQuery) FirstX(ctx context.Context) *Users {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Users ID from the query.
// Returns a *NotFoundError when no Users ID was found.
func (_q *UsersQuery) FirstID(ctx context.Context) (id int64, err error) {
var ids []int64
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{users.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *UsersQuery) FirstIDX(ctx context.Context) int64 {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Users entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Users entity is found.
// Returns a *NotFoundError when no Users entities are found.
func (_q *UsersQuery) Only(ctx context.Context) (*Users, error) {
nodes, err := _q.Limit(2).All(setContextOp(ctx, _q.ctx, ent.OpQueryOnly))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{users.Label}
default:
return nil, &NotSingularError{users.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *UsersQuery) OnlyX(ctx context.Context) *Users {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Users ID in the query.
// Returns a *NotSingularError when more than one Users ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *UsersQuery) OnlyID(ctx context.Context) (id int64, err error) {
var ids []int64
if ids, err = _q.Limit(2).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryOnlyID)); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{users.Label}
default:
err = &NotSingularError{users.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *UsersQuery) OnlyIDX(ctx context.Context) int64 {
id, err := _q.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of UsersSlice.
func (_q *UsersQuery) All(ctx context.Context) ([]*Users, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Users, *UsersQuery]()
return withInterceptors[[]*Users](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *UsersQuery) AllX(ctx context.Context) []*Users {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Users IDs.
func (_q *UsersQuery) IDs(ctx context.Context) (ids []int64, err error) {
if _q.ctx.Unique == nil && _q.path != nil {
_q.Unique(true)
}
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
if err = _q.Select(users.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *UsersQuery) IDsX(ctx context.Context) []int64 {
ids, err := _q.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (_q *UsersQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryCount)
if err := _q.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, _q, querierCount[*UsersQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *UsersQuery) CountX(ctx context.Context) int {
count, err := _q.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (_q *UsersQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryExist)
switch _, err := _q.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("models: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (_q *UsersQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the UsersQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (_q *UsersQuery) Clone() *UsersQuery {
if _q == nil {
return nil
}
return &UsersQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]users.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.Users{}, _q.predicates...),
// clone intermediate query.
sql: _q.sql.Clone(),
path: _q.path,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// Username string `json:"username,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Users.Query().
// GroupBy(users.FieldUsername).
// Aggregate(models.Count()).
// Scan(ctx, &v)
func (_q *UsersQuery) GroupBy(field string, fields ...string) *UsersGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &UsersGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = users.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// Username string `json:"username,omitempty"`
// }
//
// client.Users.Query().
// Select(users.FieldUsername).
// Scan(ctx, &v)
func (_q *UsersQuery) Select(fields ...string) *UsersSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &UsersSelect{UsersQuery: _q}
sbuild.label = users.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a UsersSelect configured with the given aggregations.
func (_q *UsersQuery) Aggregate(fns ...AggregateFunc) *UsersSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *UsersQuery) prepareQuery(ctx context.Context) error {
for _, inter := range _q.inters {
if inter == nil {
return fmt.Errorf("models: uninitialized interceptor (forgotten import models/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, _q); err != nil {
return err
}
}
}
for _, f := range _q.ctx.Fields {
if !users.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)}
}
}
if _q.path != nil {
prev, err := _q.path(ctx)
if err != nil {
return err
}
_q.sql = prev
}
return nil
}
func (_q *UsersQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Users, error) {
var (
nodes = []*Users{}
_spec = _q.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Users).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Users{config: _q.config}
nodes = append(nodes, node)
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, _q.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (_q *UsersQuery) sqlCount(ctx context.Context) (int, error) {
_spec := _q.querySpec()
_spec.Node.Columns = _q.ctx.Fields
if len(_q.ctx.Fields) > 0 {
_spec.Unique = _q.ctx.Unique != nil && *_q.ctx.Unique
}
return sqlgraph.CountNodes(ctx, _q.driver, _spec)
}
func (_q *UsersQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(users.Table, users.Columns, sqlgraph.NewFieldSpec(users.FieldID, field.TypeInt64))
_spec.From = _q.sql
if unique := _q.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if _q.path != nil {
_spec.Unique = true
}
if fields := _q.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, users.FieldID)
for i := range fields {
if fields[i] != users.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := _q.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := _q.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := _q.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := _q.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (_q *UsersQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(users.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = users.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if _q.sql != nil {
selector = _q.sql
selector.Select(selector.Columns(columns...)...)
}
if _q.ctx.Unique != nil && *_q.ctx.Unique {
selector.Distinct()
}
for _, p := range _q.predicates {
p(selector)
}
for _, p := range _q.order {
p(selector)
}
if offset := _q.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := _q.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// UsersGroupBy is the group-by builder for Users entities.
type UsersGroupBy struct {
selector
build *UsersQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *UsersGroupBy) Aggregate(fns ...AggregateFunc) *UsersGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *UsersGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _g.build.ctx, ent.OpQueryGroupBy)
if err := _g.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*UsersQuery, *UsersGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *UsersGroupBy) sqlScan(ctx context.Context, root *UsersQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(_g.fns))
for _, fn := range _g.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*_g.flds)+len(_g.fns))
for _, f := range *_g.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*_g.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _g.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// UsersSelect is the builder for selecting fields of Users entities.
type UsersSelect struct {
*UsersQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *UsersSelect) Aggregate(fns ...AggregateFunc) *UsersSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *UsersSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, _s.ctx, ent.OpQuerySelect)
if err := _s.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*UsersQuery, *UsersSelect](ctx, _s.UsersQuery, _s, _s.inters, v)
}
func (_s *UsersSelect) sqlScan(ctx context.Context, root *UsersQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(_s.fns))
for _, fn := range _s.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*_s.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := _s.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
@@ -0,0 +1,660 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"errors"
"fmt"
"juwan-backend/app/users/rpc/internal/models/predicate"
"juwan-backend/app/users/rpc/internal/models/schema"
"juwan-backend/app/users/rpc/internal/models/users"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/dialect/sql/sqljson"
"entgo.io/ent/schema/field"
)
// UsersUpdate is the builder for updating Users entities.
type UsersUpdate struct {
config
hooks []Hook
mutation *UsersMutation
}
// Where appends a list predicates to the UsersUpdate builder.
func (_u *UsersUpdate) Where(ps ...predicate.Users) *UsersUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetUsername sets the "username" field.
func (_u *UsersUpdate) SetUsername(v string) *UsersUpdate {
_u.mutation.SetUsername(v)
return _u
}
// SetNillableUsername sets the "username" field if the given value is not nil.
func (_u *UsersUpdate) SetNillableUsername(v *string) *UsersUpdate {
if v != nil {
_u.SetUsername(*v)
}
return _u
}
// SetPasswordHash sets the "password_hash" field.
func (_u *UsersUpdate) SetPasswordHash(v string) *UsersUpdate {
_u.mutation.SetPasswordHash(v)
return _u
}
// SetNillablePasswordHash sets the "password_hash" field if the given value is not nil.
func (_u *UsersUpdate) SetNillablePasswordHash(v *string) *UsersUpdate {
if v != nil {
_u.SetPasswordHash(*v)
}
return _u
}
// SetEmail sets the "email" field.
func (_u *UsersUpdate) SetEmail(v string) *UsersUpdate {
_u.mutation.SetEmail(v)
return _u
}
// SetNillableEmail sets the "email" field if the given value is not nil.
func (_u *UsersUpdate) SetNillableEmail(v *string) *UsersUpdate {
if v != nil {
_u.SetEmail(*v)
}
return _u
}
// SetPhone sets the "phone" field.
func (_u *UsersUpdate) SetPhone(v string) *UsersUpdate {
_u.mutation.SetPhone(v)
return _u
}
// SetNillablePhone sets the "phone" field if the given value is not nil.
func (_u *UsersUpdate) SetNillablePhone(v *string) *UsersUpdate {
if v != nil {
_u.SetPhone(*v)
}
return _u
}
// SetNickname sets the "nickname" field.
func (_u *UsersUpdate) SetNickname(v string) *UsersUpdate {
_u.mutation.SetNickname(v)
return _u
}
// SetNillableNickname sets the "nickname" field if the given value is not nil.
func (_u *UsersUpdate) SetNillableNickname(v *string) *UsersUpdate {
if v != nil {
_u.SetNickname(*v)
}
return _u
}
// SetAvatar sets the "avatar" field.
func (_u *UsersUpdate) SetAvatar(v string) *UsersUpdate {
_u.mutation.SetAvatar(v)
return _u
}
// SetNillableAvatar sets the "avatar" field if the given value is not nil.
func (_u *UsersUpdate) SetNillableAvatar(v *string) *UsersUpdate {
if v != nil {
_u.SetAvatar(*v)
}
return _u
}
// SetBio sets the "bio" field.
func (_u *UsersUpdate) SetBio(v string) *UsersUpdate {
_u.mutation.SetBio(v)
return _u
}
// SetNillableBio sets the "bio" field if the given value is not nil.
func (_u *UsersUpdate) SetNillableBio(v *string) *UsersUpdate {
if v != nil {
_u.SetBio(*v)
}
return _u
}
// SetCurrentRole sets the "current_role" field.
func (_u *UsersUpdate) SetCurrentRole(v string) *UsersUpdate {
_u.mutation.SetCurrentRole(v)
return _u
}
// SetNillableCurrentRole sets the "current_role" field if the given value is not nil.
func (_u *UsersUpdate) SetNillableCurrentRole(v *string) *UsersUpdate {
if v != nil {
_u.SetCurrentRole(*v)
}
return _u
}
// SetVerifiedRoles sets the "verified_roles" field.
func (_u *UsersUpdate) SetVerifiedRoles(v []string) *UsersUpdate {
_u.mutation.SetVerifiedRoles(v)
return _u
}
// AppendVerifiedRoles appends value to the "verified_roles" field.
func (_u *UsersUpdate) AppendVerifiedRoles(v []string) *UsersUpdate {
_u.mutation.AppendVerifiedRoles(v)
return _u
}
// SetVerificationStatus sets the "verificationStatus" field.
func (_u *UsersUpdate) SetVerificationStatus(v schema.VerificationStatusStruct) *UsersUpdate {
_u.mutation.SetVerificationStatus(v)
return _u
}
// SetNillableVerificationStatus sets the "verificationStatus" field if the given value is not nil.
func (_u *UsersUpdate) SetNillableVerificationStatus(v *schema.VerificationStatusStruct) *UsersUpdate {
if v != nil {
_u.SetVerificationStatus(*v)
}
return _u
}
// SetIsAdmin sets the "is_admin" field.
func (_u *UsersUpdate) SetIsAdmin(v bool) *UsersUpdate {
_u.mutation.SetIsAdmin(v)
return _u
}
// SetNillableIsAdmin sets the "is_admin" field if the given value is not nil.
func (_u *UsersUpdate) SetNillableIsAdmin(v *bool) *UsersUpdate {
if v != nil {
_u.SetIsAdmin(*v)
}
return _u
}
// SetCreatedAt sets the "created_at" field.
func (_u *UsersUpdate) SetCreatedAt(v time.Time) *UsersUpdate {
_u.mutation.SetCreatedAt(v)
return _u
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_u *UsersUpdate) SetNillableCreatedAt(v *time.Time) *UsersUpdate {
if v != nil {
_u.SetCreatedAt(*v)
}
return _u
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *UsersUpdate) SetUpdatedAt(v time.Time) *UsersUpdate {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_u *UsersUpdate) SetNillableUpdatedAt(v *time.Time) *UsersUpdate {
if v != nil {
_u.SetUpdatedAt(*v)
}
return _u
}
// SetDeletedAt sets the "deleted_at" field.
func (_u *UsersUpdate) SetDeletedAt(v time.Time) *UsersUpdate {
_u.mutation.SetDeletedAt(v)
return _u
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *UsersUpdate) SetNillableDeletedAt(v *time.Time) *UsersUpdate {
if v != nil {
_u.SetDeletedAt(*v)
}
return _u
}
// Mutation returns the UsersMutation object of the builder.
func (_u *UsersUpdate) Mutation() *UsersMutation {
return _u.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *UsersUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *UsersUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *UsersUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *UsersUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
func (_u *UsersUpdate) sqlSave(ctx context.Context) (_node int, err error) {
_spec := sqlgraph.NewUpdateSpec(users.Table, users.Columns, sqlgraph.NewFieldSpec(users.FieldID, field.TypeInt64))
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Username(); ok {
_spec.SetField(users.FieldUsername, field.TypeString, value)
}
if value, ok := _u.mutation.PasswordHash(); ok {
_spec.SetField(users.FieldPasswordHash, field.TypeString, value)
}
if value, ok := _u.mutation.Email(); ok {
_spec.SetField(users.FieldEmail, field.TypeString, value)
}
if value, ok := _u.mutation.Phone(); ok {
_spec.SetField(users.FieldPhone, field.TypeString, value)
}
if value, ok := _u.mutation.Nickname(); ok {
_spec.SetField(users.FieldNickname, field.TypeString, value)
}
if value, ok := _u.mutation.Avatar(); ok {
_spec.SetField(users.FieldAvatar, field.TypeString, value)
}
if value, ok := _u.mutation.Bio(); ok {
_spec.SetField(users.FieldBio, field.TypeString, value)
}
if value, ok := _u.mutation.CurrentRole(); ok {
_spec.SetField(users.FieldCurrentRole, field.TypeString, value)
}
if value, ok := _u.mutation.VerifiedRoles(); ok {
_spec.SetField(users.FieldVerifiedRoles, field.TypeJSON, value)
}
if value, ok := _u.mutation.AppendedVerifiedRoles(); ok {
_spec.AddModifier(func(u *sql.UpdateBuilder) {
sqljson.Append(u, users.FieldVerifiedRoles, value)
})
}
if value, ok := _u.mutation.VerificationStatus(); ok {
_spec.SetField(users.FieldVerificationStatus, field.TypeJSON, value)
}
if value, ok := _u.mutation.IsAdmin(); ok {
_spec.SetField(users.FieldIsAdmin, field.TypeBool, value)
}
if value, ok := _u.mutation.CreatedAt(); ok {
_spec.SetField(users.FieldCreatedAt, field.TypeTime, value)
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(users.FieldUpdatedAt, field.TypeTime, value)
}
if value, ok := _u.mutation.DeletedAt(); ok {
_spec.SetField(users.FieldDeletedAt, field.TypeTime, value)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{users.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// UsersUpdateOne is the builder for updating a single Users entity.
type UsersUpdateOne struct {
config
fields []string
hooks []Hook
mutation *UsersMutation
}
// SetUsername sets the "username" field.
func (_u *UsersUpdateOne) SetUsername(v string) *UsersUpdateOne {
_u.mutation.SetUsername(v)
return _u
}
// SetNillableUsername sets the "username" field if the given value is not nil.
func (_u *UsersUpdateOne) SetNillableUsername(v *string) *UsersUpdateOne {
if v != nil {
_u.SetUsername(*v)
}
return _u
}
// SetPasswordHash sets the "password_hash" field.
func (_u *UsersUpdateOne) SetPasswordHash(v string) *UsersUpdateOne {
_u.mutation.SetPasswordHash(v)
return _u
}
// SetNillablePasswordHash sets the "password_hash" field if the given value is not nil.
func (_u *UsersUpdateOne) SetNillablePasswordHash(v *string) *UsersUpdateOne {
if v != nil {
_u.SetPasswordHash(*v)
}
return _u
}
// SetEmail sets the "email" field.
func (_u *UsersUpdateOne) SetEmail(v string) *UsersUpdateOne {
_u.mutation.SetEmail(v)
return _u
}
// SetNillableEmail sets the "email" field if the given value is not nil.
func (_u *UsersUpdateOne) SetNillableEmail(v *string) *UsersUpdateOne {
if v != nil {
_u.SetEmail(*v)
}
return _u
}
// SetPhone sets the "phone" field.
func (_u *UsersUpdateOne) SetPhone(v string) *UsersUpdateOne {
_u.mutation.SetPhone(v)
return _u
}
// SetNillablePhone sets the "phone" field if the given value is not nil.
func (_u *UsersUpdateOne) SetNillablePhone(v *string) *UsersUpdateOne {
if v != nil {
_u.SetPhone(*v)
}
return _u
}
// SetNickname sets the "nickname" field.
func (_u *UsersUpdateOne) SetNickname(v string) *UsersUpdateOne {
_u.mutation.SetNickname(v)
return _u
}
// SetNillableNickname sets the "nickname" field if the given value is not nil.
func (_u *UsersUpdateOne) SetNillableNickname(v *string) *UsersUpdateOne {
if v != nil {
_u.SetNickname(*v)
}
return _u
}
// SetAvatar sets the "avatar" field.
func (_u *UsersUpdateOne) SetAvatar(v string) *UsersUpdateOne {
_u.mutation.SetAvatar(v)
return _u
}
// SetNillableAvatar sets the "avatar" field if the given value is not nil.
func (_u *UsersUpdateOne) SetNillableAvatar(v *string) *UsersUpdateOne {
if v != nil {
_u.SetAvatar(*v)
}
return _u
}
// SetBio sets the "bio" field.
func (_u *UsersUpdateOne) SetBio(v string) *UsersUpdateOne {
_u.mutation.SetBio(v)
return _u
}
// SetNillableBio sets the "bio" field if the given value is not nil.
func (_u *UsersUpdateOne) SetNillableBio(v *string) *UsersUpdateOne {
if v != nil {
_u.SetBio(*v)
}
return _u
}
// SetCurrentRole sets the "current_role" field.
func (_u *UsersUpdateOne) SetCurrentRole(v string) *UsersUpdateOne {
_u.mutation.SetCurrentRole(v)
return _u
}
// SetNillableCurrentRole sets the "current_role" field if the given value is not nil.
func (_u *UsersUpdateOne) SetNillableCurrentRole(v *string) *UsersUpdateOne {
if v != nil {
_u.SetCurrentRole(*v)
}
return _u
}
// SetVerifiedRoles sets the "verified_roles" field.
func (_u *UsersUpdateOne) SetVerifiedRoles(v []string) *UsersUpdateOne {
_u.mutation.SetVerifiedRoles(v)
return _u
}
// AppendVerifiedRoles appends value to the "verified_roles" field.
func (_u *UsersUpdateOne) AppendVerifiedRoles(v []string) *UsersUpdateOne {
_u.mutation.AppendVerifiedRoles(v)
return _u
}
// SetVerificationStatus sets the "verificationStatus" field.
func (_u *UsersUpdateOne) SetVerificationStatus(v schema.VerificationStatusStruct) *UsersUpdateOne {
_u.mutation.SetVerificationStatus(v)
return _u
}
// SetNillableVerificationStatus sets the "verificationStatus" field if the given value is not nil.
func (_u *UsersUpdateOne) SetNillableVerificationStatus(v *schema.VerificationStatusStruct) *UsersUpdateOne {
if v != nil {
_u.SetVerificationStatus(*v)
}
return _u
}
// SetIsAdmin sets the "is_admin" field.
func (_u *UsersUpdateOne) SetIsAdmin(v bool) *UsersUpdateOne {
_u.mutation.SetIsAdmin(v)
return _u
}
// SetNillableIsAdmin sets the "is_admin" field if the given value is not nil.
func (_u *UsersUpdateOne) SetNillableIsAdmin(v *bool) *UsersUpdateOne {
if v != nil {
_u.SetIsAdmin(*v)
}
return _u
}
// SetCreatedAt sets the "created_at" field.
func (_u *UsersUpdateOne) SetCreatedAt(v time.Time) *UsersUpdateOne {
_u.mutation.SetCreatedAt(v)
return _u
}
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (_u *UsersUpdateOne) SetNillableCreatedAt(v *time.Time) *UsersUpdateOne {
if v != nil {
_u.SetCreatedAt(*v)
}
return _u
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *UsersUpdateOne) SetUpdatedAt(v time.Time) *UsersUpdateOne {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_u *UsersUpdateOne) SetNillableUpdatedAt(v *time.Time) *UsersUpdateOne {
if v != nil {
_u.SetUpdatedAt(*v)
}
return _u
}
// SetDeletedAt sets the "deleted_at" field.
func (_u *UsersUpdateOne) SetDeletedAt(v time.Time) *UsersUpdateOne {
_u.mutation.SetDeletedAt(v)
return _u
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_u *UsersUpdateOne) SetNillableDeletedAt(v *time.Time) *UsersUpdateOne {
if v != nil {
_u.SetDeletedAt(*v)
}
return _u
}
// Mutation returns the UsersMutation object of the builder.
func (_u *UsersUpdateOne) Mutation() *UsersMutation {
return _u.mutation
}
// Where appends a list predicates to the UsersUpdate builder.
func (_u *UsersUpdateOne) Where(ps ...predicate.Users) *UsersUpdateOne {
_u.mutation.Where(ps...)
return _u
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (_u *UsersUpdateOne) Select(field string, fields ...string) *UsersUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated Users entity.
func (_u *UsersUpdateOne) Save(ctx context.Context) (*Users, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *UsersUpdateOne) SaveX(ctx context.Context) *Users {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *UsersUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *UsersUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
func (_u *UsersUpdateOne) sqlSave(ctx context.Context) (_node *Users, err error) {
_spec := sqlgraph.NewUpdateSpec(users.Table, users.Columns, sqlgraph.NewFieldSpec(users.FieldID, field.TypeInt64))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "Users.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := _u.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, users.FieldID)
for _, f := range fields {
if !users.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)}
}
if f != users.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := _u.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := _u.mutation.Username(); ok {
_spec.SetField(users.FieldUsername, field.TypeString, value)
}
if value, ok := _u.mutation.PasswordHash(); ok {
_spec.SetField(users.FieldPasswordHash, field.TypeString, value)
}
if value, ok := _u.mutation.Email(); ok {
_spec.SetField(users.FieldEmail, field.TypeString, value)
}
if value, ok := _u.mutation.Phone(); ok {
_spec.SetField(users.FieldPhone, field.TypeString, value)
}
if value, ok := _u.mutation.Nickname(); ok {
_spec.SetField(users.FieldNickname, field.TypeString, value)
}
if value, ok := _u.mutation.Avatar(); ok {
_spec.SetField(users.FieldAvatar, field.TypeString, value)
}
if value, ok := _u.mutation.Bio(); ok {
_spec.SetField(users.FieldBio, field.TypeString, value)
}
if value, ok := _u.mutation.CurrentRole(); ok {
_spec.SetField(users.FieldCurrentRole, field.TypeString, value)
}
if value, ok := _u.mutation.VerifiedRoles(); ok {
_spec.SetField(users.FieldVerifiedRoles, field.TypeJSON, value)
}
if value, ok := _u.mutation.AppendedVerifiedRoles(); ok {
_spec.AddModifier(func(u *sql.UpdateBuilder) {
sqljson.Append(u, users.FieldVerifiedRoles, value)
})
}
if value, ok := _u.mutation.VerificationStatus(); ok {
_spec.SetField(users.FieldVerificationStatus, field.TypeJSON, value)
}
if value, ok := _u.mutation.IsAdmin(); ok {
_spec.SetField(users.FieldIsAdmin, field.TypeBool, value)
}
if value, ok := _u.mutation.CreatedAt(); ok {
_spec.SetField(users.FieldCreatedAt, field.TypeTime, value)
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(users.FieldUpdatedAt, field.TypeTime, value)
}
if value, ok := _u.mutation.DeletedAt(); ok {
_spec.SetField(users.FieldDeletedAt, field.TypeTime, value)
}
_node = &Users{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{users.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}
@@ -78,3 +78,8 @@ func (s *UsercenterServer) Logout(ctx context.Context, in *pb.LogoutReq) (*pb.Lo
l := logic.NewLogoutLogic(ctx, s.svcCtx)
return l.Logout(in)
}
func (s *UsercenterServer) ResetPassword(ctx context.Context, in *pb.ResetPasswordReq) (*pb.ResetPasswordResp, error) {
l := logic.NewResetPasswordLogic(ctx, s.svcCtx)
return l.ResetPassword(in)
}
+25 -14
View File
@@ -7,49 +7,60 @@ import (
"juwan-backend/app/users/rpc/internal/utils"
"juwan-backend/common/redisx"
"juwan-backend/common/snowflakex"
"juwan-backend/pkg/adapter"
"time"
"ariga.io/entcache"
"entgo.io/ent/dialect/sql"
"github.com/redis/go-redis/v9"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type ServiceContext struct {
Config config.Config
UsersModelRW models.UsersModel
UsersModelRO models.UsersModel
UsersModelRW *models.UsersClient
UsersModelRO *models.UsersClient
RedisCluster *redis.ClusterClient
Snowflake snowflake.SnowflakeServiceClient
JwtManager *utils.JwtManager
}
func NewServiceContext(c config.Config) *ServiceContext {
RWDBConn := sqlx.NewSqlConn("postgres", c.DB.Master)
RODBConn := sqlx.NewSqlConn("postgres", c.DB.Slave)
RWConn, err := sql.Open("pgx", c.DB.Master)
if err != nil {
panic(err)
}
ROConn, err := sql.Open("pgx", c.DB.Slave)
if err != nil {
panic(err)
}
logx.Infof("success to connect to postgres~")
// Initialize Redis Cluster client from CacheConf
redisConn, err := redisx.ConnectMasterSlaveCluster(c.CacheConf, 5*time.Second)
if err != nil || redisConn == nil {
logx.Errorf("redis connect master error: %s", err)
panic(err)
}
redisCluster := redisConn.Client
if redisCluster != nil {
if err != nil {
logx.Errorf("failed to connect to redis cluster: %v", err)
if redisConn.HasSlave {
logx.Infof("success to connect to redis master/slave (M: %s, S: %s)", redisConn.MasterHost, redisConn.SlaveHost)
} else {
if redisConn.HasSlave {
logx.Infof("success to connect to redis master/slave (M: %s, S: %s)", redisConn.MasterHost, redisConn.SlaveHost)
} else {
logx.Infof("success to connect to redis master (M: %s), slave not configured", redisConn.MasterHost)
}
logx.Infof("success to connect to redis master (M: %s), slave not configured", redisConn.MasterHost)
}
}
// Initialize JWT Manager
jwtManager := utils.NewJwtManager(redisCluster, c.Jwt.SecretKey, c.Jwt.Issuer)
RODrv := entcache.NewDriver(ROConn, entcache.TTL(time.Second*30), entcache.Levels(adapter.NewRedisCache(redisCluster)))
RWDrv := entcache.NewDriver(RWConn, entcache.TTL(time.Second*30), entcache.Levels(adapter.NewRedisCache(redisCluster)))
return &ServiceContext{
Config: c,
UsersModelRW: models.NewUsersModel(RWDBConn, c.CacheConf),
UsersModelRO: models.NewUsersModel(RODBConn, c.CacheConf),
UsersModelRW: models.NewClient(models.Driver(RWDrv)).Users,
UsersModelRO: models.NewClient(models.Driver(RODrv)).Users,
RedisCluster: redisCluster,
JwtManager: jwtManager,
Snowflake: snowflakex.NewClient(c.SnowflakeRpcConf),
File diff suppressed because it is too large Load Diff
+39 -1
View File
@@ -1,7 +1,7 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.6.1
// - protoc v5.29.6
// - protoc v3.19.4
// source: users.proto
package pb
@@ -30,6 +30,7 @@ const (
Usercenter_ValidateToken_FullMethodName = "/pb.usercenter/ValidateToken"
Usercenter_CheckPermission_FullMethodName = "/pb.usercenter/CheckPermission"
Usercenter_Logout_FullMethodName = "/pb.usercenter/Logout"
Usercenter_ResetPassword_FullMethodName = "/pb.usercenter/ResetPassword"
)
// UsercenterClient is the client API for Usercenter service.
@@ -48,6 +49,7 @@ type UsercenterClient interface {
ValidateToken(ctx context.Context, in *ValidateTokenReq, opts ...grpc.CallOption) (*ValidateTokenResp, error)
CheckPermission(ctx context.Context, in *CheckPermissionReq, opts ...grpc.CallOption) (*CheckPermissionResp, error)
Logout(ctx context.Context, in *LogoutReq, opts ...grpc.CallOption) (*LogoutResp, error)
ResetPassword(ctx context.Context, in *ResetPasswordReq, opts ...grpc.CallOption) (*ResetPasswordResp, error)
}
type usercenterClient struct {
@@ -168,6 +170,16 @@ func (c *usercenterClient) Logout(ctx context.Context, in *LogoutReq, opts ...gr
return out, nil
}
func (c *usercenterClient) ResetPassword(ctx context.Context, in *ResetPasswordReq, opts ...grpc.CallOption) (*ResetPasswordResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(ResetPasswordResp)
err := c.cc.Invoke(ctx, Usercenter_ResetPassword_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// UsercenterServer is the server API for Usercenter service.
// All implementations must embed UnimplementedUsercenterServer
// for forward compatibility.
@@ -184,6 +196,7 @@ type UsercenterServer interface {
ValidateToken(context.Context, *ValidateTokenReq) (*ValidateTokenResp, error)
CheckPermission(context.Context, *CheckPermissionReq) (*CheckPermissionResp, error)
Logout(context.Context, *LogoutReq) (*LogoutResp, error)
ResetPassword(context.Context, *ResetPasswordReq) (*ResetPasswordResp, error)
mustEmbedUnimplementedUsercenterServer()
}
@@ -227,6 +240,9 @@ func (UnimplementedUsercenterServer) CheckPermission(context.Context, *CheckPerm
func (UnimplementedUsercenterServer) Logout(context.Context, *LogoutReq) (*LogoutResp, error) {
return nil, status.Error(codes.Unimplemented, "method Logout not implemented")
}
func (UnimplementedUsercenterServer) ResetPassword(context.Context, *ResetPasswordReq) (*ResetPasswordResp, error) {
return nil, status.Error(codes.Unimplemented, "method ResetPassword not implemented")
}
func (UnimplementedUsercenterServer) mustEmbedUnimplementedUsercenterServer() {}
func (UnimplementedUsercenterServer) testEmbeddedByValue() {}
@@ -446,6 +462,24 @@ func _Usercenter_Logout_Handler(srv interface{}, ctx context.Context, dec func(i
return interceptor(ctx, in, info, handler)
}
func _Usercenter_ResetPassword_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ResetPasswordReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UsercenterServer).ResetPassword(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Usercenter_ResetPassword_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UsercenterServer).ResetPassword(ctx, req.(*ResetPasswordReq))
}
return interceptor(ctx, in, info, handler)
}
// Usercenter_ServiceDesc is the grpc.ServiceDesc for Usercenter service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
@@ -497,6 +531,10 @@ var Usercenter_ServiceDesc = grpc.ServiceDesc{
MethodName: "Logout",
Handler: _Usercenter_Logout_Handler,
},
{
MethodName: "ResetPassword",
Handler: _Usercenter_ResetPassword_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "users.proto",
+8
View File
@@ -30,6 +30,8 @@ type (
LogoutResp = pb.LogoutResp
RegisterReq = pb.RegisterReq
RegisterResp = pb.RegisterResp
ResetPasswordReq = pb.ResetPasswordReq
ResetPasswordResp = pb.ResetPasswordResp
SearchUsersReq = pb.SearchUsersReq
SearchUsersResp = pb.SearchUsersResp
UpdateUsersReq = pb.UpdateUsersReq
@@ -51,6 +53,7 @@ type (
ValidateToken(ctx context.Context, in *ValidateTokenReq, opts ...grpc.CallOption) (*ValidateTokenResp, error)
CheckPermission(ctx context.Context, in *CheckPermissionReq, opts ...grpc.CallOption) (*CheckPermissionResp, error)
Logout(ctx context.Context, in *LogoutReq, opts ...grpc.CallOption) (*LogoutResp, error)
ResetPassword(ctx context.Context, in *ResetPasswordReq, opts ...grpc.CallOption) (*ResetPasswordResp, error)
}
defaultUsercenter struct {
@@ -119,3 +122,8 @@ func (m *defaultUsercenter) Logout(ctx context.Context, in *LogoutReq, opts ...g
client := pb.NewUsercenterClient(m.cli.Conn())
return client.Logout(ctx, in, opts...)
}
func (m *defaultUsercenter) ResetPassword(ctx context.Context, in *ResetPasswordReq, opts ...grpc.CallOption) (*ResetPasswordResp, error) {
client := pb.NewUsercenterClient(m.cli.Conn())
return client.ResetPassword(ctx, in, opts...)
}