fix: some api bug

This commit is contained in:
wwweww
2026-03-31 22:12:06 +08:00
parent c5ff4f0216
commit e7970ac25f
219 changed files with 16195 additions and 2126 deletions
-601
View File
@@ -1,601 +0,0 @@
# JWT 集成指南
指导如何将 JWT Manager 集成到 RPC Handlers 和业务逻辑中。
## 1. gRPC Unary Interceptor 实现
在 RPC 服务中添加 JWT 验证拦截器。
### 创建拦截器
创建文件 [app/users/rpc/internal/interceptor/jwt_interceptor.go](../../../app/users/rpc/internal/interceptor/jwt_interceptor.go)
```go
package interceptor
import (
"context"
"log"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"yourmodule/app/users/rpc/internal/svc"
)
// JwtUnaryInterceptor 验证 gRPC 请求中的 JWT 令牌
func JwtUnaryInterceptor(svcCtx *svc.ServiceContext) grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
// 获取请求元数据
md, ok := metadata.FromIncomingContext(ctx)
if !ok {
return nil, status.Error(codes.Unauthenticated, "missing metadata")
}
// 从 Authorization 头提取令牌
tokens := md.Get("authorization")
if len(tokens) == 0 {
return nil, status.Error(codes.Unauthenticated, "missing authorization header")
}
token := tokens[0]
// 验证令牌
claims, err := svcCtx.JwtManager.Valid(ctx, token)
if err != nil {
log.Printf("Token validation failed: %v", err)
// 尝试刷新令牌(如果过期但仍在 Redis 中)
newToken, refreshErr := svcCtx.JwtManager.Renew(ctx, token)
if refreshErr == nil && newToken != "" {
// 在响应头中返回新令牌
grpc.SetHeader(ctx, metadata.Pairs("authorization", newToken))
// 继续处理请求,使用原令牌的声明
// 注意:实际应用中需要重新验证新令牌
newClaims, err := svcCtx.JwtManager.Valid(ctx, newToken)
if err != nil {
return nil, status.Error(codes.Unauthenticated, "token refresh failed")
}
claims = newClaims
} else {
return nil, status.Error(codes.Unauthenticated, "invalid or expired token")
}
}
// 将声明附加到上下文,供处理器使用
newCtx := context.WithValue(ctx, "claims", claims)
return handler(newCtx, req)
}
}
// JwtStreamInterceptor 验证流式 gRPC 请求中的 JWT 令牌
func JwtStreamInterceptor(svcCtx *svc.ServiceContext) grpc.StreamServerInterceptor {
return func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
md, ok := metadata.FromIncomingContext(ss.Context())
if !ok {
return status.Error(codes.Unauthenticated, "missing metadata")
}
tokens := md.Get("authorization")
if len(tokens) == 0 {
return status.Error(codes.Unauthenticated, "missing authorization header")
}
token := tokens[0]
claims, err := svcCtx.JwtManager.Valid(ss.Context(), token)
if err != nil {
return status.Error(codes.Unauthenticated, "invalid token")
}
// 创建包装流以注入上下文
wrappedStream := &WrappedStream{
ServerStream: ss,
ctx: context.WithValue(ss.Context(), "claims", claims),
}
return handler(srv, wrappedStream)
}
}
// WrappedStream 包装 grpc.ServerStream 以注入新的上下文
type WrappedStream struct {
grpc.ServerStream
ctx context.Context
}
func (w *WrappedStream) Context() context.Context {
return w.ctx
}
```
### 在 Server 中注册拦截器
修改 [app/users/rpc/usercenter/usercenter.go](../../../app/users/rpc/usercenter/usercenter.go)
```go
package main
import (
"flag"
"fmt"
"log"
"yourmodule/app/users/rpc/internal/config"
"yourmodule/app/users/rpc/internal/interceptor"
"yourmodule/app/users/rpc/internal/server"
"yourmodule/app/users/rpc/internal/svc"
"yourmodule/app/users/rpc/pb"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/core/logx"
"google.golang.org/grpc"
)
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)
logx.DisableStat()
s := grpc.NewServer(
grpc.UnaryInterceptor(interceptor.JwtUnaryInterceptor(ctx)),
grpc.StreamInterceptor(interceptor.JwtStreamInterceptor(ctx)),
)
pb.RegisterUsercenterServer(s, server.NewUsercenterServer(ctx))
logx.Infof("Starting gRPC server on %s:%d", c.Host, c.Port)
if err := s.Serve(net.Listen("tcp", "0.0.0.0:"+fmt.Sprintf("%d", c.Port))); err != nil {
logx.Error(err)
}
}
```
## 2. 登录 Handler 实现
实现 [app/users/api/internal/handler/user/loginHandler.go](../../../app/users/api/internal/handler/user/loginHandler.go)
```go
package user
import (
"context"
"log"
"net/http"
"yourmodule/app/users/api/internal/logic/user"
"yourmodule/app/users/api/internal/svc"
"yourmodule/app/users/api/internal/types"
)
// LoginHandler 处理用户登录
func LoginHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.LoginRequest
// 解析请求体...
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
// 调用业务逻辑
resp, err := user.NewLoginLogic(r.Context(), svcCtx).Login(&req)
if err != nil {
log.Printf("Login failed: %v", err)
http.Error(w, "Login failed", http.StatusUnauthorized)
return
}
// 返回令牌
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
}
```
实现 [app/users/api/internal/logic/user/loginLogic.go](../../../app/users/api/internal/logic/user/loginLogic.go)
```go
package user
import (
"context"
"errors"
"yourmodule/app/users/api/internal/svc"
"yourmodule/app/users/api/internal/types"
)
type LoginLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
}
func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
return &LoginLogic{
ctx: ctx,
svcCtx: svcCtx,
}
}
func (l *LoginLogic) Login(req *types.LoginRequest) (*types.LoginResponse, error) {
// 1. 验证用户凭证(密码等)
user, err := l.svcCtx.UserModel.FindByEmail(l.ctx, req.Email)
if err != nil {
return nil, errors.New("user not found")
}
// 2. 验证密码
if !user.VerifyPassword(req.Password) {
return nil, errors.New("invalid password")
}
// 3. 生成 JWT 令牌
token, err := l.svcCtx.JwtManager.New(
l.ctx,
user.ID,
user.Email,
user.Name,
)
if err != nil {
return nil, errors.New("failed to generate token")
}
// 4. 返回令牌
return &types.LoginResponse{
Token: token,
User: types.User{
ID: user.ID,
Email: user.Email,
Name: user.Name,
},
}, nil
}
```
## 3. 在 Handlers 中使用声明
在 Protected Handlers 中提取并使用声明:
```go
package user
import (
"context"
"log"
"net/http"
"yourmodule/app/users/api/internal/svc"
"yourmodule/app/users/api/internal/types"
"github.com/golang-jwt/jwt/v4"
)
// GetUserInfoHandler 获取当前用户信息
func GetUserInfoHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 从上下文提取声明(由拦截器设置)
claims, ok := r.Context().Value("claims").(*jwt.RegisteredClaims)
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
// 使用声明中的用户信息
userID := claims.Subject // 用户 ID 存储在 Subject 中
log.Printf("User %s requested their info", userID)
// 查询用户信息
user, err := svcCtx.UserModel.FindByID(r.Context(), userID)
if err != nil {
http.Error(w, "User not found", http.StatusNotFound)
return
}
// 返回用户信息
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(user)
}
}
```
## 4. 令牌刷新端点
实现令牌刷新端点:
```go
package user
import (
"net/http"
"yourmodule/app/users/api/internal/svc"
"yourmodule/app/users/api/internal/types"
)
// RefreshTokenHandler 刷新过期的 JWT 令牌
func RefreshTokenHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
var req types.RefreshTokenRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "Invalid request", http.StatusBadRequest)
return
}
// 提取旧令牌
oldToken := req.Token
// 尝试刷新令牌
newToken, err := svcCtx.JwtManager.Renew(r.Context(), oldToken)
if err != nil {
http.Error(w, "Token refresh failed", http.StatusUnauthorized)
return
}
// 返回新令牌
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(types.RefreshTokenResponse{
Token: newToken,
})
}
}
```
## 5. 登出处理
实现登出端点以撤销令牌:
```go
package user
import (
"net/http"
"yourmodule/app/users/api/internal/svc"
)
// LogoutHandler 登出用户(撤销令牌)
func LogoutHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
// 从上下文提取声明
claims, ok := r.Context().Value("claims").(*jwt.RegisteredClaims)
if !ok {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
userID := claims.Subject
// 获取用户当前令牌
currentToken := r.Header.Get("Authorization")
// 撤销令牌
err := svcCtx.JwtManager.Revoke(r.Context(), userID, currentToken)
if err != nil {
http.Error(w, "Logout failed", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"message": "logged out successfully"})
}
}
```
## 6. 特定端点的 JWT 验证
对于 REST API,在需要的 handlers 中手动验证令牌:
### 在 Routes 中配置
修改 [app/users/api/internal/handler/routes.go](../../../app/users/api/internal/handler/routes.go)
```go
package handler
import (
"net/http"
"yourmodule/app/users/api/internal/middleware"
"yourmodule/app/users/api/internal/svc"
"yourmodule/app/users/api/internal/handler/user"
)
// RegisterRoutes 注册所有路由
func RegisterRoutes(router *http.ServeMux, svcCtx *svc.ServiceContext) {
// 公开路由
router.HandleFunc("POST /api/v1/auth/login", user.LoginHandler(svcCtx))
router.HandleFunc("POST /api/v1/auth/refresh", user.RefreshTokenHandler(svcCtx))
// 受保护的路由(需要 JWT 验证)
protected := middleware.JwtMiddleware(svcCtx)
router.HandleFunc("GET /api/v1/users/me", protected(user.GetUserInfoHandler(svcCtx)))
router.HandleFunc("POST /api/v1/users/logout", protected(user.LogoutHandler(svcCtx)))
router.HandleFunc("PUT /api/v1/users/me", protected(user.UpdateUserInfoHandler(svcCtx)))
}
```
### 创建 JWT 中间件
创建 [app/users/api/internal/middleware/jwt.go](../../../app/users/api/internal/middleware/jwt.go)
```go
package middleware
import (
"context"
"net/http"
"strings"
"yourmodule/app/users/api/internal/svc"
)
// JwtMiddleware 为 HTTP 处理器添加 JWT 验证
func JwtMiddleware(svcCtx *svc.ServiceContext) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// 从 Authorization 头提取令牌
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
http.Error(w, "Missing authorization header", http.StatusUnauthorized)
return
}
// 期望格式: "Bearer <token>"
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || parts[0] != "Bearer" {
http.Error(w, "Invalid authorization header", http.StatusUnauthorized)
return
}
token := parts[1]
// 验证令牌
claims, err := svcCtx.JwtManager.Valid(r.Context(), token)
if err != nil {
// 尝试刷新
newToken, refreshErr := svcCtx.JwtManager.Renew(r.Context(), token)
if refreshErr != nil {
http.Error(w, "Invalid or expired token", http.StatusUnauthorized)
return
}
// 在响应头返回新令牌
w.Header().Set("X-New-Token", newToken)
// 重新验证新令牌
claims, err = svcCtx.JwtManager.Valid(r.Context(), newToken)
if err != nil {
http.Error(w, "Token refresh failed", http.StatusUnauthorized)
return
}
}
// 将声明附加到上下文
newCtx := context.WithValue(r.Context(), "claims", claims)
next.ServeHTTP(w, r.WithContext(newCtx))
})
}
}
```
## 7. 错误处理最佳实践
```go
package logic
import (
"errors"
"log"
"yourmodule/app/users/rpc/internal/utils"
)
// HandleJwtError 处理 JWT 相关错误
func HandleJwtError(err error) error {
if errors.Is(err, utils.ErrTokenExpired) {
log.Println("Token has expired, user needs to refresh")
return errors.New("token expired - use refresh endpoint")
}
if errors.Is(err, utils.ErrTokenInvalid) {
log.Println("Token is invalid or malformed")
return errors.New("invalid token")
}
if errors.Is(err, utils.ErrTokenNotFound) {
log.Println("Token not found in Redis (revoked or expired)")
return errors.New("token revoked or expired")
}
return err
}
```
## 8. 测试 JWT 集成
### 单元测试示例
```go
package interceptor
import (
"context"
"testing"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
)
func TestJwtUnaryInterceptor_ValidToken(t *testing.T) {
// 1. 创建有效的令牌
token, err := svcCtx.JwtManager.New(context.Background(), "user123", "user@example.com", "John")
if err != nil {
t.Fatalf("Failed to create token: %v", err)
}
// 2. 创建包含令牌的上下文
md := metadata.Pairs("authorization", token)
ctx := metadata.NewIncomingContext(context.Background(), md)
// 3. 调用拦截器
_, err = JwtUnaryInterceptor(svcCtx)(ctx, nil, nil, func(ctx context.Context, req interface{}) (interface{}, error) {
return "success", nil
})
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
}
func TestJwtUnaryInterceptor_ExpiredToken(t *testing.T) {
// 1. 创建过期的令牌或使用无效令牌
token := "invalid.token.here"
// 2. 创建包含令牌的上下文
md := metadata.Pairs("authorization", token)
ctx := metadata.NewIncomingContext(context.Background(), md)
// 3. 调用拦截器
_, err := JwtUnaryInterceptor(svcCtx)(ctx, nil, nil, func(ctx context.Context, req interface{}) (interface{}, error) {
return "success", nil
})
// 4. 验证错误
st, ok := status.FromError(err)
if !ok || st.Code() != codes.Unauthenticated {
t.Errorf("Expected Unauthenticated error, got: %v", err)
}
}
```
## 9. 生产部署清单
在将 JWT 集成部署到生产环境前:
- [ ] 所有令牌端点都进行了压力测试
- [ ] 令牌刷新逻辑已验证
- [ ] 错误处理覆盖了所有 JWT 失败情况
- [ ] 审计日志记录了所有认证尝试
- [ ] 密钥轮换计划已确定
- [ ] 监控和告警已配置
- [ ] 灾难恢复流程已文档化
- [ ] 所有依赖于 JWT 的服务都已更新
## 相关文件
- [app/users/rpc/internal/utils/jwt.go](../../../app/users/rpc/internal/utils/jwt.go) - JWT Manager 实现
- [app/users/rpc/internal/config/config.go](../../../app/users/rpc/internal/config/config.go) - JWT 配置
- [app/users/rpc/internal/svc/serviceContext.go](../../../app/users/rpc/internal/svc/serviceContext.go) - 依赖注入
- [deploy/k8s/secrets/jwt-secret.yaml](./jwt-secret.yaml) - Secret 和 RBAC
- [deploy/k8s/secrets/DEPLOYMENT.md](./DEPLOYMENT.md) - 部署指南
+14 -4
View File
@@ -7,9 +7,19 @@ Prometheus:
Port: 4001
Path: /metrics
# ===== PROC CONFIG =====
#UsercenterRpcConf:
# Target: k8s://juwan/user-rpc-svc:8080
#UserVerificationRpc:
# Target: k8s://juwan/user_verifications-svc:8080
SnowflakeRpcConf:
Target: k8s://juwan/snowflake-svc:8080
# ===== DEV CONFIG ====
UserVerificationRpc:
Target: k8s://juwan/user_verifications-svc:8080
Endpoints:
- user-verifications-rpc:8080
UsercenterRpcConf:
Endpoints:
- user-rpc:8080
Log:
Level: debug
+14 -17
View File
@@ -146,23 +146,20 @@ func RegisterHandlers(server *rest.Server, serverCtx *svc.ServiceContext) {
)
server.AddRoutes(
rest.WithMiddlewares(
[]rest.Middleware{serverCtx.Logger},
[]rest.Route{
{
// 提交或修改角色认证申请 (支持幂等更新)
Method: http.MethodPost,
Path: "/me/verification",
Handler: verification_user.ApplyVerificationHandler(serverCtx),
},
{
// 获取我的所有认证状态
Method: http.MethodGet,
Path: "/me/verification",
Handler: verification_user.GetMyVerificationsHandler(serverCtx),
},
}...,
),
[]rest.Route{
{
// 提交或修改角色认证申请 (支持幂等更新)
Method: http.MethodPost,
Path: "/me/verification",
Handler: verification_user.ApplyVerificationHandler(serverCtx),
},
{
// 获取我的所有认证状态
Method: http.MethodGet,
Path: "/me/verification",
Handler: verification_user.GetMyVerificationsHandler(serverCtx),
},
},
rest.WithPrefix("/api/v1/users"),
)
}
@@ -6,6 +6,7 @@ package auth
import (
"context"
"errors"
"fmt"
"juwan-backend/app/users/rpc/pb"
"juwan-backend/app/users/rpc/usercenter"
"juwan-backend/common/utils/contextj"
@@ -57,7 +58,8 @@ func (l *RegisterLogic) Register(req *types.RegisterReq) (resp *types.RegisterRe
return nil, errors.New("hash password failed")
}
requestId, err := contextj.RequestIdFrom(l.ctx)
requestId, err := contextj.RIdFrom(l.ctx)
logx.Infof("requestId: %s", requestId)
if err != nil {
logx.Errorf("contextj.RequestIdFrom failed: %v", err)
return nil, errors.New("contextj.RequestIdFrom failed")
@@ -73,7 +75,7 @@ func (l *RegisterLogic) Register(req *types.RegisterReq) (resp *types.RegisterRe
})
if err != nil {
logx.Error("failed to register user: ", err)
return nil, errors.New("failed to register user")
return nil, errors.New(fmt.Sprintf("failed to register user: %v", err.Error()))
}
// 返回响应
@@ -5,6 +5,9 @@ package user
import (
"context"
"errors"
"juwan-backend/app/users/rpc/usercenter"
"juwan-backend/common/utils/contextj"
"juwan-backend/app/users/api/internal/svc"
"juwan-backend/app/users/api/internal/types"
@@ -29,6 +32,19 @@ func NewFollowUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Follow
func (l *FollowUserLogic) FollowUser(req *types.FollowUserReq) (resp *types.EmptyResp, err error) {
// todo: add your logic here and delete this line
userId, err := contextj.UserIDFrom(l.ctx)
if err != nil {
return nil, errors.New("unauthorized")
}
return
_, err = l.svcCtx.UserRpc.AddUserFollows(l.ctx, &usercenter.AddUserFollowsReq{
FollowerId: userId,
FolloweeId: req.Id,
CreatedAt: 0,
})
if err != nil {
logx.Errorf("add user follow err: %v", err)
return nil, errors.New("failed to follow user")
}
return &types.EmptyResp{}, nil
}
+25 -10
View File
@@ -6,15 +6,15 @@ package user
import (
"context"
"errors"
"juwan-backend/app/users/api/internal/svc"
"juwan-backend/app/users/api/internal/types"
"juwan-backend/app/users/rpc/usercenter"
"juwan-backend/common/converter"
"juwan-backend/common/utils/contextj"
"time"
"juwan-backend/app/users/api/internal/svc"
"juwan-backend/app/users/api/internal/types"
"github.com/jinzhu/copier"
"github.com/zeromicro/go-zero/core/logx"
"k8s.io/apimachinery/pkg/util/json"
)
type GetMeLogic struct {
@@ -35,19 +35,34 @@ func NewGetMeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMeLogic
func (l *GetMeLogic) GetMe() (resp *types.User, err error) {
userId, err := contextj.UserIDFrom(l.ctx)
if err != nil {
return nil, errors.New("illegal id")
logx.Errorf("get user id from context: %v", err)
return nil, errors.New("illegal user")
}
user, err := l.svcCtx.UserRpc.GetUsersById(l.ctx, &usercenter.GetUsersByIdReq{
Id: userId,
})
if err != nil {
return nil, errors.New("get user by id error")
logx.Errorf("GetMeLogic.GetUsersById err: %v", err)
return nil, errors.New("get user failed")
}
err = converter.StructToStruct(user, &resp)
createAt := time.Unix(user.Users.CreatedAt, 0)
resp.CreatedAt = createAt.Format(time.DateTime)
logx.Debugf("get user resp: %+v", user)
resp = &types.User{}
err = copier.Copy(&resp, user.Users)
if err != nil {
return nil, errors.New("to struct error")
logx.Errorf("copier.Copy err: %v", err)
return nil, errors.New("copy user failed")
}
var verificationStatus map[string]string
err = json.Unmarshal([]byte(user.Users.VerificationStatus), &verificationStatus)
if err != nil {
logx.Errorf("json.Unmarshal err: %v", err)
}
resp.VerifiedRoles = user.Users.VerifiedRoles
resp.VerificationStatus = verificationStatus
resp.CreatedAt = time.Unix(user.Users.CreatedAt, 0).Format(time.DateTime)
return
}
@@ -32,7 +32,6 @@ func NewSwitchRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Switch
}
func (l *SwitchRoleLogic) SwitchRole(req *types.SwitchRoleReq) (resp *types.EmptyResp, err error) {
// todo: add your logic here and delete this line
id, err := contextj.UserIDFrom(l.ctx)
if err != nil {
logx.Errorf("get user id from context: %v", err)
@@ -5,6 +5,9 @@ package user
import (
"context"
"errors"
"juwan-backend/app/users/rpc/usercenter"
"juwan-backend/common/utils/contextj"
"juwan-backend/app/users/api/internal/svc"
"juwan-backend/app/users/api/internal/types"
@@ -29,6 +32,18 @@ func NewUnfollowUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Unfo
func (l *UnfollowUserLogic) UnfollowUser(req *types.UnfollowUserReq) (resp *types.EmptyResp, err error) {
// todo: add your logic here and delete this line
userId, err := contextj.UserIDFrom(l.ctx)
if err != nil {
return nil, errors.New("unauthorized")
}
return
_, err = l.svcCtx.UserRpc.DelUserFollows(l.ctx, &usercenter.DelUserFollowsReq{
Id: req.Id,
UserId: userId,
})
if err != nil {
logx.Errorf("del user follow err: %v", err)
return nil, errors.New("unfollow user failed")
}
return &types.EmptyResp{}, nil
}
@@ -29,6 +29,5 @@ func NewUpdateNotificationSettingsLogic(ctx context.Context, svcCtx *svc.Service
func (l *UpdateNotificationSettingsLogic) UpdateNotificationSettings(req *types.UpdateNotifySettingsReq) (resp *types.EmptyResp, err error) {
// todo: add your logic here and delete this line
return
}
@@ -33,7 +33,6 @@ func NewRejectVerificationLogic(ctx context.Context, svcCtx *svc.ServiceContext)
var REJECTED = "rejected"
func (l *RejectVerificationLogic) RejectVerification(req *types.RejectVerificationReq) (resp *types.VerificationEmptyResp, err error) {
// todo: add your logic here and delete this line
adminId, err := contextj.AdminIdFrom(l.ctx)
if err != nil {
return nil, err
@@ -36,13 +36,6 @@ func (l *ApplyVerificationLogic) ApplyVerification(req *types.ApplyVerificationR
logx.Errorf("get user id from context: %v", err)
return nil, contextj.ERRILLEGALUSER
}
verifications, err := l.svcCtx.UserVerificationsRpc.SearchUserVerifications(l.ctx, &pb.SearchUserVerificationsReq{
UserId: userId,
})
if err != nil {
logx.Errorf("search user verifications: %v", err)
return nil, errors.New("search user verifications failed")
}
materials, err := json.Marshal(req.Materials)
if err != nil {
@@ -50,18 +43,14 @@ func (l *ApplyVerificationLogic) ApplyVerification(req *types.ApplyVerificationR
return nil, err
}
if verifications == nil || len(verifications.UserVerifications) == 0 {
// 如果没有则增加
_, err = l.svcCtx.UserVerificationsRpc.AddUserVerifications(l.ctx, &pb.AddUserVerificationsReq{
Role: req.Role,
Materials: string(materials),
})
if err != nil {
logx.Errorf("add user verifications: %v", err)
return nil, errors.New("add user verifications failed")
}
} else {
_, err = l.svcCtx.UserVerificationsRpc.AddOrUpdateUserVerifications(l.ctx, &pb.AddOrUpdateUserVerificationsReq{
UserId: userId,
Role: req.Role,
Material: string(materials),
})
if err != nil {
logx.Errorf("call AddOrUpdateUserVerifications: %v", err)
return nil, errors.New("apply verification failed: " + err.Error())
}
return &types.VerificationEmptyResp{}, nil
@@ -32,23 +32,21 @@ func NewGetMyVerificationsLogic(ctx context.Context, svcCtx *svc.ServiceContext)
}
func (l *GetMyVerificationsLogic) GetMyVerifications() (resp *types.GetMyVerificationsResp, err error) {
// todo: add your logic here and delete this line
userId, err := contextj.UserIDFrom(l.ctx)
if err != nil {
logx.Errorf("get user id from context: %v", err)
return nil, contextj.ERRILLEGALUSER
}
verifications, err := l.svcCtx.UserVerificationsRpc.SearchUserVerifications(l.ctx, &pb.SearchUserVerificationsReq{
verifications, err := l.svcCtx.UserVerificationsRpc.ListUserVerificationsByUserId(l.ctx, &pb.ListUserVerificationsByUserIdReq{
UserId: userId,
Page: 1,
Limit: 100, // assuming a user won't have more than 100 verification records, adjust as needed
})
if err != nil {
return nil, err
}
var searchResults []types.VerificationItem
for _, v := range verifications.UserVerifications {
temp := types.VerificationItem{}
err = copier.Copy(&temp, v)
+9 -2
View File
@@ -4,8 +4,8 @@
package types
type ApplyVerificationReq struct {
Role string `json:"role"` // 申请什么角色
Materials map[string]string `json:"materials"` // 证明材料键值对 {"idCardFront": "http...", "license": "http..."}
Role string `json:"role"` // 申请什么角色
Materials MaterialJson `json:"materials"` // 证明材料键值对 {"idCardFront": "http...", "license": "http..."}
}
type EmptyResp struct {
@@ -56,6 +56,13 @@ type LoginResp struct {
type LogoutReq struct {
}
type MaterialJson struct {
IdCardFront string `json:"idCardFront"` // 身份证正面照片URL
IdCardBack string `json:"idCardBack"` // 身份证反面照片URL
GameScreenshots []string `json:"gameScreenshots"` // 游戏截图URL列表
VoiceDemo string `json:"voiceDemo"` // 语音认证示例URL
}
type RegisterReq struct {
Phone string `json:"phone,omitempty,optional"`
Email string `json:"email,omitempty,"`
+3
View File
@@ -6,6 +6,7 @@ package main
import (
"flag"
"fmt"
"juwan-backend/common/middlewares"
"juwan-backend/app/users/api/internal/config"
"juwan-backend/app/users/api/internal/handler"
@@ -24,6 +25,8 @@ func main() {
conf.MustLoad(*configFile, &c)
server := rest.MustNewServer(c.RestConf)
server.Use(middlewares.NewHeaderExtractorMiddleware().Handle)
server.Use(middlewares.NewRequestMiddleware().Handle)
defer server.Stop()
ctx := svc.NewServiceContext(c)
+32 -13
View File
@@ -1,5 +1,5 @@
Name: pb.rpc
ListenOn: 0.0.0.0:9001
ListenOn: 0.0.0.0:8080
Prometheus:
Host: 0.0.0.0
@@ -8,26 +8,45 @@ Prometheus:
DataSource: "${DB_URI}?sslmode=disable"
# ===== PROC CONFIG =====
#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"
# ===== DEV CONFIG =====
SnowflakeRpcConf:
Target: k8s://juwan/snowflake-svc:8080
Endpoints:
- snowflake: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"
Master: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@postgres:${DB_PORT}/${DB_NAME}?sslmode=disable"
Slave: "postgresql://${PD_USERNAME}:${DB_PASSWORD}@postgres:${DB_PORT}/${DB_NAME}?sslmode=disable"
CacheConf:
- Host: "${REDIS_M_HOST}"
- Host: "${REDIS_HOST}:${REDIS_PORT}"
Type: node
Pass: "${REDIS_PASSWORD}"
User: "default"
- Host: "${REDIS_S_HOST}"
Type: node
Pass: "${REDIS_PASSWORD}"
User: "default"
Jwt:
SecretKey: "${JWT_SECRET_KEY}"
SecretKey: "MGUyMWE3ZDhjMTQ5ZDg1MWViOWU0MGM3OTE2NWVkYTBlOTE5ZWRkZDU1YjYzOGJjOWRiNzM0NTc4NDIyMjlkZQ"
Issuer: "juwan-user-rpc"
Log:
Level: info
Level: debug
@@ -0,0 +1,46 @@
package logic
import (
"context"
"errors"
"juwan-backend/app/snowflake/rpc/snowflake"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type AddUserFollowsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewAddUserFollowsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddUserFollowsLogic {
return &AddUserFollowsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// -----------------------userFollows-----------------------
func (l *AddUserFollowsLogic) AddUserFollows(in *pb.AddUserFollowsReq) (*pb.AddUserFollowsResp, error) {
idResp, err := l.svcCtx.Snowflake.NextId(l.ctx, &snowflake.NextIdReq{})
if err != nil {
logx.WithContext(l.ctx).Errorf("AddUserFollows error: %s", err.Error())
return nil, err
}
_, err = l.svcCtx.UsersModelRW.UserFollows.Create().
SetFollowerID(in.FollowerId).
SetFolloweeID(in.FolloweeId).
SetID(idResp.Id).
Save(l.ctx)
if err != nil {
logx.WithContext(l.ctx).Errorf("AddUserFollows error: %s", err.Error())
return nil, errors.New("failed to add user follow relationship")
}
return &pb.AddUserFollowsResp{}, nil
}
@@ -0,0 +1,31 @@
package logic
import (
"context"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type AddUserPreferencesLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewAddUserPreferencesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AddUserPreferencesLogic {
return &AddUserPreferencesLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// -----------------------userPreferences-----------------------
func (l *AddUserPreferencesLogic) AddUserPreferences(in *pb.AddUserPreferencesReq) (*pb.AddUserPreferencesResp, error) {
// todo: add your logic here and delete this line
return &pb.AddUserPreferencesResp{}, nil
}
@@ -0,0 +1,39 @@
package logic
import (
"context"
"errors"
"juwan-backend/app/users/rpc/internal/models/userfollows"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type DelUserFollowsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewDelUserFollowsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelUserFollowsLogic {
return &DelUserFollowsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *DelUserFollowsLogic) DelUserFollows(in *pb.DelUserFollowsReq) (*pb.DelUserFollowsResp, error) {
_, err := l.svcCtx.UsersModelRW.UserFollows.Delete().Where(
userfollows.IDEQ(in.Id),
userfollows.FollowerIDEQ(in.UserId),
).Exec(l.ctx)
if err != nil {
logx.WithContext(l.ctx).Errorf("Failed to delete user follow: %s", err.Error())
return nil, errors.New("failed to unfollow")
}
return &pb.DelUserFollowsResp{}, nil
}
@@ -0,0 +1,30 @@
package logic
import (
"context"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type DelUserPreferencesLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewDelUserPreferencesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DelUserPreferencesLogic {
return &DelUserPreferencesLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *DelUserPreferencesLogic) DelUserPreferences(in *pb.DelUserPreferencesReq) (*pb.DelUserPreferencesResp, error) {
// todo: add your logic here and delete this line
return &pb.DelUserPreferencesResp{}, nil
}
@@ -29,7 +29,7 @@ func (l *GetUserByUsernameLogic) GetUserByUsername(in *pb.GetUserByUsernameReq)
pbUsers := &pb.Users{}
//user, err := l.svcCtx.UsersModelRO.FindOneByUsername(l.ctx, in.Username)
user, err := l.svcCtx.UsersModelRO.Query().Where(users.UsernameEQ(in.Username)).First(l.ctx)
user, err := l.svcCtx.UsersModelRO.Users.Query().Where(users.UsernameEQ(in.Username)).First(l.ctx)
if err == nil || user != nil {
return &pb.GetUserByUsernameResp{
Users: pbUsers,
@@ -0,0 +1,30 @@
package logic
import (
"context"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type GetUserFollowsByIdLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewGetUserFollowsByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserFollowsByIdLogic {
return &GetUserFollowsByIdLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *GetUserFollowsByIdLogic) GetUserFollowsById(in *pb.GetUserFollowsByIdReq) (*pb.GetUserFollowsByIdResp, error) {
// todo: add your logic here and delete this line
return &pb.GetUserFollowsByIdResp{}, nil
}
@@ -0,0 +1,30 @@
package logic
import (
"context"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type GetUserPreferencesByIdLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewGetUserPreferencesByIdLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserPreferencesByIdLogic {
return &GetUserPreferencesByIdLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *GetUserPreferencesByIdLogic) GetUserPreferencesById(in *pb.GetUserPreferencesByIdReq) (*pb.GetUserPreferencesByIdResp, error) {
// todo: add your logic here and delete this line
return &pb.GetUserPreferencesByIdResp{}, nil
}
@@ -2,11 +2,12 @@ package logic
import (
"context"
"encoding/json"
"errors"
"juwan-backend/app/users/rpc/internal/models/users"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
"juwan-backend/common/converter"
"github.com/zeromicro/go-zero/core/logx"
)
@@ -28,15 +29,37 @@ 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.Query().Where(users.IDEQ(in.Id)).All(l.ctx)
if err != nil {
return nil, err
}
pbUser := &pb.Users{}
err = converter.StructToStruct(&user, &pbUser)
user, err := l.svcCtx.UsersModelRO.Users.Query().Where(users.IDEQ(in.Id)).First(l.ctx)
if err != nil {
return nil, err
}
verificationStatus, err := json.Marshal(user.VerificationStatus)
if err != nil {
logx.Errorf("json marshal verification status failed: %v", err)
return nil, errors.New("marshal verification status failed")
}
logx.Debugf("Users data: %+v", user)
logx.Debugf("verified_role: %+v", user.VerifiedRoles)
pbUser := &pb.Users{
Id: user.ID,
Username: user.Username,
PasswordHash: "",
Phone: "",
Email: "",
Nickname: user.Nickname,
Avatar: user.Avatar,
Bio: user.Bio,
CurrentRole: user.CurrentRole,
VerifiedRoles: user.VerifiedRoles.Elements,
VerificationStatus: string(verificationStatus),
IsAdmin: user.IsAdmin,
CreatedAt: user.CreatedAt.Unix(),
UpdatedAt: user.UpdatedAt.Unix(),
DeletedAt: user.DeletedAt.Unix(),
}
logx.Debugf("pb users data: %+v", pbUser)
return &pb.GetUsersByIdResp{Users: pbUser}, nil
}
+5 -3
View File
@@ -29,11 +29,13 @@ 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.Query().Where(users.NicknameEQ(in.Username)).First(l.ctx)
user, err := l.svcCtx.UsersModelRO.Users.Query().
Where(users.UsernameEQ(in.Username)).
Select(users.FieldID, users.FieldUsername, users.FieldPasswordHash, users.FieldEmail).
First(l.ctx)
if err != nil {
logx.WithContext(l.ctx).Errorf("LoginLogic.Login error:%v", err)
return nil, err
return nil, errors.New("user not found")
}
logx.Infof("user:%v", user)
if !pwdUtils.VerifyPassword(user.PasswordHash, in.Passwd) {
@@ -49,6 +49,7 @@ func (l *RegisterLogic) Register(in *pb.RegisterReq) (*pb.RegisterResp, error) {
}
redisKey := fmt.Sprintf(redisx.VCODE_KEY_PREFIX, in.RequestId, redisx.SCENE_REG, in.Email)
logx.Infof("redisKey: %s", redisKey)
vcode, err := l.svcCtx.RedisCluster.Get(l.ctx, redisKey).Result()
logx.Infof("vcode:%s, err:%v", vcode, err)
if err != nil {
@@ -66,12 +67,15 @@ func (l *RegisterLogic) Register(in *pb.RegisterReq) (*pb.RegisterResp, error) {
return nil, errors.New("generate user ID failed")
}
_, err = l.svcCtx.UsersModelRW.Create().
_, err = l.svcCtx.UsersModelRW.Users.Create().
SetID(resp.Id).
SetUsername(in.Username).
SetPasswordHash(in.Passwd).
SetPhone(in.Phone).
SetEmail(in.Email).
SetBio(in.Email).
SetAvatar("").
SetCurrentRole("consumer").
SetNickname(mustNewRandomNickname()).
Save(l.ctx)
if err != nil {
@@ -38,7 +38,7 @@ func (l *ResetPasswordLogic) ResetPassword(in *pb.ResetPasswordReq) (*pb.ResetPa
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)).
err = l.svcCtx.UsersModelRW.Users.Update().Where(users.EmailEQ(in.Email)).
SetPasswordHash(in.NewPassword).
Exec(l.ctx)
if err != nil {
@@ -0,0 +1,30 @@
package logic
import (
"context"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type SearchUserFollowsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewSearchUserFollowsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchUserFollowsLogic {
return &SearchUserFollowsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *SearchUserFollowsLogic) SearchUserFollows(in *pb.SearchUserFollowsReq) (*pb.SearchUserFollowsResp, error) {
// todo: add your logic here and delete this line
return &pb.SearchUserFollowsResp{}, nil
}
@@ -0,0 +1,30 @@
package logic
import (
"context"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type SearchUserPreferencesLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewSearchUserPreferencesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SearchUserPreferencesLogic {
return &SearchUserPreferencesLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *SearchUserPreferencesLogic) SearchUserPreferences(in *pb.SearchUserPreferencesReq) (*pb.SearchUserPreferencesResp, error) {
// todo: add your logic here and delete this line
return &pb.SearchUserPreferencesResp{}, nil
}
@@ -38,7 +38,7 @@ func (l *SearchUsersLogic) SearchUsers(in *pb.SearchUsersReq) (out *pb.SearchUse
logx.Errorf("Limit exceeds max limit: %d", in.Limit)
return nil, errors.New("limit exceeds max limit")
}
user, err := l.svcCtx.UsersModelRO.Query().
user, err := l.svcCtx.UsersModelRO.Users.Query().
Where(users.Or(
users.UsernameContainsFold(*in.Username),
users.NicknameContainsFold(*in.Username),
@@ -80,7 +80,8 @@ func ConvertEntUserToProto(entUser *models.Users) *pb.Users {
}
out.VerificationStatus = string(verificationStatus)
out.VerifiedRoles = entUser.VerifiedRoles
//out.VerifiedRoles = entUser.VerifiedRoles
out.VerifiedRoles = entUser.VerifiedRoles.Elements
out.PasswordHash = "" // 手动清空敏感字段
return out
@@ -0,0 +1,64 @@
package logic
import (
"context"
"errors"
"slices"
"juwan-backend/app/users/rpc/internal/models/users"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type SwitchRoleLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewSwitchRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SwitchRoleLogic {
return &SwitchRoleLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
var userRoles = []string{"consumer", "owner", "player", "admin"}
func (l *SwitchRoleLogic) SwitchRole(in *pb.SwitchRoleReq) (*pb.SwitchRoleResp, error) {
user, err := l.svcCtx.UsersModelRO.Users.Query().
Select(users.FieldVerifiedRoles).
Where(users.IDEQ(in.UserId)).
First(l.ctx)
if err != nil {
logx.Errorf("find user error by switch role, err: %v", err.Error())
return &pb.SwitchRoleResp{
Success: false,
}, errors.New("failed to find user")
}
if !slices.Contains(userRoles, in.NewRole) {
logx.Infof("user role not found by userId: %v", in.UserId)
return nil, errors.New("user role not found by userId")
}
if !slices.Contains(user.VerifiedRoles.Elements, in.NewRole) {
logx.Infof("user verified role not exists, user: %v", in.UserId)
return nil, errors.New("no permission to operate")
}
user, err = l.svcCtx.UsersModelRW.Users.UpdateOneID(in.UserId).
SetCurrentRole(in.NewRole).
Save(l.ctx)
if err != nil {
logx.Errorf("failed to update user role, userId: %v, err: %v", in.UserId, err.Error())
return nil, errors.New("failed to update user")
}
return &pb.SwitchRoleResp{
Success: true,
}, nil
}
@@ -0,0 +1,30 @@
package logic
import (
"context"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type UpdateUserFollowsLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewUpdateUserFollowsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUserFollowsLogic {
return &UpdateUserFollowsLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *UpdateUserFollowsLogic) UpdateUserFollows(in *pb.UpdateUserFollowsReq) (*pb.UpdateUserFollowsResp, error) {
// todo: add your logic here and delete this line
return &pb.UpdateUserFollowsResp{}, nil
}
@@ -0,0 +1,30 @@
package logic
import (
"context"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
"github.com/zeromicro/go-zero/core/logx"
)
type UpdateUserPreferencesLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewUpdateUserPreferencesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateUserPreferencesLogic {
return &UpdateUserPreferencesLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *UpdateUserPreferencesLogic) UpdateUserPreferences(in *pb.UpdateUserPreferencesReq) (*pb.UpdateUserPreferencesResp, error) {
// todo: add your logic here and delete this line
return &pb.UpdateUserPreferencesResp{}, nil
}
@@ -4,6 +4,7 @@ import (
"context"
"juwan-backend/app/users/rpc/internal/svc"
"juwan-backend/app/users/rpc/pb"
"juwan-backend/pkg/types"
"github.com/zeromicro/go-zero/core/logx"
)
@@ -23,14 +24,20 @@ func NewUpdateUsersLogic(ctx context.Context, svcCtx *svc.ServiceContext) *Updat
}
func (l *UpdateUsersLogic) UpdateUsers(in *pb.UpdateUsersReq) (*pb.UpdateUsersResp, error) {
updater := l.svcCtx.UsersModelRW.UpdateOneID(in.Id).
updater := l.svcCtx.UsersModelRW.Users.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)
var verifiedRoles types.TextArray
err := verifiedRoles.Scan(in.VerifiedRoles)
if err != nil {
logx.Errorf("failed to scan verified roles: %v", err)
return nil, err
}
updater.SetVerifiedRoles(verifiedRoles)
}
err := updater.Exec(l.ctx)
if err != nil {
@@ -2,6 +2,8 @@ package logic
import (
"context"
"encoding/json"
"errors"
"juwan-backend/app/users/rpc/internal/models/users"
"juwan-backend/app/users/rpc/internal/svc"
@@ -33,15 +35,24 @@ func (l *ValidateTokenLogic) ValidateToken(in *pb.ValidateTokenReq) (*pb.Validat
return nil, err
}
//users, err := l.svcCtx.UsersModelRO.FindOne(l.ctx, in.UserId)
user, err := l.svcCtx.UsersModelRO.Query().Where(users.IDEQ(in.UserId)).First(l.ctx)
user, err := l.svcCtx.UsersModelRO.Users.Query().
Where(users.IDEQ(in.UserId)).
Select(users.FieldCurrentRole).
First(l.ctx)
if err != nil {
return nil, err
}
userJson, err := json.Marshal(user.CurrentRole)
if err != nil {
logx.Errorf("json marshal err: %v", err)
return nil, errors.New("internal error")
}
return &pb.ValidateTokenResp{
Valid: true,
Message: "OK",
UserId: in.UserId,
RoleType: user.CurrentRole,
RoleType: string(userJson),
}, nil
}
+295 -9
View File
@@ -11,6 +11,8 @@ import (
"juwan-backend/app/users/rpc/internal/models/migrate"
"juwan-backend/app/users/rpc/internal/models/userfollows"
"juwan-backend/app/users/rpc/internal/models/userpreferences"
"juwan-backend/app/users/rpc/internal/models/users"
"entgo.io/ent"
@@ -23,6 +25,10 @@ type Client struct {
config
// Schema is the client for creating, migrating and dropping schema.
Schema *migrate.Schema
// UserFollows is the client for interacting with the UserFollows builders.
UserFollows *UserFollowsClient
// UserPreferences is the client for interacting with the UserPreferences builders.
UserPreferences *UserPreferencesClient
// Users is the client for interacting with the Users builders.
Users *UsersClient
}
@@ -36,6 +42,8 @@ func NewClient(opts ...Option) *Client {
func (c *Client) init() {
c.Schema = migrate.NewSchema(c.driver)
c.UserFollows = NewUserFollowsClient(c.config)
c.UserPreferences = NewUserPreferencesClient(c.config)
c.Users = NewUsersClient(c.config)
}
@@ -127,9 +135,11 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
cfg := c.config
cfg.driver = tx
return &Tx{
ctx: ctx,
config: cfg,
Users: NewUsersClient(cfg),
ctx: ctx,
config: cfg,
UserFollows: NewUserFollowsClient(cfg),
UserPreferences: NewUserPreferencesClient(cfg),
Users: NewUsersClient(cfg),
}, nil
}
@@ -147,16 +157,18 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
cfg := c.config
cfg.driver = &txDriver{tx: tx, drv: c.driver}
return &Tx{
ctx: ctx,
config: cfg,
Users: NewUsersClient(cfg),
ctx: ctx,
config: cfg,
UserFollows: NewUserFollowsClient(cfg),
UserPreferences: NewUserPreferencesClient(cfg),
Users: NewUsersClient(cfg),
}, nil
}
// Debug returns a new debug-client. It's used to get verbose logging on specific operations.
//
// client.Debug().
// Users.
// UserFollows.
// Query().
// Count(ctx)
func (c *Client) Debug() *Client {
@@ -178,18 +190,26 @@ func (c *Client) Close() error {
// 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.UserFollows.Use(hooks...)
c.UserPreferences.Use(hooks...)
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.UserFollows.Intercept(interceptors...)
c.UserPreferences.Intercept(interceptors...)
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 *UserFollowsMutation:
return c.UserFollows.mutate(ctx, m)
case *UserPreferencesMutation:
return c.UserPreferences.mutate(ctx, m)
case *UsersMutation:
return c.Users.mutate(ctx, m)
default:
@@ -197,6 +217,272 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
}
}
// UserFollowsClient is a client for the UserFollows schema.
type UserFollowsClient struct {
config
}
// NewUserFollowsClient returns a client for the UserFollows from the given config.
func NewUserFollowsClient(c config) *UserFollowsClient {
return &UserFollowsClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `userfollows.Hooks(f(g(h())))`.
func (c *UserFollowsClient) Use(hooks ...Hook) {
c.hooks.UserFollows = append(c.hooks.UserFollows, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `userfollows.Intercept(f(g(h())))`.
func (c *UserFollowsClient) Intercept(interceptors ...Interceptor) {
c.inters.UserFollows = append(c.inters.UserFollows, interceptors...)
}
// Create returns a builder for creating a UserFollows entity.
func (c *UserFollowsClient) Create() *UserFollowsCreate {
mutation := newUserFollowsMutation(c.config, OpCreate)
return &UserFollowsCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of UserFollows entities.
func (c *UserFollowsClient) CreateBulk(builders ...*UserFollowsCreate) *UserFollowsCreateBulk {
return &UserFollowsCreateBulk{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 *UserFollowsClient) MapCreateBulk(slice any, setFunc func(*UserFollowsCreate, int)) *UserFollowsCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &UserFollowsCreateBulk{err: fmt.Errorf("calling to UserFollowsClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*UserFollowsCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &UserFollowsCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for UserFollows.
func (c *UserFollowsClient) Update() *UserFollowsUpdate {
mutation := newUserFollowsMutation(c.config, OpUpdate)
return &UserFollowsUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *UserFollowsClient) UpdateOne(_m *UserFollows) *UserFollowsUpdateOne {
mutation := newUserFollowsMutation(c.config, OpUpdateOne, withUserFollows(_m))
return &UserFollowsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *UserFollowsClient) UpdateOneID(id int64) *UserFollowsUpdateOne {
mutation := newUserFollowsMutation(c.config, OpUpdateOne, withUserFollowsID(id))
return &UserFollowsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for UserFollows.
func (c *UserFollowsClient) Delete() *UserFollowsDelete {
mutation := newUserFollowsMutation(c.config, OpDelete)
return &UserFollowsDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *UserFollowsClient) DeleteOne(_m *UserFollows) *UserFollowsDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *UserFollowsClient) DeleteOneID(id int64) *UserFollowsDeleteOne {
builder := c.Delete().Where(userfollows.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &UserFollowsDeleteOne{builder}
}
// Query returns a query builder for UserFollows.
func (c *UserFollowsClient) Query() *UserFollowsQuery {
return &UserFollowsQuery{
config: c.config,
ctx: &QueryContext{Type: TypeUserFollows},
inters: c.Interceptors(),
}
}
// Get returns a UserFollows entity by its id.
func (c *UserFollowsClient) Get(ctx context.Context, id int64) (*UserFollows, error) {
return c.Query().Where(userfollows.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *UserFollowsClient) GetX(ctx context.Context, id int64) *UserFollows {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *UserFollowsClient) Hooks() []Hook {
return c.hooks.UserFollows
}
// Interceptors returns the client interceptors.
func (c *UserFollowsClient) Interceptors() []Interceptor {
return c.inters.UserFollows
}
func (c *UserFollowsClient) mutate(ctx context.Context, m *UserFollowsMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&UserFollowsCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&UserFollowsUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&UserFollowsUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&UserFollowsDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("models: unknown UserFollows mutation op: %q", m.Op())
}
}
// UserPreferencesClient is a client for the UserPreferences schema.
type UserPreferencesClient struct {
config
}
// NewUserPreferencesClient returns a client for the UserPreferences from the given config.
func NewUserPreferencesClient(c config) *UserPreferencesClient {
return &UserPreferencesClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `userpreferences.Hooks(f(g(h())))`.
func (c *UserPreferencesClient) Use(hooks ...Hook) {
c.hooks.UserPreferences = append(c.hooks.UserPreferences, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `userpreferences.Intercept(f(g(h())))`.
func (c *UserPreferencesClient) Intercept(interceptors ...Interceptor) {
c.inters.UserPreferences = append(c.inters.UserPreferences, interceptors...)
}
// Create returns a builder for creating a UserPreferences entity.
func (c *UserPreferencesClient) Create() *UserPreferencesCreate {
mutation := newUserPreferencesMutation(c.config, OpCreate)
return &UserPreferencesCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of UserPreferences entities.
func (c *UserPreferencesClient) CreateBulk(builders ...*UserPreferencesCreate) *UserPreferencesCreateBulk {
return &UserPreferencesCreateBulk{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 *UserPreferencesClient) MapCreateBulk(slice any, setFunc func(*UserPreferencesCreate, int)) *UserPreferencesCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &UserPreferencesCreateBulk{err: fmt.Errorf("calling to UserPreferencesClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*UserPreferencesCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &UserPreferencesCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for UserPreferences.
func (c *UserPreferencesClient) Update() *UserPreferencesUpdate {
mutation := newUserPreferencesMutation(c.config, OpUpdate)
return &UserPreferencesUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *UserPreferencesClient) UpdateOne(_m *UserPreferences) *UserPreferencesUpdateOne {
mutation := newUserPreferencesMutation(c.config, OpUpdateOne, withUserPreferences(_m))
return &UserPreferencesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *UserPreferencesClient) UpdateOneID(id int) *UserPreferencesUpdateOne {
mutation := newUserPreferencesMutation(c.config, OpUpdateOne, withUserPreferencesID(id))
return &UserPreferencesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for UserPreferences.
func (c *UserPreferencesClient) Delete() *UserPreferencesDelete {
mutation := newUserPreferencesMutation(c.config, OpDelete)
return &UserPreferencesDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *UserPreferencesClient) DeleteOne(_m *UserPreferences) *UserPreferencesDeleteOne {
return c.DeleteOneID(_m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *UserPreferencesClient) DeleteOneID(id int) *UserPreferencesDeleteOne {
builder := c.Delete().Where(userpreferences.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &UserPreferencesDeleteOne{builder}
}
// Query returns a query builder for UserPreferences.
func (c *UserPreferencesClient) Query() *UserPreferencesQuery {
return &UserPreferencesQuery{
config: c.config,
ctx: &QueryContext{Type: TypeUserPreferences},
inters: c.Interceptors(),
}
}
// Get returns a UserPreferences entity by its id.
func (c *UserPreferencesClient) Get(ctx context.Context, id int) (*UserPreferences, error) {
return c.Query().Where(userpreferences.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *UserPreferencesClient) GetX(ctx context.Context, id int) *UserPreferences {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *UserPreferencesClient) Hooks() []Hook {
return c.hooks.UserPreferences
}
// Interceptors returns the client interceptors.
func (c *UserPreferencesClient) Interceptors() []Interceptor {
return c.inters.UserPreferences
}
func (c *UserPreferencesClient) mutate(ctx context.Context, m *UserPreferencesMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&UserPreferencesCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&UserPreferencesUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&UserPreferencesUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&UserPreferencesDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("models: unknown UserPreferences mutation op: %q", m.Op())
}
}
// UsersClient is a client for the Users schema.
type UsersClient struct {
config
@@ -333,9 +619,9 @@ func (c *UsersClient) mutate(ctx context.Context, m *UsersMutation) (Value, erro
// hooks and interceptors per client, for fast access.
type (
hooks struct {
Users []ent.Hook
UserFollows, UserPreferences, Users []ent.Hook
}
inters struct {
Users []ent.Interceptor
UserFollows, UserPreferences, Users []ent.Interceptor
}
)
+5 -1
View File
@@ -6,6 +6,8 @@ import (
"context"
"errors"
"fmt"
"juwan-backend/app/users/rpc/internal/models/userfollows"
"juwan-backend/app/users/rpc/internal/models/userpreferences"
"juwan-backend/app/users/rpc/internal/models/users"
"reflect"
"sync"
@@ -73,7 +75,9 @@ var (
func checkColumn(t, c string) error {
initCheck.Do(func() {
columnCheck = sql.NewColumnCheck(map[string]func(string) bool{
users.Table: users.ValidColumn,
userfollows.Table: userfollows.ValidColumn,
userpreferences.Table: userpreferences.ValidColumn,
users.Table: users.ValidColumn,
})
})
return columnCheck(t, c)
@@ -8,6 +8,30 @@ import (
"juwan-backend/app/users/rpc/internal/models"
)
// The UserFollowsFunc type is an adapter to allow the use of ordinary
// function as UserFollows mutator.
type UserFollowsFunc func(context.Context, *models.UserFollowsMutation) (models.Value, error)
// Mutate calls f(ctx, m).
func (f UserFollowsFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) {
if mv, ok := m.(*models.UserFollowsMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *models.UserFollowsMutation", m)
}
// The UserPreferencesFunc type is an adapter to allow the use of ordinary
// function as UserPreferences mutator.
type UserPreferencesFunc func(context.Context, *models.UserPreferencesMutation) (models.Value, error)
// Mutate calls f(ctx, m).
func (f UserPreferencesFunc) Mutate(ctx context.Context, m models.Mutation) (models.Value, error) {
if mv, ok := m.(*models.UserPreferencesMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *models.UserPreferencesMutation", m)
}
// 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)
@@ -8,6 +8,36 @@ import (
)
var (
// UserFollowsColumns holds the columns for the "user_follows" table.
UserFollowsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt64, Increment: true},
{Name: "follower_id", Type: field.TypeInt64},
{Name: "followee_id", Type: field.TypeInt64},
{Name: "created_at", Type: field.TypeTime},
}
// UserFollowsTable holds the schema information for the "user_follows" table.
UserFollowsTable = &schema.Table{
Name: "user_follows",
Columns: UserFollowsColumns,
PrimaryKey: []*schema.Column{UserFollowsColumns[0]},
}
// UserPreferencesColumns holds the columns for the "user_preferences" table.
UserPreferencesColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "user_id", Type: field.TypeInt64},
{Name: "notification_order", Type: field.TypeBool, Default: true},
{Name: "notification_community", Type: field.TypeBool, Default: true},
{Name: "notification_system", Type: field.TypeBool, Default: true},
{Name: "theme", Type: field.TypeString, Default: "light"},
{Name: "language", Type: field.TypeString, Default: "zh-CN"},
{Name: "updated_at", Type: field.TypeTime},
}
// UserPreferencesTable holds the schema information for the "user_preferences" table.
UserPreferencesTable = &schema.Table{
Name: "user_preferences",
Columns: UserPreferencesColumns,
PrimaryKey: []*schema.Column{UserPreferencesColumns[0]},
}
// UsersColumns holds the columns for the "users" table.
UsersColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt64, Increment: true},
@@ -15,16 +45,16 @@ var (
{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: "nickname", Type: field.TypeString, Default: ""},
{Name: "avatar", Type: field.TypeString, Default: ""},
{Name: "bio", Type: field.TypeString, Default: ""},
{Name: "current_role", Type: field.TypeString, Default: "consumer"},
{Name: "verification_status", Type: field.TypeJSON, Nullable: true},
{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},
{Name: "deleted_at", Type: field.TypeTime, Nullable: true},
{Name: "verified_roles", Type: field.TypeOther, Nullable: true, SchemaType: map[string]string{"postgres": "text[]"}},
}
// UsersTable holds the schema information for the "users" table.
UsersTable = &schema.Table{
@@ -34,6 +64,8 @@ var (
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
UserFollowsTable,
UserPreferencesTable,
UsersTable,
}
)
File diff suppressed because it is too large Load Diff
@@ -6,5 +6,11 @@ import (
"entgo.io/ent/dialect/sql"
)
// UserFollows is the predicate function for userfollows builders.
type UserFollows func(*sql.Selector)
// UserPreferences is the predicate function for userpreferences builders.
type UserPreferences func(*sql.Selector)
// Users is the predicate function for users builders.
type Users func(*sql.Selector)
+48 -3
View File
@@ -4,6 +4,7 @@ package models
import (
"juwan-backend/app/users/rpc/internal/models/schema"
"juwan-backend/app/users/rpc/internal/models/userpreferences"
"juwan-backend/app/users/rpc/internal/models/users"
"time"
)
@@ -12,18 +13,62 @@ import (
// (default values, validators, hooks and policies) and stitches it
// to their package variables.
func init() {
userpreferencesFields := schema.UserPreferences{}.Fields()
_ = userpreferencesFields
// userpreferencesDescNotificationOrder is the schema descriptor for notification_order field.
userpreferencesDescNotificationOrder := userpreferencesFields[1].Descriptor()
// userpreferences.DefaultNotificationOrder holds the default value on creation for the notification_order field.
userpreferences.DefaultNotificationOrder = userpreferencesDescNotificationOrder.Default.(bool)
// userpreferencesDescNotificationCommunity is the schema descriptor for notification_community field.
userpreferencesDescNotificationCommunity := userpreferencesFields[2].Descriptor()
// userpreferences.DefaultNotificationCommunity holds the default value on creation for the notification_community field.
userpreferences.DefaultNotificationCommunity = userpreferencesDescNotificationCommunity.Default.(bool)
// userpreferencesDescNotificationSystem is the schema descriptor for notification_system field.
userpreferencesDescNotificationSystem := userpreferencesFields[3].Descriptor()
// userpreferences.DefaultNotificationSystem holds the default value on creation for the notification_system field.
userpreferences.DefaultNotificationSystem = userpreferencesDescNotificationSystem.Default.(bool)
// userpreferencesDescTheme is the schema descriptor for theme field.
userpreferencesDescTheme := userpreferencesFields[4].Descriptor()
// userpreferences.DefaultTheme holds the default value on creation for the theme field.
userpreferences.DefaultTheme = userpreferencesDescTheme.Default.(string)
// userpreferencesDescLanguage is the schema descriptor for language field.
userpreferencesDescLanguage := userpreferencesFields[5].Descriptor()
// userpreferences.DefaultLanguage holds the default value on creation for the language field.
userpreferences.DefaultLanguage = userpreferencesDescLanguage.Default.(string)
// userpreferencesDescUpdatedAt is the schema descriptor for updated_at field.
userpreferencesDescUpdatedAt := userpreferencesFields[6].Descriptor()
// userpreferences.DefaultUpdatedAt holds the default value on creation for the updated_at field.
userpreferences.DefaultUpdatedAt = userpreferencesDescUpdatedAt.Default.(func() time.Time)
usersFields := schema.Users{}.Fields()
_ = usersFields
// usersDescNickname is the schema descriptor for nickname field.
usersDescNickname := usersFields[5].Descriptor()
// users.DefaultNickname holds the default value on creation for the nickname field.
users.DefaultNickname = usersDescNickname.Default.(string)
// usersDescAvatar is the schema descriptor for avatar field.
usersDescAvatar := usersFields[6].Descriptor()
// users.DefaultAvatar holds the default value on creation for the avatar field.
users.DefaultAvatar = usersDescAvatar.Default.(string)
// usersDescBio is the schema descriptor for bio field.
usersDescBio := usersFields[7].Descriptor()
// users.DefaultBio holds the default value on creation for the bio field.
users.DefaultBio = usersDescBio.Default.(string)
// usersDescCurrentRole is the schema descriptor for current_role field.
usersDescCurrentRole := usersFields[8].Descriptor()
// users.DefaultCurrentRole holds the default value on creation for the current_role field.
users.DefaultCurrentRole = usersDescCurrentRole.Default.(string)
// users.CurrentRoleValidator is a validator for the "current_role" field. It is called by the builders before save.
users.CurrentRoleValidator = usersDescCurrentRole.Validators[0].(func(string) error)
// usersDescIsAdmin is the schema descriptor for is_admin field.
usersDescIsAdmin := usersFields[11].Descriptor()
usersDescIsAdmin := usersFields[10].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()
usersDescCreatedAt := usersFields[11].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()
usersDescUpdatedAt := usersFields[12].Descriptor()
// users.DefaultUpdatedAt holds the default value on creation for the updated_at field.
users.DefaultUpdatedAt = usersDescUpdatedAt.Default.(func() time.Time)
}
@@ -0,0 +1,26 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/field"
)
// UserFollows holds the schema definition for the UserFollows entity.
type UserFollows struct {
ent.Schema
}
// Fields of the UserFollows.
func (UserFollows) Fields() []ent.Field {
return []ent.Field{
field.Int64("id").Immutable().Unique(),
field.Int64("follower_id"),
field.Int64("followee_id"),
field.Time("created_at").Immutable(),
}
}
// Edges of the UserFollows.
func (UserFollows) Edges() []ent.Edge {
return nil
}
@@ -0,0 +1,31 @@
package schema
import (
"time"
"entgo.io/ent"
"entgo.io/ent/schema/field"
)
// UserPreferences holds the schema definition for the UserPreferences entity.
type UserPreferences struct {
ent.Schema
}
// Fields of the UserPreferences.
func (UserPreferences) Fields() []ent.Field {
return []ent.Field{
field.Int64("user_id"),
field.Bool("notification_order").Default(true),
field.Bool("notification_community").Default(true),
field.Bool("notification_system").Default(true),
field.String("theme").Default("light"),
field.String("language").Default("zh-CN"),
field.Time("updated_at").Default(time.Now),
}
}
// Edges of the UserPreferences.
func (UserPreferences) Edges() []ent.Edge {
return nil
}
+11 -7
View File
@@ -1,9 +1,11 @@
package schema
import (
"juwan-backend/pkg/types"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect"
"entgo.io/ent/schema/field"
)
@@ -26,16 +28,18 @@ func (Users) Fields() []ent.Field {
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.String("nickname").Default(""),
field.String("avatar").Default(""),
field.String("bio").Default(""),
field.String("current_role").Default("consumer").NotEmpty(),
//field.Strings("verified_roles").Default([]string{"consumer"}),
field.JSON("verificationStatus", VerificationStatusStruct{}).Optional(),
field.Bool("is_admin").Default(false),
field.Time("created_at").Default(time.Now),
field.Time("updated_at").Default(time.Now),
field.Time("deleted_at"),
field.Time("deleted_at").Optional(),
field.Other("verified_roles", types.TextArray{}).
SchemaType(map[string]string{dialect.Postgres: "text[]"}).Optional(),
}
}
+7 -1
View File
@@ -12,6 +12,10 @@ import (
// Tx is a transactional client that is created by calling Client.Tx().
type Tx struct {
config
// UserFollows is the client for interacting with the UserFollows builders.
UserFollows *UserFollowsClient
// UserPreferences is the client for interacting with the UserPreferences builders.
UserPreferences *UserPreferencesClient
// Users is the client for interacting with the Users builders.
Users *UsersClient
@@ -145,6 +149,8 @@ func (tx *Tx) Client() *Client {
}
func (tx *Tx) init() {
tx.UserFollows = NewUserFollowsClient(tx.config)
tx.UserPreferences = NewUserPreferencesClient(tx.config)
tx.Users = NewUsersClient(tx.config)
}
@@ -155,7 +161,7 @@ func (tx *Tx) init() {
// 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
// applies a query, for example: UserFollows.QueryXXX(), the query will be executed
// through the driver which created this transaction.
//
// Note that txDriver is not goroutine safe.
@@ -0,0 +1,126 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"fmt"
"juwan-backend/app/users/rpc/internal/models/userfollows"
"strings"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
)
// UserFollows is the model entity for the UserFollows schema.
type UserFollows struct {
config `json:"-"`
// ID of the ent.
ID int64 `json:"id,omitempty"`
// FollowerID holds the value of the "follower_id" field.
FollowerID int64 `json:"follower_id,omitempty"`
// FolloweeID holds the value of the "followee_id" field.
FolloweeID int64 `json:"followee_id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt time.Time `json:"created_at,omitempty"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*UserFollows) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case userfollows.FieldID, userfollows.FieldFollowerID, userfollows.FieldFolloweeID:
values[i] = new(sql.NullInt64)
case userfollows.FieldCreatedAt:
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 UserFollows fields.
func (_m *UserFollows) 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 userfollows.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 userfollows.FieldFollowerID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field follower_id", values[i])
} else if value.Valid {
_m.FollowerID = value.Int64
}
case userfollows.FieldFolloweeID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field followee_id", values[i])
} else if value.Valid {
_m.FolloweeID = value.Int64
}
case userfollows.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
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the UserFollows.
// This includes values selected through modifiers, order, etc.
func (_m *UserFollows) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// Update returns a builder for updating this UserFollows.
// Note that you need to call UserFollows.Unwrap() before calling this method if this UserFollows
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *UserFollows) Update() *UserFollowsUpdateOne {
return NewUserFollowsClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the UserFollows 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 *UserFollows) Unwrap() *UserFollows {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("models: UserFollows is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *UserFollows) String() string {
var builder strings.Builder
builder.WriteString("UserFollows(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("follower_id=")
builder.WriteString(fmt.Sprintf("%v", _m.FollowerID))
builder.WriteString(", ")
builder.WriteString("followee_id=")
builder.WriteString(fmt.Sprintf("%v", _m.FolloweeID))
builder.WriteString(", ")
builder.WriteString("created_at=")
builder.WriteString(_m.CreatedAt.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// UserFollowsSlice is a parsable slice of UserFollows.
type UserFollowsSlice []*UserFollows
@@ -0,0 +1,63 @@
// Code generated by ent, DO NOT EDIT.
package userfollows
import (
"entgo.io/ent/dialect/sql"
)
const (
// Label holds the string label denoting the userfollows type in the database.
Label = "user_follows"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldFollowerID holds the string denoting the follower_id field in the database.
FieldFollowerID = "follower_id"
// FieldFolloweeID holds the string denoting the followee_id field in the database.
FieldFolloweeID = "followee_id"
// FieldCreatedAt holds the string denoting the created_at field in the database.
FieldCreatedAt = "created_at"
// Table holds the table name of the userfollows in the database.
Table = "user_follows"
)
// Columns holds all SQL columns for userfollows fields.
var Columns = []string{
FieldID,
FieldFollowerID,
FieldFolloweeID,
FieldCreatedAt,
}
// 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
}
// OrderOption defines the ordering options for the UserFollows 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()
}
// ByFollowerID orders the results by the follower_id field.
func ByFollowerID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldFollowerID, opts...).ToFunc()
}
// ByFolloweeID orders the results by the followee_id field.
func ByFolloweeID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldFolloweeID, opts...).ToFunc()
}
// ByCreatedAt orders the results by the created_at field.
func ByCreatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCreatedAt, opts...).ToFunc()
}
@@ -0,0 +1,205 @@
// Code generated by ent, DO NOT EDIT.
package userfollows
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.UserFollows {
return predicate.UserFollows(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldLTE(FieldID, id))
}
// FollowerID applies equality check predicate on the "follower_id" field. It's identical to FollowerIDEQ.
func FollowerID(v int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldEQ(FieldFollowerID, v))
}
// FolloweeID applies equality check predicate on the "followee_id" field. It's identical to FolloweeIDEQ.
func FolloweeID(v int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldEQ(FieldFolloweeID, v))
}
// CreatedAt applies equality check predicate on the "created_at" field. It's identical to CreatedAtEQ.
func CreatedAt(v time.Time) predicate.UserFollows {
return predicate.UserFollows(sql.FieldEQ(FieldCreatedAt, v))
}
// FollowerIDEQ applies the EQ predicate on the "follower_id" field.
func FollowerIDEQ(v int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldEQ(FieldFollowerID, v))
}
// FollowerIDNEQ applies the NEQ predicate on the "follower_id" field.
func FollowerIDNEQ(v int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldNEQ(FieldFollowerID, v))
}
// FollowerIDIn applies the In predicate on the "follower_id" field.
func FollowerIDIn(vs ...int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldIn(FieldFollowerID, vs...))
}
// FollowerIDNotIn applies the NotIn predicate on the "follower_id" field.
func FollowerIDNotIn(vs ...int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldNotIn(FieldFollowerID, vs...))
}
// FollowerIDGT applies the GT predicate on the "follower_id" field.
func FollowerIDGT(v int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldGT(FieldFollowerID, v))
}
// FollowerIDGTE applies the GTE predicate on the "follower_id" field.
func FollowerIDGTE(v int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldGTE(FieldFollowerID, v))
}
// FollowerIDLT applies the LT predicate on the "follower_id" field.
func FollowerIDLT(v int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldLT(FieldFollowerID, v))
}
// FollowerIDLTE applies the LTE predicate on the "follower_id" field.
func FollowerIDLTE(v int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldLTE(FieldFollowerID, v))
}
// FolloweeIDEQ applies the EQ predicate on the "followee_id" field.
func FolloweeIDEQ(v int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldEQ(FieldFolloweeID, v))
}
// FolloweeIDNEQ applies the NEQ predicate on the "followee_id" field.
func FolloweeIDNEQ(v int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldNEQ(FieldFolloweeID, v))
}
// FolloweeIDIn applies the In predicate on the "followee_id" field.
func FolloweeIDIn(vs ...int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldIn(FieldFolloweeID, vs...))
}
// FolloweeIDNotIn applies the NotIn predicate on the "followee_id" field.
func FolloweeIDNotIn(vs ...int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldNotIn(FieldFolloweeID, vs...))
}
// FolloweeIDGT applies the GT predicate on the "followee_id" field.
func FolloweeIDGT(v int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldGT(FieldFolloweeID, v))
}
// FolloweeIDGTE applies the GTE predicate on the "followee_id" field.
func FolloweeIDGTE(v int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldGTE(FieldFolloweeID, v))
}
// FolloweeIDLT applies the LT predicate on the "followee_id" field.
func FolloweeIDLT(v int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldLT(FieldFolloweeID, v))
}
// FolloweeIDLTE applies the LTE predicate on the "followee_id" field.
func FolloweeIDLTE(v int64) predicate.UserFollows {
return predicate.UserFollows(sql.FieldLTE(FieldFolloweeID, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.UserFollows {
return predicate.UserFollows(sql.FieldEQ(FieldCreatedAt, v))
}
// CreatedAtNEQ applies the NEQ predicate on the "created_at" field.
func CreatedAtNEQ(v time.Time) predicate.UserFollows {
return predicate.UserFollows(sql.FieldNEQ(FieldCreatedAt, v))
}
// CreatedAtIn applies the In predicate on the "created_at" field.
func CreatedAtIn(vs ...time.Time) predicate.UserFollows {
return predicate.UserFollows(sql.FieldIn(FieldCreatedAt, vs...))
}
// CreatedAtNotIn applies the NotIn predicate on the "created_at" field.
func CreatedAtNotIn(vs ...time.Time) predicate.UserFollows {
return predicate.UserFollows(sql.FieldNotIn(FieldCreatedAt, vs...))
}
// CreatedAtGT applies the GT predicate on the "created_at" field.
func CreatedAtGT(v time.Time) predicate.UserFollows {
return predicate.UserFollows(sql.FieldGT(FieldCreatedAt, v))
}
// CreatedAtGTE applies the GTE predicate on the "created_at" field.
func CreatedAtGTE(v time.Time) predicate.UserFollows {
return predicate.UserFollows(sql.FieldGTE(FieldCreatedAt, v))
}
// CreatedAtLT applies the LT predicate on the "created_at" field.
func CreatedAtLT(v time.Time) predicate.UserFollows {
return predicate.UserFollows(sql.FieldLT(FieldCreatedAt, v))
}
// CreatedAtLTE applies the LTE predicate on the "created_at" field.
func CreatedAtLTE(v time.Time) predicate.UserFollows {
return predicate.UserFollows(sql.FieldLTE(FieldCreatedAt, v))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.UserFollows) predicate.UserFollows {
return predicate.UserFollows(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.UserFollows) predicate.UserFollows {
return predicate.UserFollows(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.UserFollows) predicate.UserFollows {
return predicate.UserFollows(sql.NotPredicates(p))
}
@@ -0,0 +1,222 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"errors"
"fmt"
"juwan-backend/app/users/rpc/internal/models/userfollows"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// UserFollowsCreate is the builder for creating a UserFollows entity.
type UserFollowsCreate struct {
config
mutation *UserFollowsMutation
hooks []Hook
}
// SetFollowerID sets the "follower_id" field.
func (_c *UserFollowsCreate) SetFollowerID(v int64) *UserFollowsCreate {
_c.mutation.SetFollowerID(v)
return _c
}
// SetFolloweeID sets the "followee_id" field.
func (_c *UserFollowsCreate) SetFolloweeID(v int64) *UserFollowsCreate {
_c.mutation.SetFolloweeID(v)
return _c
}
// SetCreatedAt sets the "created_at" field.
func (_c *UserFollowsCreate) SetCreatedAt(v time.Time) *UserFollowsCreate {
_c.mutation.SetCreatedAt(v)
return _c
}
// SetID sets the "id" field.
func (_c *UserFollowsCreate) SetID(v int64) *UserFollowsCreate {
_c.mutation.SetID(v)
return _c
}
// Mutation returns the UserFollowsMutation object of the builder.
func (_c *UserFollowsCreate) Mutation() *UserFollowsMutation {
return _c.mutation
}
// Save creates the UserFollows in the database.
func (_c *UserFollowsCreate) Save(ctx context.Context) (*UserFollows, error) {
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *UserFollowsCreate) SaveX(ctx context.Context) *UserFollows {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *UserFollowsCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *UserFollowsCreate) ExecX(ctx context.Context) {
if err := _c.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *UserFollowsCreate) check() error {
if _, ok := _c.mutation.FollowerID(); !ok {
return &ValidationError{Name: "follower_id", err: errors.New(`models: missing required field "UserFollows.follower_id"`)}
}
if _, ok := _c.mutation.FolloweeID(); !ok {
return &ValidationError{Name: "followee_id", err: errors.New(`models: missing required field "UserFollows.followee_id"`)}
}
if _, ok := _c.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`models: missing required field "UserFollows.created_at"`)}
}
return nil
}
func (_c *UserFollowsCreate) sqlSave(ctx context.Context) (*UserFollows, 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 *UserFollowsCreate) createSpec() (*UserFollows, *sqlgraph.CreateSpec) {
var (
_node = &UserFollows{config: _c.config}
_spec = sqlgraph.NewCreateSpec(userfollows.Table, sqlgraph.NewFieldSpec(userfollows.FieldID, field.TypeInt64))
)
if id, ok := _c.mutation.ID(); ok {
_node.ID = id
_spec.ID.Value = id
}
if value, ok := _c.mutation.FollowerID(); ok {
_spec.SetField(userfollows.FieldFollowerID, field.TypeInt64, value)
_node.FollowerID = value
}
if value, ok := _c.mutation.FolloweeID(); ok {
_spec.SetField(userfollows.FieldFolloweeID, field.TypeInt64, value)
_node.FolloweeID = value
}
if value, ok := _c.mutation.CreatedAt(); ok {
_spec.SetField(userfollows.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = value
}
return _node, _spec
}
// UserFollowsCreateBulk is the builder for creating many UserFollows entities in bulk.
type UserFollowsCreateBulk struct {
config
err error
builders []*UserFollowsCreate
}
// Save creates the UserFollows entities in the database.
func (_c *UserFollowsCreateBulk) Save(ctx context.Context) ([]*UserFollows, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*UserFollows, len(_c.builders))
mutators := make([]Mutator, len(_c.builders))
for i := range _c.builders {
func(i int, root context.Context) {
builder := _c.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*UserFollowsMutation)
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 *UserFollowsCreateBulk) SaveX(ctx context.Context) []*UserFollows {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *UserFollowsCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *UserFollowsCreateBulk) 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/userfollows"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// UserFollowsDelete is the builder for deleting a UserFollows entity.
type UserFollowsDelete struct {
config
hooks []Hook
mutation *UserFollowsMutation
}
// Where appends a list predicates to the UserFollowsDelete builder.
func (_d *UserFollowsDelete) Where(ps ...predicate.UserFollows) *UserFollowsDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *UserFollowsDelete) 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 *UserFollowsDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *UserFollowsDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(userfollows.Table, sqlgraph.NewFieldSpec(userfollows.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
}
// UserFollowsDeleteOne is the builder for deleting a single UserFollows entity.
type UserFollowsDeleteOne struct {
_d *UserFollowsDelete
}
// Where appends a list predicates to the UserFollowsDelete builder.
func (_d *UserFollowsDeleteOne) Where(ps ...predicate.UserFollows) *UserFollowsDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *UserFollowsDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{userfollows.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *UserFollowsDeleteOne) 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/userfollows"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// UserFollowsQuery is the builder for querying UserFollows entities.
type UserFollowsQuery struct {
config
ctx *QueryContext
order []userfollows.OrderOption
inters []Interceptor
predicates []predicate.UserFollows
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the UserFollowsQuery builder.
func (_q *UserFollowsQuery) Where(ps ...predicate.UserFollows) *UserFollowsQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *UserFollowsQuery) Limit(limit int) *UserFollowsQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *UserFollowsQuery) Offset(offset int) *UserFollowsQuery {
_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 *UserFollowsQuery) Unique(unique bool) *UserFollowsQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *UserFollowsQuery) Order(o ...userfollows.OrderOption) *UserFollowsQuery {
_q.order = append(_q.order, o...)
return _q
}
// First returns the first UserFollows entity from the query.
// Returns a *NotFoundError when no UserFollows was found.
func (_q *UserFollowsQuery) First(ctx context.Context) (*UserFollows, 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{userfollows.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *UserFollowsQuery) FirstX(ctx context.Context) *UserFollows {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first UserFollows ID from the query.
// Returns a *NotFoundError when no UserFollows ID was found.
func (_q *UserFollowsQuery) 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{userfollows.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *UserFollowsQuery) FirstIDX(ctx context.Context) int64 {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single UserFollows entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one UserFollows entity is found.
// Returns a *NotFoundError when no UserFollows entities are found.
func (_q *UserFollowsQuery) Only(ctx context.Context) (*UserFollows, 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{userfollows.Label}
default:
return nil, &NotSingularError{userfollows.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *UserFollowsQuery) OnlyX(ctx context.Context) *UserFollows {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only UserFollows ID in the query.
// Returns a *NotSingularError when more than one UserFollows ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *UserFollowsQuery) 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{userfollows.Label}
default:
err = &NotSingularError{userfollows.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *UserFollowsQuery) 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 UserFollowsSlice.
func (_q *UserFollowsQuery) All(ctx context.Context) ([]*UserFollows, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*UserFollows, *UserFollowsQuery]()
return withInterceptors[[]*UserFollows](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *UserFollowsQuery) AllX(ctx context.Context) []*UserFollows {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of UserFollows IDs.
func (_q *UserFollowsQuery) 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(userfollows.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *UserFollowsQuery) 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 *UserFollowsQuery) 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[*UserFollowsQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *UserFollowsQuery) 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 *UserFollowsQuery) 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 *UserFollowsQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the UserFollowsQuery 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 *UserFollowsQuery) Clone() *UserFollowsQuery {
if _q == nil {
return nil
}
return &UserFollowsQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]userfollows.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.UserFollows{}, _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 {
// FollowerID int64 `json:"follower_id,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.UserFollows.Query().
// GroupBy(userfollows.FieldFollowerID).
// Aggregate(models.Count()).
// Scan(ctx, &v)
func (_q *UserFollowsQuery) GroupBy(field string, fields ...string) *UserFollowsGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &UserFollowsGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = userfollows.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 {
// FollowerID int64 `json:"follower_id,omitempty"`
// }
//
// client.UserFollows.Query().
// Select(userfollows.FieldFollowerID).
// Scan(ctx, &v)
func (_q *UserFollowsQuery) Select(fields ...string) *UserFollowsSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &UserFollowsSelect{UserFollowsQuery: _q}
sbuild.label = userfollows.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a UserFollowsSelect configured with the given aggregations.
func (_q *UserFollowsQuery) Aggregate(fns ...AggregateFunc) *UserFollowsSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *UserFollowsQuery) 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 !userfollows.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 *UserFollowsQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*UserFollows, error) {
var (
nodes = []*UserFollows{}
_spec = _q.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*UserFollows).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &UserFollows{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 *UserFollowsQuery) 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 *UserFollowsQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(userfollows.Table, userfollows.Columns, sqlgraph.NewFieldSpec(userfollows.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, userfollows.FieldID)
for i := range fields {
if fields[i] != userfollows.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 *UserFollowsQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(userfollows.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = userfollows.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
}
// UserFollowsGroupBy is the group-by builder for UserFollows entities.
type UserFollowsGroupBy struct {
selector
build *UserFollowsQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *UserFollowsGroupBy) Aggregate(fns ...AggregateFunc) *UserFollowsGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *UserFollowsGroupBy) 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[*UserFollowsQuery, *UserFollowsGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *UserFollowsGroupBy) sqlScan(ctx context.Context, root *UserFollowsQuery, 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)
}
// UserFollowsSelect is the builder for selecting fields of UserFollows entities.
type UserFollowsSelect struct {
*UserFollowsQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *UserFollowsSelect) Aggregate(fns ...AggregateFunc) *UserFollowsSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *UserFollowsSelect) 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[*UserFollowsQuery, *UserFollowsSelect](ctx, _s.UserFollowsQuery, _s, _s.inters, v)
}
func (_s *UserFollowsSelect) sqlScan(ctx context.Context, root *UserFollowsQuery, 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,283 @@
// 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/userfollows"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// UserFollowsUpdate is the builder for updating UserFollows entities.
type UserFollowsUpdate struct {
config
hooks []Hook
mutation *UserFollowsMutation
}
// Where appends a list predicates to the UserFollowsUpdate builder.
func (_u *UserFollowsUpdate) Where(ps ...predicate.UserFollows) *UserFollowsUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetFollowerID sets the "follower_id" field.
func (_u *UserFollowsUpdate) SetFollowerID(v int64) *UserFollowsUpdate {
_u.mutation.ResetFollowerID()
_u.mutation.SetFollowerID(v)
return _u
}
// SetNillableFollowerID sets the "follower_id" field if the given value is not nil.
func (_u *UserFollowsUpdate) SetNillableFollowerID(v *int64) *UserFollowsUpdate {
if v != nil {
_u.SetFollowerID(*v)
}
return _u
}
// AddFollowerID adds value to the "follower_id" field.
func (_u *UserFollowsUpdate) AddFollowerID(v int64) *UserFollowsUpdate {
_u.mutation.AddFollowerID(v)
return _u
}
// SetFolloweeID sets the "followee_id" field.
func (_u *UserFollowsUpdate) SetFolloweeID(v int64) *UserFollowsUpdate {
_u.mutation.ResetFolloweeID()
_u.mutation.SetFolloweeID(v)
return _u
}
// SetNillableFolloweeID sets the "followee_id" field if the given value is not nil.
func (_u *UserFollowsUpdate) SetNillableFolloweeID(v *int64) *UserFollowsUpdate {
if v != nil {
_u.SetFolloweeID(*v)
}
return _u
}
// AddFolloweeID adds value to the "followee_id" field.
func (_u *UserFollowsUpdate) AddFolloweeID(v int64) *UserFollowsUpdate {
_u.mutation.AddFolloweeID(v)
return _u
}
// Mutation returns the UserFollowsMutation object of the builder.
func (_u *UserFollowsUpdate) Mutation() *UserFollowsMutation {
return _u.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *UserFollowsUpdate) 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 *UserFollowsUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *UserFollowsUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *UserFollowsUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
func (_u *UserFollowsUpdate) sqlSave(ctx context.Context) (_node int, err error) {
_spec := sqlgraph.NewUpdateSpec(userfollows.Table, userfollows.Columns, sqlgraph.NewFieldSpec(userfollows.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.FollowerID(); ok {
_spec.SetField(userfollows.FieldFollowerID, field.TypeInt64, value)
}
if value, ok := _u.mutation.AddedFollowerID(); ok {
_spec.AddField(userfollows.FieldFollowerID, field.TypeInt64, value)
}
if value, ok := _u.mutation.FolloweeID(); ok {
_spec.SetField(userfollows.FieldFolloweeID, field.TypeInt64, value)
}
if value, ok := _u.mutation.AddedFolloweeID(); ok {
_spec.AddField(userfollows.FieldFolloweeID, field.TypeInt64, value)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{userfollows.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// UserFollowsUpdateOne is the builder for updating a single UserFollows entity.
type UserFollowsUpdateOne struct {
config
fields []string
hooks []Hook
mutation *UserFollowsMutation
}
// SetFollowerID sets the "follower_id" field.
func (_u *UserFollowsUpdateOne) SetFollowerID(v int64) *UserFollowsUpdateOne {
_u.mutation.ResetFollowerID()
_u.mutation.SetFollowerID(v)
return _u
}
// SetNillableFollowerID sets the "follower_id" field if the given value is not nil.
func (_u *UserFollowsUpdateOne) SetNillableFollowerID(v *int64) *UserFollowsUpdateOne {
if v != nil {
_u.SetFollowerID(*v)
}
return _u
}
// AddFollowerID adds value to the "follower_id" field.
func (_u *UserFollowsUpdateOne) AddFollowerID(v int64) *UserFollowsUpdateOne {
_u.mutation.AddFollowerID(v)
return _u
}
// SetFolloweeID sets the "followee_id" field.
func (_u *UserFollowsUpdateOne) SetFolloweeID(v int64) *UserFollowsUpdateOne {
_u.mutation.ResetFolloweeID()
_u.mutation.SetFolloweeID(v)
return _u
}
// SetNillableFolloweeID sets the "followee_id" field if the given value is not nil.
func (_u *UserFollowsUpdateOne) SetNillableFolloweeID(v *int64) *UserFollowsUpdateOne {
if v != nil {
_u.SetFolloweeID(*v)
}
return _u
}
// AddFolloweeID adds value to the "followee_id" field.
func (_u *UserFollowsUpdateOne) AddFolloweeID(v int64) *UserFollowsUpdateOne {
_u.mutation.AddFolloweeID(v)
return _u
}
// Mutation returns the UserFollowsMutation object of the builder.
func (_u *UserFollowsUpdateOne) Mutation() *UserFollowsMutation {
return _u.mutation
}
// Where appends a list predicates to the UserFollowsUpdate builder.
func (_u *UserFollowsUpdateOne) Where(ps ...predicate.UserFollows) *UserFollowsUpdateOne {
_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 *UserFollowsUpdateOne) Select(field string, fields ...string) *UserFollowsUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated UserFollows entity.
func (_u *UserFollowsUpdateOne) Save(ctx context.Context) (*UserFollows, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *UserFollowsUpdateOne) SaveX(ctx context.Context) *UserFollows {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *UserFollowsUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *UserFollowsUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
func (_u *UserFollowsUpdateOne) sqlSave(ctx context.Context) (_node *UserFollows, err error) {
_spec := sqlgraph.NewUpdateSpec(userfollows.Table, userfollows.Columns, sqlgraph.NewFieldSpec(userfollows.FieldID, field.TypeInt64))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "UserFollows.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, userfollows.FieldID)
for _, f := range fields {
if !userfollows.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)}
}
if f != userfollows.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.FollowerID(); ok {
_spec.SetField(userfollows.FieldFollowerID, field.TypeInt64, value)
}
if value, ok := _u.mutation.AddedFollowerID(); ok {
_spec.AddField(userfollows.FieldFollowerID, field.TypeInt64, value)
}
if value, ok := _u.mutation.FolloweeID(); ok {
_spec.SetField(userfollows.FieldFolloweeID, field.TypeInt64, value)
}
if value, ok := _u.mutation.AddedFolloweeID(); ok {
_spec.AddField(userfollows.FieldFolloweeID, field.TypeInt64, value)
}
_node = &UserFollows{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{userfollows.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}
@@ -0,0 +1,174 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"fmt"
"juwan-backend/app/users/rpc/internal/models/userpreferences"
"strings"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
)
// UserPreferences is the model entity for the UserPreferences schema.
type UserPreferences struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// UserID holds the value of the "user_id" field.
UserID int64 `json:"user_id,omitempty"`
// NotificationOrder holds the value of the "notification_order" field.
NotificationOrder bool `json:"notification_order,omitempty"`
// NotificationCommunity holds the value of the "notification_community" field.
NotificationCommunity bool `json:"notification_community,omitempty"`
// NotificationSystem holds the value of the "notification_system" field.
NotificationSystem bool `json:"notification_system,omitempty"`
// Theme holds the value of the "theme" field.
Theme string `json:"theme,omitempty"`
// Language holds the value of the "language" field.
Language string `json:"language,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt time.Time `json:"updated_at,omitempty"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*UserPreferences) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case userpreferences.FieldNotificationOrder, userpreferences.FieldNotificationCommunity, userpreferences.FieldNotificationSystem:
values[i] = new(sql.NullBool)
case userpreferences.FieldID, userpreferences.FieldUserID:
values[i] = new(sql.NullInt64)
case userpreferences.FieldTheme, userpreferences.FieldLanguage:
values[i] = new(sql.NullString)
case userpreferences.FieldUpdatedAt:
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 UserPreferences fields.
func (_m *UserPreferences) 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 userpreferences.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
_m.ID = int(value.Int64)
case userpreferences.FieldUserID:
if value, ok := values[i].(*sql.NullInt64); !ok {
return fmt.Errorf("unexpected type %T for field user_id", values[i])
} else if value.Valid {
_m.UserID = value.Int64
}
case userpreferences.FieldNotificationOrder:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field notification_order", values[i])
} else if value.Valid {
_m.NotificationOrder = value.Bool
}
case userpreferences.FieldNotificationCommunity:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field notification_community", values[i])
} else if value.Valid {
_m.NotificationCommunity = value.Bool
}
case userpreferences.FieldNotificationSystem:
if value, ok := values[i].(*sql.NullBool); !ok {
return fmt.Errorf("unexpected type %T for field notification_system", values[i])
} else if value.Valid {
_m.NotificationSystem = value.Bool
}
case userpreferences.FieldTheme:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field theme", values[i])
} else if value.Valid {
_m.Theme = value.String
}
case userpreferences.FieldLanguage:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field language", values[i])
} else if value.Valid {
_m.Language = value.String
}
case userpreferences.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
}
default:
_m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the UserPreferences.
// This includes values selected through modifiers, order, etc.
func (_m *UserPreferences) Value(name string) (ent.Value, error) {
return _m.selectValues.Get(name)
}
// Update returns a builder for updating this UserPreferences.
// Note that you need to call UserPreferences.Unwrap() before calling this method if this UserPreferences
// was returned from a transaction, and the transaction was committed or rolled back.
func (_m *UserPreferences) Update() *UserPreferencesUpdateOne {
return NewUserPreferencesClient(_m.config).UpdateOne(_m)
}
// Unwrap unwraps the UserPreferences 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 *UserPreferences) Unwrap() *UserPreferences {
_tx, ok := _m.config.driver.(*txDriver)
if !ok {
panic("models: UserPreferences is not a transactional entity")
}
_m.config.driver = _tx.drv
return _m
}
// String implements the fmt.Stringer.
func (_m *UserPreferences) String() string {
var builder strings.Builder
builder.WriteString("UserPreferences(")
builder.WriteString(fmt.Sprintf("id=%v, ", _m.ID))
builder.WriteString("user_id=")
builder.WriteString(fmt.Sprintf("%v", _m.UserID))
builder.WriteString(", ")
builder.WriteString("notification_order=")
builder.WriteString(fmt.Sprintf("%v", _m.NotificationOrder))
builder.WriteString(", ")
builder.WriteString("notification_community=")
builder.WriteString(fmt.Sprintf("%v", _m.NotificationCommunity))
builder.WriteString(", ")
builder.WriteString("notification_system=")
builder.WriteString(fmt.Sprintf("%v", _m.NotificationSystem))
builder.WriteString(", ")
builder.WriteString("theme=")
builder.WriteString(_m.Theme)
builder.WriteString(", ")
builder.WriteString("language=")
builder.WriteString(_m.Language)
builder.WriteString(", ")
builder.WriteString("updated_at=")
builder.WriteString(_m.UpdatedAt.Format(time.ANSIC))
builder.WriteByte(')')
return builder.String()
}
// UserPreferencesSlice is a parsable slice of UserPreferences.
type UserPreferencesSlice []*UserPreferences
@@ -0,0 +1,112 @@
// Code generated by ent, DO NOT EDIT.
package userpreferences
import (
"time"
"entgo.io/ent/dialect/sql"
)
const (
// Label holds the string label denoting the userpreferences type in the database.
Label = "user_preferences"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldUserID holds the string denoting the user_id field in the database.
FieldUserID = "user_id"
// FieldNotificationOrder holds the string denoting the notification_order field in the database.
FieldNotificationOrder = "notification_order"
// FieldNotificationCommunity holds the string denoting the notification_community field in the database.
FieldNotificationCommunity = "notification_community"
// FieldNotificationSystem holds the string denoting the notification_system field in the database.
FieldNotificationSystem = "notification_system"
// FieldTheme holds the string denoting the theme field in the database.
FieldTheme = "theme"
// FieldLanguage holds the string denoting the language field in the database.
FieldLanguage = "language"
// FieldUpdatedAt holds the string denoting the updated_at field in the database.
FieldUpdatedAt = "updated_at"
// Table holds the table name of the userpreferences in the database.
Table = "user_preferences"
)
// Columns holds all SQL columns for userpreferences fields.
var Columns = []string{
FieldID,
FieldUserID,
FieldNotificationOrder,
FieldNotificationCommunity,
FieldNotificationSystem,
FieldTheme,
FieldLanguage,
FieldUpdatedAt,
}
// 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 (
// DefaultNotificationOrder holds the default value on creation for the "notification_order" field.
DefaultNotificationOrder bool
// DefaultNotificationCommunity holds the default value on creation for the "notification_community" field.
DefaultNotificationCommunity bool
// DefaultNotificationSystem holds the default value on creation for the "notification_system" field.
DefaultNotificationSystem bool
// DefaultTheme holds the default value on creation for the "theme" field.
DefaultTheme string
// DefaultLanguage holds the default value on creation for the "language" field.
DefaultLanguage string
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
)
// OrderOption defines the ordering options for the UserPreferences 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()
}
// ByUserID orders the results by the user_id field.
func ByUserID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUserID, opts...).ToFunc()
}
// ByNotificationOrder orders the results by the notification_order field.
func ByNotificationOrder(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldNotificationOrder, opts...).ToFunc()
}
// ByNotificationCommunity orders the results by the notification_community field.
func ByNotificationCommunity(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldNotificationCommunity, opts...).ToFunc()
}
// ByNotificationSystem orders the results by the notification_system field.
func ByNotificationSystem(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldNotificationSystem, opts...).ToFunc()
}
// ByTheme orders the results by the theme field.
func ByTheme(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldTheme, opts...).ToFunc()
}
// ByLanguage orders the results by the language field.
func ByLanguage(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldLanguage, opts...).ToFunc()
}
// ByUpdatedAt orders the results by the updated_at field.
func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldUpdatedAt, opts...).ToFunc()
}
@@ -0,0 +1,345 @@
// Code generated by ent, DO NOT EDIT.
package userpreferences
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 int) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldLTE(FieldID, id))
}
// UserID applies equality check predicate on the "user_id" field. It's identical to UserIDEQ.
func UserID(v int64) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldEQ(FieldUserID, v))
}
// NotificationOrder applies equality check predicate on the "notification_order" field. It's identical to NotificationOrderEQ.
func NotificationOrder(v bool) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldEQ(FieldNotificationOrder, v))
}
// NotificationCommunity applies equality check predicate on the "notification_community" field. It's identical to NotificationCommunityEQ.
func NotificationCommunity(v bool) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldEQ(FieldNotificationCommunity, v))
}
// NotificationSystem applies equality check predicate on the "notification_system" field. It's identical to NotificationSystemEQ.
func NotificationSystem(v bool) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldEQ(FieldNotificationSystem, v))
}
// Theme applies equality check predicate on the "theme" field. It's identical to ThemeEQ.
func Theme(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldEQ(FieldTheme, v))
}
// Language applies equality check predicate on the "language" field. It's identical to LanguageEQ.
func Language(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldEQ(FieldLanguage, v))
}
// UpdatedAt applies equality check predicate on the "updated_at" field. It's identical to UpdatedAtEQ.
func UpdatedAt(v time.Time) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldEQ(FieldUpdatedAt, v))
}
// UserIDEQ applies the EQ predicate on the "user_id" field.
func UserIDEQ(v int64) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldEQ(FieldUserID, v))
}
// UserIDNEQ applies the NEQ predicate on the "user_id" field.
func UserIDNEQ(v int64) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldNEQ(FieldUserID, v))
}
// UserIDIn applies the In predicate on the "user_id" field.
func UserIDIn(vs ...int64) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldIn(FieldUserID, vs...))
}
// UserIDNotIn applies the NotIn predicate on the "user_id" field.
func UserIDNotIn(vs ...int64) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldNotIn(FieldUserID, vs...))
}
// UserIDGT applies the GT predicate on the "user_id" field.
func UserIDGT(v int64) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldGT(FieldUserID, v))
}
// UserIDGTE applies the GTE predicate on the "user_id" field.
func UserIDGTE(v int64) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldGTE(FieldUserID, v))
}
// UserIDLT applies the LT predicate on the "user_id" field.
func UserIDLT(v int64) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldLT(FieldUserID, v))
}
// UserIDLTE applies the LTE predicate on the "user_id" field.
func UserIDLTE(v int64) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldLTE(FieldUserID, v))
}
// NotificationOrderEQ applies the EQ predicate on the "notification_order" field.
func NotificationOrderEQ(v bool) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldEQ(FieldNotificationOrder, v))
}
// NotificationOrderNEQ applies the NEQ predicate on the "notification_order" field.
func NotificationOrderNEQ(v bool) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldNEQ(FieldNotificationOrder, v))
}
// NotificationCommunityEQ applies the EQ predicate on the "notification_community" field.
func NotificationCommunityEQ(v bool) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldEQ(FieldNotificationCommunity, v))
}
// NotificationCommunityNEQ applies the NEQ predicate on the "notification_community" field.
func NotificationCommunityNEQ(v bool) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldNEQ(FieldNotificationCommunity, v))
}
// NotificationSystemEQ applies the EQ predicate on the "notification_system" field.
func NotificationSystemEQ(v bool) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldEQ(FieldNotificationSystem, v))
}
// NotificationSystemNEQ applies the NEQ predicate on the "notification_system" field.
func NotificationSystemNEQ(v bool) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldNEQ(FieldNotificationSystem, v))
}
// ThemeEQ applies the EQ predicate on the "theme" field.
func ThemeEQ(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldEQ(FieldTheme, v))
}
// ThemeNEQ applies the NEQ predicate on the "theme" field.
func ThemeNEQ(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldNEQ(FieldTheme, v))
}
// ThemeIn applies the In predicate on the "theme" field.
func ThemeIn(vs ...string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldIn(FieldTheme, vs...))
}
// ThemeNotIn applies the NotIn predicate on the "theme" field.
func ThemeNotIn(vs ...string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldNotIn(FieldTheme, vs...))
}
// ThemeGT applies the GT predicate on the "theme" field.
func ThemeGT(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldGT(FieldTheme, v))
}
// ThemeGTE applies the GTE predicate on the "theme" field.
func ThemeGTE(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldGTE(FieldTheme, v))
}
// ThemeLT applies the LT predicate on the "theme" field.
func ThemeLT(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldLT(FieldTheme, v))
}
// ThemeLTE applies the LTE predicate on the "theme" field.
func ThemeLTE(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldLTE(FieldTheme, v))
}
// ThemeContains applies the Contains predicate on the "theme" field.
func ThemeContains(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldContains(FieldTheme, v))
}
// ThemeHasPrefix applies the HasPrefix predicate on the "theme" field.
func ThemeHasPrefix(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldHasPrefix(FieldTheme, v))
}
// ThemeHasSuffix applies the HasSuffix predicate on the "theme" field.
func ThemeHasSuffix(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldHasSuffix(FieldTheme, v))
}
// ThemeEqualFold applies the EqualFold predicate on the "theme" field.
func ThemeEqualFold(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldEqualFold(FieldTheme, v))
}
// ThemeContainsFold applies the ContainsFold predicate on the "theme" field.
func ThemeContainsFold(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldContainsFold(FieldTheme, v))
}
// LanguageEQ applies the EQ predicate on the "language" field.
func LanguageEQ(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldEQ(FieldLanguage, v))
}
// LanguageNEQ applies the NEQ predicate on the "language" field.
func LanguageNEQ(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldNEQ(FieldLanguage, v))
}
// LanguageIn applies the In predicate on the "language" field.
func LanguageIn(vs ...string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldIn(FieldLanguage, vs...))
}
// LanguageNotIn applies the NotIn predicate on the "language" field.
func LanguageNotIn(vs ...string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldNotIn(FieldLanguage, vs...))
}
// LanguageGT applies the GT predicate on the "language" field.
func LanguageGT(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldGT(FieldLanguage, v))
}
// LanguageGTE applies the GTE predicate on the "language" field.
func LanguageGTE(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldGTE(FieldLanguage, v))
}
// LanguageLT applies the LT predicate on the "language" field.
func LanguageLT(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldLT(FieldLanguage, v))
}
// LanguageLTE applies the LTE predicate on the "language" field.
func LanguageLTE(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldLTE(FieldLanguage, v))
}
// LanguageContains applies the Contains predicate on the "language" field.
func LanguageContains(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldContains(FieldLanguage, v))
}
// LanguageHasPrefix applies the HasPrefix predicate on the "language" field.
func LanguageHasPrefix(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldHasPrefix(FieldLanguage, v))
}
// LanguageHasSuffix applies the HasSuffix predicate on the "language" field.
func LanguageHasSuffix(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldHasSuffix(FieldLanguage, v))
}
// LanguageEqualFold applies the EqualFold predicate on the "language" field.
func LanguageEqualFold(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldEqualFold(FieldLanguage, v))
}
// LanguageContainsFold applies the ContainsFold predicate on the "language" field.
func LanguageContainsFold(v string) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldContainsFold(FieldLanguage, v))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldEQ(FieldUpdatedAt, v))
}
// UpdatedAtNEQ applies the NEQ predicate on the "updated_at" field.
func UpdatedAtNEQ(v time.Time) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldNEQ(FieldUpdatedAt, v))
}
// UpdatedAtIn applies the In predicate on the "updated_at" field.
func UpdatedAtIn(vs ...time.Time) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldIn(FieldUpdatedAt, vs...))
}
// UpdatedAtNotIn applies the NotIn predicate on the "updated_at" field.
func UpdatedAtNotIn(vs ...time.Time) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldNotIn(FieldUpdatedAt, vs...))
}
// UpdatedAtGT applies the GT predicate on the "updated_at" field.
func UpdatedAtGT(v time.Time) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldGT(FieldUpdatedAt, v))
}
// UpdatedAtGTE applies the GTE predicate on the "updated_at" field.
func UpdatedAtGTE(v time.Time) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldGTE(FieldUpdatedAt, v))
}
// UpdatedAtLT applies the LT predicate on the "updated_at" field.
func UpdatedAtLT(v time.Time) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldLT(FieldUpdatedAt, v))
}
// UpdatedAtLTE applies the LTE predicate on the "updated_at" field.
func UpdatedAtLTE(v time.Time) predicate.UserPreferences {
return predicate.UserPreferences(sql.FieldLTE(FieldUpdatedAt, v))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.UserPreferences) predicate.UserPreferences {
return predicate.UserPreferences(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.UserPreferences) predicate.UserPreferences {
return predicate.UserPreferences(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.UserPreferences) predicate.UserPreferences {
return predicate.UserPreferences(sql.NotPredicates(p))
}
@@ -0,0 +1,340 @@
// Code generated by ent, DO NOT EDIT.
package models
import (
"context"
"errors"
"fmt"
"juwan-backend/app/users/rpc/internal/models/userpreferences"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// UserPreferencesCreate is the builder for creating a UserPreferences entity.
type UserPreferencesCreate struct {
config
mutation *UserPreferencesMutation
hooks []Hook
}
// SetUserID sets the "user_id" field.
func (_c *UserPreferencesCreate) SetUserID(v int64) *UserPreferencesCreate {
_c.mutation.SetUserID(v)
return _c
}
// SetNotificationOrder sets the "notification_order" field.
func (_c *UserPreferencesCreate) SetNotificationOrder(v bool) *UserPreferencesCreate {
_c.mutation.SetNotificationOrder(v)
return _c
}
// SetNillableNotificationOrder sets the "notification_order" field if the given value is not nil.
func (_c *UserPreferencesCreate) SetNillableNotificationOrder(v *bool) *UserPreferencesCreate {
if v != nil {
_c.SetNotificationOrder(*v)
}
return _c
}
// SetNotificationCommunity sets the "notification_community" field.
func (_c *UserPreferencesCreate) SetNotificationCommunity(v bool) *UserPreferencesCreate {
_c.mutation.SetNotificationCommunity(v)
return _c
}
// SetNillableNotificationCommunity sets the "notification_community" field if the given value is not nil.
func (_c *UserPreferencesCreate) SetNillableNotificationCommunity(v *bool) *UserPreferencesCreate {
if v != nil {
_c.SetNotificationCommunity(*v)
}
return _c
}
// SetNotificationSystem sets the "notification_system" field.
func (_c *UserPreferencesCreate) SetNotificationSystem(v bool) *UserPreferencesCreate {
_c.mutation.SetNotificationSystem(v)
return _c
}
// SetNillableNotificationSystem sets the "notification_system" field if the given value is not nil.
func (_c *UserPreferencesCreate) SetNillableNotificationSystem(v *bool) *UserPreferencesCreate {
if v != nil {
_c.SetNotificationSystem(*v)
}
return _c
}
// SetTheme sets the "theme" field.
func (_c *UserPreferencesCreate) SetTheme(v string) *UserPreferencesCreate {
_c.mutation.SetTheme(v)
return _c
}
// SetNillableTheme sets the "theme" field if the given value is not nil.
func (_c *UserPreferencesCreate) SetNillableTheme(v *string) *UserPreferencesCreate {
if v != nil {
_c.SetTheme(*v)
}
return _c
}
// SetLanguage sets the "language" field.
func (_c *UserPreferencesCreate) SetLanguage(v string) *UserPreferencesCreate {
_c.mutation.SetLanguage(v)
return _c
}
// SetNillableLanguage sets the "language" field if the given value is not nil.
func (_c *UserPreferencesCreate) SetNillableLanguage(v *string) *UserPreferencesCreate {
if v != nil {
_c.SetLanguage(*v)
}
return _c
}
// SetUpdatedAt sets the "updated_at" field.
func (_c *UserPreferencesCreate) SetUpdatedAt(v time.Time) *UserPreferencesCreate {
_c.mutation.SetUpdatedAt(v)
return _c
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_c *UserPreferencesCreate) SetNillableUpdatedAt(v *time.Time) *UserPreferencesCreate {
if v != nil {
_c.SetUpdatedAt(*v)
}
return _c
}
// Mutation returns the UserPreferencesMutation object of the builder.
func (_c *UserPreferencesCreate) Mutation() *UserPreferencesMutation {
return _c.mutation
}
// Save creates the UserPreferences in the database.
func (_c *UserPreferencesCreate) Save(ctx context.Context) (*UserPreferences, error) {
_c.defaults()
return withHooks(ctx, _c.sqlSave, _c.mutation, _c.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (_c *UserPreferencesCreate) SaveX(ctx context.Context) *UserPreferences {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *UserPreferencesCreate) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *UserPreferencesCreate) 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 *UserPreferencesCreate) defaults() {
if _, ok := _c.mutation.NotificationOrder(); !ok {
v := userpreferences.DefaultNotificationOrder
_c.mutation.SetNotificationOrder(v)
}
if _, ok := _c.mutation.NotificationCommunity(); !ok {
v := userpreferences.DefaultNotificationCommunity
_c.mutation.SetNotificationCommunity(v)
}
if _, ok := _c.mutation.NotificationSystem(); !ok {
v := userpreferences.DefaultNotificationSystem
_c.mutation.SetNotificationSystem(v)
}
if _, ok := _c.mutation.Theme(); !ok {
v := userpreferences.DefaultTheme
_c.mutation.SetTheme(v)
}
if _, ok := _c.mutation.Language(); !ok {
v := userpreferences.DefaultLanguage
_c.mutation.SetLanguage(v)
}
if _, ok := _c.mutation.UpdatedAt(); !ok {
v := userpreferences.DefaultUpdatedAt()
_c.mutation.SetUpdatedAt(v)
}
}
// check runs all checks and user-defined validators on the builder.
func (_c *UserPreferencesCreate) check() error {
if _, ok := _c.mutation.UserID(); !ok {
return &ValidationError{Name: "user_id", err: errors.New(`models: missing required field "UserPreferences.user_id"`)}
}
if _, ok := _c.mutation.NotificationOrder(); !ok {
return &ValidationError{Name: "notification_order", err: errors.New(`models: missing required field "UserPreferences.notification_order"`)}
}
if _, ok := _c.mutation.NotificationCommunity(); !ok {
return &ValidationError{Name: "notification_community", err: errors.New(`models: missing required field "UserPreferences.notification_community"`)}
}
if _, ok := _c.mutation.NotificationSystem(); !ok {
return &ValidationError{Name: "notification_system", err: errors.New(`models: missing required field "UserPreferences.notification_system"`)}
}
if _, ok := _c.mutation.Theme(); !ok {
return &ValidationError{Name: "theme", err: errors.New(`models: missing required field "UserPreferences.theme"`)}
}
if _, ok := _c.mutation.Language(); !ok {
return &ValidationError{Name: "language", err: errors.New(`models: missing required field "UserPreferences.language"`)}
}
if _, ok := _c.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`models: missing required field "UserPreferences.updated_at"`)}
}
return nil
}
func (_c *UserPreferencesCreate) sqlSave(ctx context.Context) (*UserPreferences, 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
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
_c.mutation.id = &_node.ID
_c.mutation.done = true
return _node, nil
}
func (_c *UserPreferencesCreate) createSpec() (*UserPreferences, *sqlgraph.CreateSpec) {
var (
_node = &UserPreferences{config: _c.config}
_spec = sqlgraph.NewCreateSpec(userpreferences.Table, sqlgraph.NewFieldSpec(userpreferences.FieldID, field.TypeInt))
)
if value, ok := _c.mutation.UserID(); ok {
_spec.SetField(userpreferences.FieldUserID, field.TypeInt64, value)
_node.UserID = value
}
if value, ok := _c.mutation.NotificationOrder(); ok {
_spec.SetField(userpreferences.FieldNotificationOrder, field.TypeBool, value)
_node.NotificationOrder = value
}
if value, ok := _c.mutation.NotificationCommunity(); ok {
_spec.SetField(userpreferences.FieldNotificationCommunity, field.TypeBool, value)
_node.NotificationCommunity = value
}
if value, ok := _c.mutation.NotificationSystem(); ok {
_spec.SetField(userpreferences.FieldNotificationSystem, field.TypeBool, value)
_node.NotificationSystem = value
}
if value, ok := _c.mutation.Theme(); ok {
_spec.SetField(userpreferences.FieldTheme, field.TypeString, value)
_node.Theme = value
}
if value, ok := _c.mutation.Language(); ok {
_spec.SetField(userpreferences.FieldLanguage, field.TypeString, value)
_node.Language = value
}
if value, ok := _c.mutation.UpdatedAt(); ok {
_spec.SetField(userpreferences.FieldUpdatedAt, field.TypeTime, value)
_node.UpdatedAt = value
}
return _node, _spec
}
// UserPreferencesCreateBulk is the builder for creating many UserPreferences entities in bulk.
type UserPreferencesCreateBulk struct {
config
err error
builders []*UserPreferencesCreate
}
// Save creates the UserPreferences entities in the database.
func (_c *UserPreferencesCreateBulk) Save(ctx context.Context) ([]*UserPreferences, error) {
if _c.err != nil {
return nil, _c.err
}
specs := make([]*sqlgraph.CreateSpec, len(_c.builders))
nodes := make([]*UserPreferences, 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.(*UserPreferencesMutation)
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 {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(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 *UserPreferencesCreateBulk) SaveX(ctx context.Context) []*UserPreferences {
v, err := _c.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (_c *UserPreferencesCreateBulk) Exec(ctx context.Context) error {
_, err := _c.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_c *UserPreferencesCreateBulk) 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/userpreferences"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// UserPreferencesDelete is the builder for deleting a UserPreferences entity.
type UserPreferencesDelete struct {
config
hooks []Hook
mutation *UserPreferencesMutation
}
// Where appends a list predicates to the UserPreferencesDelete builder.
func (_d *UserPreferencesDelete) Where(ps ...predicate.UserPreferences) *UserPreferencesDelete {
_d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (_d *UserPreferencesDelete) 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 *UserPreferencesDelete) ExecX(ctx context.Context) int {
n, err := _d.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (_d *UserPreferencesDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(userpreferences.Table, sqlgraph.NewFieldSpec(userpreferences.FieldID, field.TypeInt))
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
}
// UserPreferencesDeleteOne is the builder for deleting a single UserPreferences entity.
type UserPreferencesDeleteOne struct {
_d *UserPreferencesDelete
}
// Where appends a list predicates to the UserPreferencesDelete builder.
func (_d *UserPreferencesDeleteOne) Where(ps ...predicate.UserPreferences) *UserPreferencesDeleteOne {
_d._d.mutation.Where(ps...)
return _d
}
// Exec executes the deletion query.
func (_d *UserPreferencesDeleteOne) Exec(ctx context.Context) error {
n, err := _d._d.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{userpreferences.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (_d *UserPreferencesDeleteOne) 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/userpreferences"
"math"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// UserPreferencesQuery is the builder for querying UserPreferences entities.
type UserPreferencesQuery struct {
config
ctx *QueryContext
order []userpreferences.OrderOption
inters []Interceptor
predicates []predicate.UserPreferences
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the UserPreferencesQuery builder.
func (_q *UserPreferencesQuery) Where(ps ...predicate.UserPreferences) *UserPreferencesQuery {
_q.predicates = append(_q.predicates, ps...)
return _q
}
// Limit the number of records to be returned by this query.
func (_q *UserPreferencesQuery) Limit(limit int) *UserPreferencesQuery {
_q.ctx.Limit = &limit
return _q
}
// Offset to start from.
func (_q *UserPreferencesQuery) Offset(offset int) *UserPreferencesQuery {
_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 *UserPreferencesQuery) Unique(unique bool) *UserPreferencesQuery {
_q.ctx.Unique = &unique
return _q
}
// Order specifies how the records should be ordered.
func (_q *UserPreferencesQuery) Order(o ...userpreferences.OrderOption) *UserPreferencesQuery {
_q.order = append(_q.order, o...)
return _q
}
// First returns the first UserPreferences entity from the query.
// Returns a *NotFoundError when no UserPreferences was found.
func (_q *UserPreferencesQuery) First(ctx context.Context) (*UserPreferences, 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{userpreferences.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (_q *UserPreferencesQuery) FirstX(ctx context.Context) *UserPreferences {
node, err := _q.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first UserPreferences ID from the query.
// Returns a *NotFoundError when no UserPreferences ID was found.
func (_q *UserPreferencesQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = _q.Limit(1).IDs(setContextOp(ctx, _q.ctx, ent.OpQueryFirstID)); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{userpreferences.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (_q *UserPreferencesQuery) FirstIDX(ctx context.Context) int {
id, err := _q.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single UserPreferences entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one UserPreferences entity is found.
// Returns a *NotFoundError when no UserPreferences entities are found.
func (_q *UserPreferencesQuery) Only(ctx context.Context) (*UserPreferences, 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{userpreferences.Label}
default:
return nil, &NotSingularError{userpreferences.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (_q *UserPreferencesQuery) OnlyX(ctx context.Context) *UserPreferences {
node, err := _q.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only UserPreferences ID in the query.
// Returns a *NotSingularError when more than one UserPreferences ID is found.
// Returns a *NotFoundError when no entities are found.
func (_q *UserPreferencesQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
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{userpreferences.Label}
default:
err = &NotSingularError{userpreferences.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (_q *UserPreferencesQuery) OnlyIDX(ctx context.Context) int {
id, err := _q.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of UserPreferencesSlice.
func (_q *UserPreferencesQuery) All(ctx context.Context) ([]*UserPreferences, error) {
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryAll)
if err := _q.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*UserPreferences, *UserPreferencesQuery]()
return withInterceptors[[]*UserPreferences](ctx, _q, qr, _q.inters)
}
// AllX is like All, but panics if an error occurs.
func (_q *UserPreferencesQuery) AllX(ctx context.Context) []*UserPreferences {
nodes, err := _q.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of UserPreferences IDs.
func (_q *UserPreferencesQuery) IDs(ctx context.Context) (ids []int, err error) {
if _q.ctx.Unique == nil && _q.path != nil {
_q.Unique(true)
}
ctx = setContextOp(ctx, _q.ctx, ent.OpQueryIDs)
if err = _q.Select(userpreferences.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (_q *UserPreferencesQuery) IDsX(ctx context.Context) []int {
ids, err := _q.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (_q *UserPreferencesQuery) 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[*UserPreferencesQuery](), _q.inters)
}
// CountX is like Count, but panics if an error occurs.
func (_q *UserPreferencesQuery) 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 *UserPreferencesQuery) 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 *UserPreferencesQuery) ExistX(ctx context.Context) bool {
exist, err := _q.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the UserPreferencesQuery 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 *UserPreferencesQuery) Clone() *UserPreferencesQuery {
if _q == nil {
return nil
}
return &UserPreferencesQuery{
config: _q.config,
ctx: _q.ctx.Clone(),
order: append([]userpreferences.OrderOption{}, _q.order...),
inters: append([]Interceptor{}, _q.inters...),
predicates: append([]predicate.UserPreferences{}, _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 {
// UserID int64 `json:"user_id,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.UserPreferences.Query().
// GroupBy(userpreferences.FieldUserID).
// Aggregate(models.Count()).
// Scan(ctx, &v)
func (_q *UserPreferencesQuery) GroupBy(field string, fields ...string) *UserPreferencesGroupBy {
_q.ctx.Fields = append([]string{field}, fields...)
grbuild := &UserPreferencesGroupBy{build: _q}
grbuild.flds = &_q.ctx.Fields
grbuild.label = userpreferences.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 {
// UserID int64 `json:"user_id,omitempty"`
// }
//
// client.UserPreferences.Query().
// Select(userpreferences.FieldUserID).
// Scan(ctx, &v)
func (_q *UserPreferencesQuery) Select(fields ...string) *UserPreferencesSelect {
_q.ctx.Fields = append(_q.ctx.Fields, fields...)
sbuild := &UserPreferencesSelect{UserPreferencesQuery: _q}
sbuild.label = userpreferences.Label
sbuild.flds, sbuild.scan = &_q.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a UserPreferencesSelect configured with the given aggregations.
func (_q *UserPreferencesQuery) Aggregate(fns ...AggregateFunc) *UserPreferencesSelect {
return _q.Select().Aggregate(fns...)
}
func (_q *UserPreferencesQuery) 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 !userpreferences.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 *UserPreferencesQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*UserPreferences, error) {
var (
nodes = []*UserPreferences{}
_spec = _q.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*UserPreferences).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &UserPreferences{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 *UserPreferencesQuery) 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 *UserPreferencesQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(userpreferences.Table, userpreferences.Columns, sqlgraph.NewFieldSpec(userpreferences.FieldID, field.TypeInt))
_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, userpreferences.FieldID)
for i := range fields {
if fields[i] != userpreferences.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 *UserPreferencesQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(_q.driver.Dialect())
t1 := builder.Table(userpreferences.Table)
columns := _q.ctx.Fields
if len(columns) == 0 {
columns = userpreferences.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
}
// UserPreferencesGroupBy is the group-by builder for UserPreferences entities.
type UserPreferencesGroupBy struct {
selector
build *UserPreferencesQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (_g *UserPreferencesGroupBy) Aggregate(fns ...AggregateFunc) *UserPreferencesGroupBy {
_g.fns = append(_g.fns, fns...)
return _g
}
// Scan applies the selector query and scans the result into the given value.
func (_g *UserPreferencesGroupBy) 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[*UserPreferencesQuery, *UserPreferencesGroupBy](ctx, _g.build, _g, _g.build.inters, v)
}
func (_g *UserPreferencesGroupBy) sqlScan(ctx context.Context, root *UserPreferencesQuery, 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)
}
// UserPreferencesSelect is the builder for selecting fields of UserPreferences entities.
type UserPreferencesSelect struct {
*UserPreferencesQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (_s *UserPreferencesSelect) Aggregate(fns ...AggregateFunc) *UserPreferencesSelect {
_s.fns = append(_s.fns, fns...)
return _s
}
// Scan applies the selector query and scans the result into the given value.
func (_s *UserPreferencesSelect) 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[*UserPreferencesQuery, *UserPreferencesSelect](ctx, _s.UserPreferencesQuery, _s, _s.inters, v)
}
func (_s *UserPreferencesSelect) sqlScan(ctx context.Context, root *UserPreferencesQuery, 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,434 @@
// 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/userpreferences"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
)
// UserPreferencesUpdate is the builder for updating UserPreferences entities.
type UserPreferencesUpdate struct {
config
hooks []Hook
mutation *UserPreferencesMutation
}
// Where appends a list predicates to the UserPreferencesUpdate builder.
func (_u *UserPreferencesUpdate) Where(ps ...predicate.UserPreferences) *UserPreferencesUpdate {
_u.mutation.Where(ps...)
return _u
}
// SetUserID sets the "user_id" field.
func (_u *UserPreferencesUpdate) SetUserID(v int64) *UserPreferencesUpdate {
_u.mutation.ResetUserID()
_u.mutation.SetUserID(v)
return _u
}
// SetNillableUserID sets the "user_id" field if the given value is not nil.
func (_u *UserPreferencesUpdate) SetNillableUserID(v *int64) *UserPreferencesUpdate {
if v != nil {
_u.SetUserID(*v)
}
return _u
}
// AddUserID adds value to the "user_id" field.
func (_u *UserPreferencesUpdate) AddUserID(v int64) *UserPreferencesUpdate {
_u.mutation.AddUserID(v)
return _u
}
// SetNotificationOrder sets the "notification_order" field.
func (_u *UserPreferencesUpdate) SetNotificationOrder(v bool) *UserPreferencesUpdate {
_u.mutation.SetNotificationOrder(v)
return _u
}
// SetNillableNotificationOrder sets the "notification_order" field if the given value is not nil.
func (_u *UserPreferencesUpdate) SetNillableNotificationOrder(v *bool) *UserPreferencesUpdate {
if v != nil {
_u.SetNotificationOrder(*v)
}
return _u
}
// SetNotificationCommunity sets the "notification_community" field.
func (_u *UserPreferencesUpdate) SetNotificationCommunity(v bool) *UserPreferencesUpdate {
_u.mutation.SetNotificationCommunity(v)
return _u
}
// SetNillableNotificationCommunity sets the "notification_community" field if the given value is not nil.
func (_u *UserPreferencesUpdate) SetNillableNotificationCommunity(v *bool) *UserPreferencesUpdate {
if v != nil {
_u.SetNotificationCommunity(*v)
}
return _u
}
// SetNotificationSystem sets the "notification_system" field.
func (_u *UserPreferencesUpdate) SetNotificationSystem(v bool) *UserPreferencesUpdate {
_u.mutation.SetNotificationSystem(v)
return _u
}
// SetNillableNotificationSystem sets the "notification_system" field if the given value is not nil.
func (_u *UserPreferencesUpdate) SetNillableNotificationSystem(v *bool) *UserPreferencesUpdate {
if v != nil {
_u.SetNotificationSystem(*v)
}
return _u
}
// SetTheme sets the "theme" field.
func (_u *UserPreferencesUpdate) SetTheme(v string) *UserPreferencesUpdate {
_u.mutation.SetTheme(v)
return _u
}
// SetNillableTheme sets the "theme" field if the given value is not nil.
func (_u *UserPreferencesUpdate) SetNillableTheme(v *string) *UserPreferencesUpdate {
if v != nil {
_u.SetTheme(*v)
}
return _u
}
// SetLanguage sets the "language" field.
func (_u *UserPreferencesUpdate) SetLanguage(v string) *UserPreferencesUpdate {
_u.mutation.SetLanguage(v)
return _u
}
// SetNillableLanguage sets the "language" field if the given value is not nil.
func (_u *UserPreferencesUpdate) SetNillableLanguage(v *string) *UserPreferencesUpdate {
if v != nil {
_u.SetLanguage(*v)
}
return _u
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *UserPreferencesUpdate) SetUpdatedAt(v time.Time) *UserPreferencesUpdate {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_u *UserPreferencesUpdate) SetNillableUpdatedAt(v *time.Time) *UserPreferencesUpdate {
if v != nil {
_u.SetUpdatedAt(*v)
}
return _u
}
// Mutation returns the UserPreferencesMutation object of the builder.
func (_u *UserPreferencesUpdate) Mutation() *UserPreferencesMutation {
return _u.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (_u *UserPreferencesUpdate) 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 *UserPreferencesUpdate) SaveX(ctx context.Context) int {
affected, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (_u *UserPreferencesUpdate) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *UserPreferencesUpdate) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
func (_u *UserPreferencesUpdate) sqlSave(ctx context.Context) (_node int, err error) {
_spec := sqlgraph.NewUpdateSpec(userpreferences.Table, userpreferences.Columns, sqlgraph.NewFieldSpec(userpreferences.FieldID, field.TypeInt))
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.UserID(); ok {
_spec.SetField(userpreferences.FieldUserID, field.TypeInt64, value)
}
if value, ok := _u.mutation.AddedUserID(); ok {
_spec.AddField(userpreferences.FieldUserID, field.TypeInt64, value)
}
if value, ok := _u.mutation.NotificationOrder(); ok {
_spec.SetField(userpreferences.FieldNotificationOrder, field.TypeBool, value)
}
if value, ok := _u.mutation.NotificationCommunity(); ok {
_spec.SetField(userpreferences.FieldNotificationCommunity, field.TypeBool, value)
}
if value, ok := _u.mutation.NotificationSystem(); ok {
_spec.SetField(userpreferences.FieldNotificationSystem, field.TypeBool, value)
}
if value, ok := _u.mutation.Theme(); ok {
_spec.SetField(userpreferences.FieldTheme, field.TypeString, value)
}
if value, ok := _u.mutation.Language(); ok {
_spec.SetField(userpreferences.FieldLanguage, field.TypeString, value)
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(userpreferences.FieldUpdatedAt, field.TypeTime, value)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{userpreferences.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
_u.mutation.done = true
return _node, nil
}
// UserPreferencesUpdateOne is the builder for updating a single UserPreferences entity.
type UserPreferencesUpdateOne struct {
config
fields []string
hooks []Hook
mutation *UserPreferencesMutation
}
// SetUserID sets the "user_id" field.
func (_u *UserPreferencesUpdateOne) SetUserID(v int64) *UserPreferencesUpdateOne {
_u.mutation.ResetUserID()
_u.mutation.SetUserID(v)
return _u
}
// SetNillableUserID sets the "user_id" field if the given value is not nil.
func (_u *UserPreferencesUpdateOne) SetNillableUserID(v *int64) *UserPreferencesUpdateOne {
if v != nil {
_u.SetUserID(*v)
}
return _u
}
// AddUserID adds value to the "user_id" field.
func (_u *UserPreferencesUpdateOne) AddUserID(v int64) *UserPreferencesUpdateOne {
_u.mutation.AddUserID(v)
return _u
}
// SetNotificationOrder sets the "notification_order" field.
func (_u *UserPreferencesUpdateOne) SetNotificationOrder(v bool) *UserPreferencesUpdateOne {
_u.mutation.SetNotificationOrder(v)
return _u
}
// SetNillableNotificationOrder sets the "notification_order" field if the given value is not nil.
func (_u *UserPreferencesUpdateOne) SetNillableNotificationOrder(v *bool) *UserPreferencesUpdateOne {
if v != nil {
_u.SetNotificationOrder(*v)
}
return _u
}
// SetNotificationCommunity sets the "notification_community" field.
func (_u *UserPreferencesUpdateOne) SetNotificationCommunity(v bool) *UserPreferencesUpdateOne {
_u.mutation.SetNotificationCommunity(v)
return _u
}
// SetNillableNotificationCommunity sets the "notification_community" field if the given value is not nil.
func (_u *UserPreferencesUpdateOne) SetNillableNotificationCommunity(v *bool) *UserPreferencesUpdateOne {
if v != nil {
_u.SetNotificationCommunity(*v)
}
return _u
}
// SetNotificationSystem sets the "notification_system" field.
func (_u *UserPreferencesUpdateOne) SetNotificationSystem(v bool) *UserPreferencesUpdateOne {
_u.mutation.SetNotificationSystem(v)
return _u
}
// SetNillableNotificationSystem sets the "notification_system" field if the given value is not nil.
func (_u *UserPreferencesUpdateOne) SetNillableNotificationSystem(v *bool) *UserPreferencesUpdateOne {
if v != nil {
_u.SetNotificationSystem(*v)
}
return _u
}
// SetTheme sets the "theme" field.
func (_u *UserPreferencesUpdateOne) SetTheme(v string) *UserPreferencesUpdateOne {
_u.mutation.SetTheme(v)
return _u
}
// SetNillableTheme sets the "theme" field if the given value is not nil.
func (_u *UserPreferencesUpdateOne) SetNillableTheme(v *string) *UserPreferencesUpdateOne {
if v != nil {
_u.SetTheme(*v)
}
return _u
}
// SetLanguage sets the "language" field.
func (_u *UserPreferencesUpdateOne) SetLanguage(v string) *UserPreferencesUpdateOne {
_u.mutation.SetLanguage(v)
return _u
}
// SetNillableLanguage sets the "language" field if the given value is not nil.
func (_u *UserPreferencesUpdateOne) SetNillableLanguage(v *string) *UserPreferencesUpdateOne {
if v != nil {
_u.SetLanguage(*v)
}
return _u
}
// SetUpdatedAt sets the "updated_at" field.
func (_u *UserPreferencesUpdateOne) SetUpdatedAt(v time.Time) *UserPreferencesUpdateOne {
_u.mutation.SetUpdatedAt(v)
return _u
}
// SetNillableUpdatedAt sets the "updated_at" field if the given value is not nil.
func (_u *UserPreferencesUpdateOne) SetNillableUpdatedAt(v *time.Time) *UserPreferencesUpdateOne {
if v != nil {
_u.SetUpdatedAt(*v)
}
return _u
}
// Mutation returns the UserPreferencesMutation object of the builder.
func (_u *UserPreferencesUpdateOne) Mutation() *UserPreferencesMutation {
return _u.mutation
}
// Where appends a list predicates to the UserPreferencesUpdate builder.
func (_u *UserPreferencesUpdateOne) Where(ps ...predicate.UserPreferences) *UserPreferencesUpdateOne {
_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 *UserPreferencesUpdateOne) Select(field string, fields ...string) *UserPreferencesUpdateOne {
_u.fields = append([]string{field}, fields...)
return _u
}
// Save executes the query and returns the updated UserPreferences entity.
func (_u *UserPreferencesUpdateOne) Save(ctx context.Context) (*UserPreferences, error) {
return withHooks(ctx, _u.sqlSave, _u.mutation, _u.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (_u *UserPreferencesUpdateOne) SaveX(ctx context.Context) *UserPreferences {
node, err := _u.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (_u *UserPreferencesUpdateOne) Exec(ctx context.Context) error {
_, err := _u.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (_u *UserPreferencesUpdateOne) ExecX(ctx context.Context) {
if err := _u.Exec(ctx); err != nil {
panic(err)
}
}
func (_u *UserPreferencesUpdateOne) sqlSave(ctx context.Context) (_node *UserPreferences, err error) {
_spec := sqlgraph.NewUpdateSpec(userpreferences.Table, userpreferences.Columns, sqlgraph.NewFieldSpec(userpreferences.FieldID, field.TypeInt))
id, ok := _u.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`models: missing "UserPreferences.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, userpreferences.FieldID)
for _, f := range fields {
if !userpreferences.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("models: invalid field %q for query", f)}
}
if f != userpreferences.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.UserID(); ok {
_spec.SetField(userpreferences.FieldUserID, field.TypeInt64, value)
}
if value, ok := _u.mutation.AddedUserID(); ok {
_spec.AddField(userpreferences.FieldUserID, field.TypeInt64, value)
}
if value, ok := _u.mutation.NotificationOrder(); ok {
_spec.SetField(userpreferences.FieldNotificationOrder, field.TypeBool, value)
}
if value, ok := _u.mutation.NotificationCommunity(); ok {
_spec.SetField(userpreferences.FieldNotificationCommunity, field.TypeBool, value)
}
if value, ok := _u.mutation.NotificationSystem(); ok {
_spec.SetField(userpreferences.FieldNotificationSystem, field.TypeBool, value)
}
if value, ok := _u.mutation.Theme(); ok {
_spec.SetField(userpreferences.FieldTheme, field.TypeString, value)
}
if value, ok := _u.mutation.Language(); ok {
_spec.SetField(userpreferences.FieldLanguage, field.TypeString, value)
}
if value, ok := _u.mutation.UpdatedAt(); ok {
_spec.SetField(userpreferences.FieldUpdatedAt, field.TypeTime, value)
}
_node = &UserPreferences{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{userpreferences.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
_u.mutation.done = true
return _node, nil
}
+18 -17
View File
@@ -7,6 +7,7 @@ import (
"fmt"
"juwan-backend/app/users/rpc/internal/models/schema"
"juwan-backend/app/users/rpc/internal/models/users"
"juwan-backend/pkg/types"
"strings"
"time"
@@ -14,7 +15,7 @@ import (
"entgo.io/ent/dialect/sql"
)
// Users is the models entity for the Users schema.
// Users is the model entity for the Users schema.
type Users struct {
config `json:"-"`
// ID of the ent.
@@ -35,8 +36,6 @@ type Users struct {
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.
@@ -46,8 +45,10 @@ type Users struct {
// 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
DeletedAt time.Time `json:"deleted_at,omitempty"`
// VerifiedRoles holds the value of the "verified_roles" field.
VerifiedRoles types.TextArray `json:"verified_roles,omitempty"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
@@ -55,7 +56,7 @@ func (*Users) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case users.FieldVerifiedRoles, users.FieldVerificationStatus:
case users.FieldVerificationStatus:
values[i] = new([]byte)
case users.FieldIsAdmin:
values[i] = new(sql.NullBool)
@@ -65,6 +66,8 @@ func (*Users) scanValues(columns []string) ([]any, error) {
values[i] = new(sql.NullString)
case users.FieldCreatedAt, users.FieldUpdatedAt, users.FieldDeletedAt:
values[i] = new(sql.NullTime)
case users.FieldVerifiedRoles:
values[i] = new(types.TextArray)
default:
values[i] = new(sql.UnknownType)
}
@@ -134,14 +137,6 @@ func (_m *Users) assignValues(columns []string, values []any) error {
} 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])
@@ -174,6 +169,12 @@ func (_m *Users) assignValues(columns []string, values []any) error {
} else if value.Valid {
_m.DeletedAt = value.Time
}
case users.FieldVerifiedRoles:
if value, ok := values[i].(*types.TextArray); !ok {
return fmt.Errorf("unexpected type %T for field verified_roles", values[i])
} else if value != nil {
_m.VerifiedRoles = *value
}
default:
_m.selectValues.Set(columns[i], values[i])
}
@@ -234,9 +235,6 @@ func (_m *Users) String() string {
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(", ")
@@ -251,6 +249,9 @@ func (_m *Users) String() string {
builder.WriteString(", ")
builder.WriteString("deleted_at=")
builder.WriteString(_m.DeletedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("verified_roles=")
builder.WriteString(fmt.Sprintf("%v", _m.VerifiedRoles))
builder.WriteByte(')')
return builder.String()
}
+18 -3
View File
@@ -29,8 +29,6 @@ const (
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.
@@ -41,6 +39,8 @@ const (
FieldUpdatedAt = "updated_at"
// FieldDeletedAt holds the string denoting the deleted_at field in the database.
FieldDeletedAt = "deleted_at"
// FieldVerifiedRoles holds the string denoting the verified_roles field in the database.
FieldVerifiedRoles = "verified_roles"
// Table holds the table name of the users in the database.
Table = "users"
)
@@ -56,12 +56,12 @@ var Columns = []string{
FieldAvatar,
FieldBio,
FieldCurrentRole,
FieldVerifiedRoles,
FieldVerificationStatus,
FieldIsAdmin,
FieldCreatedAt,
FieldUpdatedAt,
FieldDeletedAt,
FieldVerifiedRoles,
}
// ValidColumn reports if the column name is valid (part of the table columns).
@@ -75,6 +75,16 @@ func ValidColumn(column string) bool {
}
var (
// DefaultNickname holds the default value on creation for the "nickname" field.
DefaultNickname string
// DefaultAvatar holds the default value on creation for the "avatar" field.
DefaultAvatar string
// DefaultBio holds the default value on creation for the "bio" field.
DefaultBio string
// DefaultCurrentRole holds the default value on creation for the "current_role" field.
DefaultCurrentRole string
// CurrentRoleValidator is a validator for the "current_role" field. It is called by the builders before save.
CurrentRoleValidator func(string) error
// 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.
@@ -150,3 +160,8 @@ func ByUpdatedAt(opts ...sql.OrderTermOption) OrderOption {
func ByDeletedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldDeletedAt, opts...).ToFunc()
}
// ByVerifiedRoles orders the results by the verified_roles field.
func ByVerifiedRoles(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldVerifiedRoles, opts...).ToFunc()
}
@@ -4,6 +4,7 @@ package users
import (
"juwan-backend/app/users/rpc/internal/models/predicate"
"juwan-backend/pkg/types"
"time"
"entgo.io/ent/dialect/sql"
@@ -114,6 +115,11 @@ func DeletedAt(v time.Time) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldDeletedAt, v))
}
// VerifiedRoles applies equality check predicate on the "verified_roles" field. It's identical to VerifiedRolesEQ.
func VerifiedRoles(v types.TextArray) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldVerifiedRoles, v))
}
// UsernameEQ applies the EQ predicate on the "username" field.
func UsernameEQ(v string) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldUsername, v))
@@ -634,6 +640,16 @@ func CurrentRoleContainsFold(v string) predicate.Users {
return predicate.Users(sql.FieldContainsFold(FieldCurrentRole, v))
}
// VerificationStatusIsNil applies the IsNil predicate on the "verificationStatus" field.
func VerificationStatusIsNil() predicate.Users {
return predicate.Users(sql.FieldIsNull(FieldVerificationStatus))
}
// VerificationStatusNotNil applies the NotNil predicate on the "verificationStatus" field.
func VerificationStatusNotNil() predicate.Users {
return predicate.Users(sql.FieldNotNull(FieldVerificationStatus))
}
// IsAdminEQ applies the EQ predicate on the "is_admin" field.
func IsAdminEQ(v bool) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldIsAdmin, v))
@@ -764,6 +780,66 @@ func DeletedAtLTE(v time.Time) predicate.Users {
return predicate.Users(sql.FieldLTE(FieldDeletedAt, v))
}
// DeletedAtIsNil applies the IsNil predicate on the "deleted_at" field.
func DeletedAtIsNil() predicate.Users {
return predicate.Users(sql.FieldIsNull(FieldDeletedAt))
}
// DeletedAtNotNil applies the NotNil predicate on the "deleted_at" field.
func DeletedAtNotNil() predicate.Users {
return predicate.Users(sql.FieldNotNull(FieldDeletedAt))
}
// VerifiedRolesEQ applies the EQ predicate on the "verified_roles" field.
func VerifiedRolesEQ(v types.TextArray) predicate.Users {
return predicate.Users(sql.FieldEQ(FieldVerifiedRoles, v))
}
// VerifiedRolesNEQ applies the NEQ predicate on the "verified_roles" field.
func VerifiedRolesNEQ(v types.TextArray) predicate.Users {
return predicate.Users(sql.FieldNEQ(FieldVerifiedRoles, v))
}
// VerifiedRolesIn applies the In predicate on the "verified_roles" field.
func VerifiedRolesIn(vs ...types.TextArray) predicate.Users {
return predicate.Users(sql.FieldIn(FieldVerifiedRoles, vs...))
}
// VerifiedRolesNotIn applies the NotIn predicate on the "verified_roles" field.
func VerifiedRolesNotIn(vs ...types.TextArray) predicate.Users {
return predicate.Users(sql.FieldNotIn(FieldVerifiedRoles, vs...))
}
// VerifiedRolesGT applies the GT predicate on the "verified_roles" field.
func VerifiedRolesGT(v types.TextArray) predicate.Users {
return predicate.Users(sql.FieldGT(FieldVerifiedRoles, v))
}
// VerifiedRolesGTE applies the GTE predicate on the "verified_roles" field.
func VerifiedRolesGTE(v types.TextArray) predicate.Users {
return predicate.Users(sql.FieldGTE(FieldVerifiedRoles, v))
}
// VerifiedRolesLT applies the LT predicate on the "verified_roles" field.
func VerifiedRolesLT(v types.TextArray) predicate.Users {
return predicate.Users(sql.FieldLT(FieldVerifiedRoles, v))
}
// VerifiedRolesLTE applies the LTE predicate on the "verified_roles" field.
func VerifiedRolesLTE(v types.TextArray) predicate.Users {
return predicate.Users(sql.FieldLTE(FieldVerifiedRoles, v))
}
// VerifiedRolesIsNil applies the IsNil predicate on the "verified_roles" field.
func VerifiedRolesIsNil() predicate.Users {
return predicate.Users(sql.FieldIsNull(FieldVerifiedRoles))
}
// VerifiedRolesNotNil applies the NotNil predicate on the "verified_roles" field.
func VerifiedRolesNotNil() predicate.Users {
return predicate.Users(sql.FieldNotNull(FieldVerifiedRoles))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Users) predicate.Users {
return predicate.Users(sql.AndPredicates(predicates...))
+84 -15
View File
@@ -8,6 +8,7 @@ import (
"fmt"
"juwan-backend/app/users/rpc/internal/models/schema"
"juwan-backend/app/users/rpc/internal/models/users"
"juwan-backend/pkg/types"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
@@ -51,27 +52,53 @@ func (_c *UsersCreate) SetNickname(v string) *UsersCreate {
return _c
}
// SetNillableNickname sets the "nickname" field if the given value is not nil.
func (_c *UsersCreate) SetNillableNickname(v *string) *UsersCreate {
if v != nil {
_c.SetNickname(*v)
}
return _c
}
// SetAvatar sets the "avatar" field.
func (_c *UsersCreate) SetAvatar(v string) *UsersCreate {
_c.mutation.SetAvatar(v)
return _c
}
// SetNillableAvatar sets the "avatar" field if the given value is not nil.
func (_c *UsersCreate) SetNillableAvatar(v *string) *UsersCreate {
if v != nil {
_c.SetAvatar(*v)
}
return _c
}
// SetBio sets the "bio" field.
func (_c *UsersCreate) SetBio(v string) *UsersCreate {
_c.mutation.SetBio(v)
return _c
}
// SetNillableBio sets the "bio" field if the given value is not nil.
func (_c *UsersCreate) SetNillableBio(v *string) *UsersCreate {
if v != nil {
_c.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)
// SetNillableCurrentRole sets the "current_role" field if the given value is not nil.
func (_c *UsersCreate) SetNillableCurrentRole(v *string) *UsersCreate {
if v != nil {
_c.SetCurrentRole(*v)
}
return _c
}
@@ -81,6 +108,14 @@ func (_c *UsersCreate) SetVerificationStatus(v schema.VerificationStatusStruct)
return _c
}
// SetNillableVerificationStatus sets the "verificationStatus" field if the given value is not nil.
func (_c *UsersCreate) SetNillableVerificationStatus(v *schema.VerificationStatusStruct) *UsersCreate {
if v != nil {
_c.SetVerificationStatus(*v)
}
return _c
}
// SetIsAdmin sets the "is_admin" field.
func (_c *UsersCreate) SetIsAdmin(v bool) *UsersCreate {
_c.mutation.SetIsAdmin(v)
@@ -129,6 +164,28 @@ func (_c *UsersCreate) SetDeletedAt(v time.Time) *UsersCreate {
return _c
}
// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (_c *UsersCreate) SetNillableDeletedAt(v *time.Time) *UsersCreate {
if v != nil {
_c.SetDeletedAt(*v)
}
return _c
}
// SetVerifiedRoles sets the "verified_roles" field.
func (_c *UsersCreate) SetVerifiedRoles(v types.TextArray) *UsersCreate {
_c.mutation.SetVerifiedRoles(v)
return _c
}
// SetNillableVerifiedRoles sets the "verified_roles" field if the given value is not nil.
func (_c *UsersCreate) SetNillableVerifiedRoles(v *types.TextArray) *UsersCreate {
if v != nil {
_c.SetVerifiedRoles(*v)
}
return _c
}
// SetID sets the "id" field.
func (_c *UsersCreate) SetID(v int64) *UsersCreate {
_c.mutation.SetID(v)
@@ -170,6 +227,22 @@ func (_c *UsersCreate) ExecX(ctx context.Context) {
// defaults sets the default values of the builder before save.
func (_c *UsersCreate) defaults() {
if _, ok := _c.mutation.Nickname(); !ok {
v := users.DefaultNickname
_c.mutation.SetNickname(v)
}
if _, ok := _c.mutation.Avatar(); !ok {
v := users.DefaultAvatar
_c.mutation.SetAvatar(v)
}
if _, ok := _c.mutation.Bio(); !ok {
v := users.DefaultBio
_c.mutation.SetBio(v)
}
if _, ok := _c.mutation.CurrentRole(); !ok {
v := users.DefaultCurrentRole
_c.mutation.SetCurrentRole(v)
}
if _, ok := _c.mutation.IsAdmin(); !ok {
v := users.DefaultIsAdmin
_c.mutation.SetIsAdmin(v)
@@ -210,11 +283,10 @@ func (_c *UsersCreate) check() error {
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 v, ok := _c.mutation.CurrentRole(); ok {
if err := users.CurrentRoleValidator(v); err != nil {
return &ValidationError{Name: "current_role", err: fmt.Errorf(`models: validator failed for field "Users.current_role": %w`, err)}
}
}
if _, ok := _c.mutation.IsAdmin(); !ok {
return &ValidationError{Name: "is_admin", err: errors.New(`models: missing required field "Users.is_admin"`)}
@@ -225,9 +297,6 @@ func (_c *UsersCreate) check() error {
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
}
@@ -292,10 +361,6 @@ func (_c *UsersCreate) createSpec() (*Users, *sqlgraph.CreateSpec) {
_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
@@ -316,6 +381,10 @@ func (_c *UsersCreate) createSpec() (*Users, *sqlgraph.CreateSpec) {
_spec.SetField(users.FieldDeletedAt, field.TypeTime, value)
_node.DeletedAt = value
}
if value, ok := _c.mutation.VerifiedRoles(); ok {
_spec.SetField(users.FieldVerifiedRoles, field.TypeOther, value)
_node.VerifiedRoles = value
}
return _node, _spec
}
+115 -41
View File
@@ -9,11 +9,11 @@ import (
"juwan-backend/app/users/rpc/internal/models/predicate"
"juwan-backend/app/users/rpc/internal/models/schema"
"juwan-backend/app/users/rpc/internal/models/users"
"juwan-backend/pkg/types"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/dialect/sql/sqljson"
"entgo.io/ent/schema/field"
)
@@ -142,18 +142,6 @@ func (_u *UsersUpdate) SetNillableCurrentRole(v *string) *UsersUpdate {
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)
@@ -168,6 +156,12 @@ func (_u *UsersUpdate) SetNillableVerificationStatus(v *schema.VerificationStatu
return _u
}
// ClearVerificationStatus clears the value of the "verificationStatus" field.
func (_u *UsersUpdate) ClearVerificationStatus() *UsersUpdate {
_u.mutation.ClearVerificationStatus()
return _u
}
// SetIsAdmin sets the "is_admin" field.
func (_u *UsersUpdate) SetIsAdmin(v bool) *UsersUpdate {
_u.mutation.SetIsAdmin(v)
@@ -224,6 +218,32 @@ func (_u *UsersUpdate) SetNillableDeletedAt(v *time.Time) *UsersUpdate {
return _u
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *UsersUpdate) ClearDeletedAt() *UsersUpdate {
_u.mutation.ClearDeletedAt()
return _u
}
// SetVerifiedRoles sets the "verified_roles" field.
func (_u *UsersUpdate) SetVerifiedRoles(v types.TextArray) *UsersUpdate {
_u.mutation.SetVerifiedRoles(v)
return _u
}
// SetNillableVerifiedRoles sets the "verified_roles" field if the given value is not nil.
func (_u *UsersUpdate) SetNillableVerifiedRoles(v *types.TextArray) *UsersUpdate {
if v != nil {
_u.SetVerifiedRoles(*v)
}
return _u
}
// ClearVerifiedRoles clears the value of the "verified_roles" field.
func (_u *UsersUpdate) ClearVerifiedRoles() *UsersUpdate {
_u.mutation.ClearVerifiedRoles()
return _u
}
// Mutation returns the UsersMutation object of the builder.
func (_u *UsersUpdate) Mutation() *UsersMutation {
return _u.mutation
@@ -256,7 +276,20 @@ func (_u *UsersUpdate) ExecX(ctx context.Context) {
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *UsersUpdate) check() error {
if v, ok := _u.mutation.CurrentRole(); ok {
if err := users.CurrentRoleValidator(v); err != nil {
return &ValidationError{Name: "current_role", err: fmt.Errorf(`models: validator failed for field "Users.current_role": %w`, err)}
}
}
return nil
}
func (_u *UsersUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_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) {
@@ -289,17 +322,12 @@ func (_u *UsersUpdate) sqlSave(ctx context.Context) (_node int, err error) {
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 _u.mutation.VerificationStatusCleared() {
_spec.ClearField(users.FieldVerificationStatus, field.TypeJSON)
}
if value, ok := _u.mutation.IsAdmin(); ok {
_spec.SetField(users.FieldIsAdmin, field.TypeBool, value)
}
@@ -312,6 +340,15 @@ func (_u *UsersUpdate) sqlSave(ctx context.Context) (_node int, err error) {
if value, ok := _u.mutation.DeletedAt(); ok {
_spec.SetField(users.FieldDeletedAt, field.TypeTime, value)
}
if _u.mutation.DeletedAtCleared() {
_spec.ClearField(users.FieldDeletedAt, field.TypeTime)
}
if value, ok := _u.mutation.VerifiedRoles(); ok {
_spec.SetField(users.FieldVerifiedRoles, field.TypeOther, value)
}
if _u.mutation.VerifiedRolesCleared() {
_spec.ClearField(users.FieldVerifiedRoles, field.TypeOther)
}
if _node, err = sqlgraph.UpdateNodes(ctx, _u.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{users.Label}
@@ -444,18 +481,6 @@ func (_u *UsersUpdateOne) SetNillableCurrentRole(v *string) *UsersUpdateOne {
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)
@@ -470,6 +495,12 @@ func (_u *UsersUpdateOne) SetNillableVerificationStatus(v *schema.VerificationSt
return _u
}
// ClearVerificationStatus clears the value of the "verificationStatus" field.
func (_u *UsersUpdateOne) ClearVerificationStatus() *UsersUpdateOne {
_u.mutation.ClearVerificationStatus()
return _u
}
// SetIsAdmin sets the "is_admin" field.
func (_u *UsersUpdateOne) SetIsAdmin(v bool) *UsersUpdateOne {
_u.mutation.SetIsAdmin(v)
@@ -526,6 +557,32 @@ func (_u *UsersUpdateOne) SetNillableDeletedAt(v *time.Time) *UsersUpdateOne {
return _u
}
// ClearDeletedAt clears the value of the "deleted_at" field.
func (_u *UsersUpdateOne) ClearDeletedAt() *UsersUpdateOne {
_u.mutation.ClearDeletedAt()
return _u
}
// SetVerifiedRoles sets the "verified_roles" field.
func (_u *UsersUpdateOne) SetVerifiedRoles(v types.TextArray) *UsersUpdateOne {
_u.mutation.SetVerifiedRoles(v)
return _u
}
// SetNillableVerifiedRoles sets the "verified_roles" field if the given value is not nil.
func (_u *UsersUpdateOne) SetNillableVerifiedRoles(v *types.TextArray) *UsersUpdateOne {
if v != nil {
_u.SetVerifiedRoles(*v)
}
return _u
}
// ClearVerifiedRoles clears the value of the "verified_roles" field.
func (_u *UsersUpdateOne) ClearVerifiedRoles() *UsersUpdateOne {
_u.mutation.ClearVerifiedRoles()
return _u
}
// Mutation returns the UsersMutation object of the builder.
func (_u *UsersUpdateOne) Mutation() *UsersMutation {
return _u.mutation
@@ -571,7 +628,20 @@ func (_u *UsersUpdateOne) ExecX(ctx context.Context) {
}
}
// check runs all checks and user-defined validators on the builder.
func (_u *UsersUpdateOne) check() error {
if v, ok := _u.mutation.CurrentRole(); ok {
if err := users.CurrentRoleValidator(v); err != nil {
return &ValidationError{Name: "current_role", err: fmt.Errorf(`models: validator failed for field "Users.current_role": %w`, err)}
}
}
return nil
}
func (_u *UsersUpdateOne) sqlSave(ctx context.Context) (_node *Users, err error) {
if err := _u.check(); err != nil {
return _node, err
}
_spec := sqlgraph.NewUpdateSpec(users.Table, users.Columns, sqlgraph.NewFieldSpec(users.FieldID, field.TypeInt64))
id, ok := _u.mutation.ID()
if !ok {
@@ -621,17 +691,12 @@ func (_u *UsersUpdateOne) sqlSave(ctx context.Context) (_node *Users, err error)
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 _u.mutation.VerificationStatusCleared() {
_spec.ClearField(users.FieldVerificationStatus, field.TypeJSON)
}
if value, ok := _u.mutation.IsAdmin(); ok {
_spec.SetField(users.FieldIsAdmin, field.TypeBool, value)
}
@@ -644,6 +709,15 @@ func (_u *UsersUpdateOne) sqlSave(ctx context.Context) (_node *Users, err error)
if value, ok := _u.mutation.DeletedAt(); ok {
_spec.SetField(users.FieldDeletedAt, field.TypeTime, value)
}
if _u.mutation.DeletedAtCleared() {
_spec.ClearField(users.FieldDeletedAt, field.TypeTime)
}
if value, ok := _u.mutation.VerifiedRoles(); ok {
_spec.SetField(users.FieldVerifiedRoles, field.TypeOther, value)
}
if _u.mutation.VerifiedRolesCleared() {
_spec.ClearField(users.FieldVerifiedRoles, field.TypeOther)
}
_node = &Users{config: _u.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
@@ -44,16 +44,16 @@ func (s *UsercenterServer) GetUsersById(ctx context.Context, in *pb.GetUsersById
return l.GetUsersById(in)
}
func (s *UsercenterServer) GetUserByUsername(ctx context.Context, in *pb.GetUserByUsernameReq) (*pb.GetUserByUsernameResp, error) {
l := logic.NewGetUserByUsernameLogic(ctx, s.svcCtx)
return l.GetUserByUsername(in)
}
func (s *UsercenterServer) SearchUsers(ctx context.Context, in *pb.SearchUsersReq) (*pb.SearchUsersResp, error) {
l := logic.NewSearchUsersLogic(ctx, s.svcCtx)
return l.SearchUsers(in)
}
func (s *UsercenterServer) GetUserByUsername(ctx context.Context, in *pb.GetUserByUsernameReq) (*pb.GetUserByUsernameResp, error) {
l := logic.NewGetUserByUsernameLogic(ctx, s.svcCtx)
return l.GetUserByUsername(in)
}
func (s *UsercenterServer) Login(ctx context.Context, in *pb.LoginReq) (*pb.LoginResp, error) {
l := logic.NewLoginLogic(ctx, s.svcCtx)
return l.Login(in)
@@ -83,3 +83,60 @@ func (s *UsercenterServer) ResetPassword(ctx context.Context, in *pb.ResetPasswo
l := logic.NewResetPasswordLogic(ctx, s.svcCtx)
return l.ResetPassword(in)
}
func (s *UsercenterServer) SwitchRole(ctx context.Context, in *pb.SwitchRoleReq) (*pb.SwitchRoleResp, error) {
l := logic.NewSwitchRoleLogic(ctx, s.svcCtx)
return l.SwitchRole(in)
}
// -----------------------userFollows-----------------------
func (s *UsercenterServer) AddUserFollows(ctx context.Context, in *pb.AddUserFollowsReq) (*pb.AddUserFollowsResp, error) {
l := logic.NewAddUserFollowsLogic(ctx, s.svcCtx)
return l.AddUserFollows(in)
}
func (s *UsercenterServer) UpdateUserFollows(ctx context.Context, in *pb.UpdateUserFollowsReq) (*pb.UpdateUserFollowsResp, error) {
l := logic.NewUpdateUserFollowsLogic(ctx, s.svcCtx)
return l.UpdateUserFollows(in)
}
func (s *UsercenterServer) DelUserFollows(ctx context.Context, in *pb.DelUserFollowsReq) (*pb.DelUserFollowsResp, error) {
l := logic.NewDelUserFollowsLogic(ctx, s.svcCtx)
return l.DelUserFollows(in)
}
func (s *UsercenterServer) GetUserFollowsById(ctx context.Context, in *pb.GetUserFollowsByIdReq) (*pb.GetUserFollowsByIdResp, error) {
l := logic.NewGetUserFollowsByIdLogic(ctx, s.svcCtx)
return l.GetUserFollowsById(in)
}
func (s *UsercenterServer) SearchUserFollows(ctx context.Context, in *pb.SearchUserFollowsReq) (*pb.SearchUserFollowsResp, error) {
l := logic.NewSearchUserFollowsLogic(ctx, s.svcCtx)
return l.SearchUserFollows(in)
}
// -----------------------userPreferences-----------------------
func (s *UsercenterServer) AddUserPreferences(ctx context.Context, in *pb.AddUserPreferencesReq) (*pb.AddUserPreferencesResp, error) {
l := logic.NewAddUserPreferencesLogic(ctx, s.svcCtx)
return l.AddUserPreferences(in)
}
func (s *UsercenterServer) UpdateUserPreferences(ctx context.Context, in *pb.UpdateUserPreferencesReq) (*pb.UpdateUserPreferencesResp, error) {
l := logic.NewUpdateUserPreferencesLogic(ctx, s.svcCtx)
return l.UpdateUserPreferences(in)
}
func (s *UsercenterServer) DelUserPreferences(ctx context.Context, in *pb.DelUserPreferencesReq) (*pb.DelUserPreferencesResp, error) {
l := logic.NewDelUserPreferencesLogic(ctx, s.svcCtx)
return l.DelUserPreferences(in)
}
func (s *UsercenterServer) GetUserPreferencesById(ctx context.Context, in *pb.GetUserPreferencesByIdReq) (*pb.GetUserPreferencesByIdResp, error) {
l := logic.NewGetUserPreferencesByIdLogic(ctx, s.svcCtx)
return l.GetUserPreferencesById(in)
}
func (s *UsercenterServer) SearchUserPreferences(ctx context.Context, in *pb.SearchUserPreferencesReq) (*pb.SearchUserPreferencesResp, error) {
l := logic.NewSearchUserPreferencesLogic(ctx, s.svcCtx)
return l.SearchUserPreferences(in)
}
+17 -12
View File
@@ -1,6 +1,7 @@
package svc
import (
stdsql "database/sql"
"juwan-backend/app/snowflake/rpc/snowflake"
"juwan-backend/app/users/rpc/internal/config"
"juwan-backend/app/users/rpc/internal/models"
@@ -11,30 +12,34 @@ import (
"time"
"ariga.io/entcache"
"entgo.io/ent/dialect"
"entgo.io/ent/dialect/sql"
_ "github.com/jackc/pgx/v5/stdlib"
"github.com/redis/go-redis/v9"
"github.com/zeromicro/go-zero/core/logx"
)
type ServiceContext struct {
Config config.Config
UsersModelRW *models.UsersClient
UsersModelRO *models.UsersClient
UsersModelRW *models.Client
UsersModelRO *models.Client
RedisCluster *redis.ClusterClient
Snowflake snowflake.SnowflakeServiceClient
JwtManager *utils.JwtManager
}
func NewServiceContext(c config.Config) *ServiceContext {
rawRW, err := stdsql.Open("pgx", c.DB.Master)
if err != nil {
panic(err)
}
rawRO, err := stdsql.Open("pgx", c.DB.Slave)
if err != nil {
panic(err)
}
RWConn := sql.OpenDB(dialect.Postgres, rawRW)
ROConn := sql.OpenDB(dialect.Postgres, rawRO)
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
@@ -59,8 +64,8 @@ func NewServiceContext(c config.Config) *ServiceContext {
RWDrv := entcache.NewDriver(RWConn, entcache.TTL(time.Second*30), entcache.Levels(adapter.NewRedisCache(redisCluster)))
return &ServiceContext{
Config: c,
UsersModelRW: models.NewClient(models.Driver(RWDrv)).Users,
UsersModelRO: models.NewClient(models.Driver(RODrv)).Users,
UsersModelRW: models.NewClient(models.Driver(RWDrv)),
UsersModelRO: models.NewClient(models.Driver(RODrv)),
RedisCluster: redisCluster,
JwtManager: jwtManager,
Snowflake: snowflakex.NewClient(c.SnowflakeRpcConf),
File diff suppressed because it is too large Load Diff
+467 -45
View File
@@ -19,18 +19,29 @@ import (
const _ = grpc.SupportPackageIsVersion9
const (
Usercenter_AddUsers_FullMethodName = "/pb.usercenter/AddUsers"
Usercenter_UpdateUsers_FullMethodName = "/pb.usercenter/UpdateUsers"
Usercenter_DelUsers_FullMethodName = "/pb.usercenter/DelUsers"
Usercenter_GetUsersById_FullMethodName = "/pb.usercenter/GetUsersById"
Usercenter_GetUserByUsername_FullMethodName = "/pb.usercenter/GetUserByUsername"
Usercenter_SearchUsers_FullMethodName = "/pb.usercenter/SearchUsers"
Usercenter_Login_FullMethodName = "/pb.usercenter/Login"
Usercenter_Register_FullMethodName = "/pb.usercenter/Register"
Usercenter_ValidateToken_FullMethodName = "/pb.usercenter/ValidateToken"
Usercenter_CheckPermission_FullMethodName = "/pb.usercenter/CheckPermission"
Usercenter_Logout_FullMethodName = "/pb.usercenter/Logout"
Usercenter_ResetPassword_FullMethodName = "/pb.usercenter/ResetPassword"
Usercenter_AddUsers_FullMethodName = "/pb.usercenter/AddUsers"
Usercenter_UpdateUsers_FullMethodName = "/pb.usercenter/UpdateUsers"
Usercenter_DelUsers_FullMethodName = "/pb.usercenter/DelUsers"
Usercenter_GetUsersById_FullMethodName = "/pb.usercenter/GetUsersById"
Usercenter_SearchUsers_FullMethodName = "/pb.usercenter/SearchUsers"
Usercenter_GetUserByUsername_FullMethodName = "/pb.usercenter/GetUserByUsername"
Usercenter_Login_FullMethodName = "/pb.usercenter/Login"
Usercenter_Register_FullMethodName = "/pb.usercenter/Register"
Usercenter_ValidateToken_FullMethodName = "/pb.usercenter/ValidateToken"
Usercenter_CheckPermission_FullMethodName = "/pb.usercenter/CheckPermission"
Usercenter_Logout_FullMethodName = "/pb.usercenter/Logout"
Usercenter_ResetPassword_FullMethodName = "/pb.usercenter/ResetPassword"
Usercenter_SwitchRole_FullMethodName = "/pb.usercenter/SwitchRole"
Usercenter_AddUserFollows_FullMethodName = "/pb.usercenter/AddUserFollows"
Usercenter_UpdateUserFollows_FullMethodName = "/pb.usercenter/UpdateUserFollows"
Usercenter_DelUserFollows_FullMethodName = "/pb.usercenter/DelUserFollows"
Usercenter_GetUserFollowsById_FullMethodName = "/pb.usercenter/GetUserFollowsById"
Usercenter_SearchUserFollows_FullMethodName = "/pb.usercenter/SearchUserFollows"
Usercenter_AddUserPreferences_FullMethodName = "/pb.usercenter/AddUserPreferences"
Usercenter_UpdateUserPreferences_FullMethodName = "/pb.usercenter/UpdateUserPreferences"
Usercenter_DelUserPreferences_FullMethodName = "/pb.usercenter/DelUserPreferences"
Usercenter_GetUserPreferencesById_FullMethodName = "/pb.usercenter/GetUserPreferencesById"
Usercenter_SearchUserPreferences_FullMethodName = "/pb.usercenter/SearchUserPreferences"
)
// UsercenterClient is the client API for Usercenter service.
@@ -42,14 +53,27 @@ type UsercenterClient interface {
UpdateUsers(ctx context.Context, in *UpdateUsersReq, opts ...grpc.CallOption) (*UpdateUsersResp, error)
DelUsers(ctx context.Context, in *DelUsersReq, opts ...grpc.CallOption) (*DelUsersResp, error)
GetUsersById(ctx context.Context, in *GetUsersByIdReq, opts ...grpc.CallOption) (*GetUsersByIdResp, error)
GetUserByUsername(ctx context.Context, in *GetUserByUsernameReq, opts ...grpc.CallOption) (*GetUserByUsernameResp, error)
SearchUsers(ctx context.Context, in *SearchUsersReq, opts ...grpc.CallOption) (*SearchUsersResp, error)
GetUserByUsername(ctx context.Context, in *GetUserByUsernameReq, opts ...grpc.CallOption) (*GetUserByUsernameResp, error)
Login(ctx context.Context, in *LoginReq, opts ...grpc.CallOption) (*LoginResp, error)
Register(ctx context.Context, in *RegisterReq, opts ...grpc.CallOption) (*RegisterResp, error)
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)
SwitchRole(ctx context.Context, in *SwitchRoleReq, opts ...grpc.CallOption) (*SwitchRoleResp, error)
// -----------------------userFollows-----------------------
AddUserFollows(ctx context.Context, in *AddUserFollowsReq, opts ...grpc.CallOption) (*AddUserFollowsResp, error)
UpdateUserFollows(ctx context.Context, in *UpdateUserFollowsReq, opts ...grpc.CallOption) (*UpdateUserFollowsResp, error)
DelUserFollows(ctx context.Context, in *DelUserFollowsReq, opts ...grpc.CallOption) (*DelUserFollowsResp, error)
GetUserFollowsById(ctx context.Context, in *GetUserFollowsByIdReq, opts ...grpc.CallOption) (*GetUserFollowsByIdResp, error)
SearchUserFollows(ctx context.Context, in *SearchUserFollowsReq, opts ...grpc.CallOption) (*SearchUserFollowsResp, error)
// -----------------------userPreferences-----------------------
AddUserPreferences(ctx context.Context, in *AddUserPreferencesReq, opts ...grpc.CallOption) (*AddUserPreferencesResp, error)
UpdateUserPreferences(ctx context.Context, in *UpdateUserPreferencesReq, opts ...grpc.CallOption) (*UpdateUserPreferencesResp, error)
DelUserPreferences(ctx context.Context, in *DelUserPreferencesReq, opts ...grpc.CallOption) (*DelUserPreferencesResp, error)
GetUserPreferencesById(ctx context.Context, in *GetUserPreferencesByIdReq, opts ...grpc.CallOption) (*GetUserPreferencesByIdResp, error)
SearchUserPreferences(ctx context.Context, in *SearchUserPreferencesReq, opts ...grpc.CallOption) (*SearchUserPreferencesResp, error)
}
type usercenterClient struct {
@@ -100,20 +124,20 @@ func (c *usercenterClient) GetUsersById(ctx context.Context, in *GetUsersByIdReq
return out, nil
}
func (c *usercenterClient) GetUserByUsername(ctx context.Context, in *GetUserByUsernameReq, opts ...grpc.CallOption) (*GetUserByUsernameResp, error) {
func (c *usercenterClient) SearchUsers(ctx context.Context, in *SearchUsersReq, opts ...grpc.CallOption) (*SearchUsersResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetUserByUsernameResp)
err := c.cc.Invoke(ctx, Usercenter_GetUserByUsername_FullMethodName, in, out, cOpts...)
out := new(SearchUsersResp)
err := c.cc.Invoke(ctx, Usercenter_SearchUsers_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *usercenterClient) SearchUsers(ctx context.Context, in *SearchUsersReq, opts ...grpc.CallOption) (*SearchUsersResp, error) {
func (c *usercenterClient) GetUserByUsername(ctx context.Context, in *GetUserByUsernameReq, opts ...grpc.CallOption) (*GetUserByUsernameResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SearchUsersResp)
err := c.cc.Invoke(ctx, Usercenter_SearchUsers_FullMethodName, in, out, cOpts...)
out := new(GetUserByUsernameResp)
err := c.cc.Invoke(ctx, Usercenter_GetUserByUsername_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
@@ -180,6 +204,116 @@ func (c *usercenterClient) ResetPassword(ctx context.Context, in *ResetPasswordR
return out, nil
}
func (c *usercenterClient) SwitchRole(ctx context.Context, in *SwitchRoleReq, opts ...grpc.CallOption) (*SwitchRoleResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SwitchRoleResp)
err := c.cc.Invoke(ctx, Usercenter_SwitchRole_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *usercenterClient) AddUserFollows(ctx context.Context, in *AddUserFollowsReq, opts ...grpc.CallOption) (*AddUserFollowsResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(AddUserFollowsResp)
err := c.cc.Invoke(ctx, Usercenter_AddUserFollows_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *usercenterClient) UpdateUserFollows(ctx context.Context, in *UpdateUserFollowsReq, opts ...grpc.CallOption) (*UpdateUserFollowsResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(UpdateUserFollowsResp)
err := c.cc.Invoke(ctx, Usercenter_UpdateUserFollows_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *usercenterClient) DelUserFollows(ctx context.Context, in *DelUserFollowsReq, opts ...grpc.CallOption) (*DelUserFollowsResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(DelUserFollowsResp)
err := c.cc.Invoke(ctx, Usercenter_DelUserFollows_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *usercenterClient) GetUserFollowsById(ctx context.Context, in *GetUserFollowsByIdReq, opts ...grpc.CallOption) (*GetUserFollowsByIdResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetUserFollowsByIdResp)
err := c.cc.Invoke(ctx, Usercenter_GetUserFollowsById_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *usercenterClient) SearchUserFollows(ctx context.Context, in *SearchUserFollowsReq, opts ...grpc.CallOption) (*SearchUserFollowsResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SearchUserFollowsResp)
err := c.cc.Invoke(ctx, Usercenter_SearchUserFollows_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *usercenterClient) AddUserPreferences(ctx context.Context, in *AddUserPreferencesReq, opts ...grpc.CallOption) (*AddUserPreferencesResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(AddUserPreferencesResp)
err := c.cc.Invoke(ctx, Usercenter_AddUserPreferences_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *usercenterClient) UpdateUserPreferences(ctx context.Context, in *UpdateUserPreferencesReq, opts ...grpc.CallOption) (*UpdateUserPreferencesResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(UpdateUserPreferencesResp)
err := c.cc.Invoke(ctx, Usercenter_UpdateUserPreferences_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *usercenterClient) DelUserPreferences(ctx context.Context, in *DelUserPreferencesReq, opts ...grpc.CallOption) (*DelUserPreferencesResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(DelUserPreferencesResp)
err := c.cc.Invoke(ctx, Usercenter_DelUserPreferences_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *usercenterClient) GetUserPreferencesById(ctx context.Context, in *GetUserPreferencesByIdReq, opts ...grpc.CallOption) (*GetUserPreferencesByIdResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(GetUserPreferencesByIdResp)
err := c.cc.Invoke(ctx, Usercenter_GetUserPreferencesById_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *usercenterClient) SearchUserPreferences(ctx context.Context, in *SearchUserPreferencesReq, opts ...grpc.CallOption) (*SearchUserPreferencesResp, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(SearchUserPreferencesResp)
err := c.cc.Invoke(ctx, Usercenter_SearchUserPreferences_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.
@@ -189,14 +323,27 @@ type UsercenterServer interface {
UpdateUsers(context.Context, *UpdateUsersReq) (*UpdateUsersResp, error)
DelUsers(context.Context, *DelUsersReq) (*DelUsersResp, error)
GetUsersById(context.Context, *GetUsersByIdReq) (*GetUsersByIdResp, error)
GetUserByUsername(context.Context, *GetUserByUsernameReq) (*GetUserByUsernameResp, error)
SearchUsers(context.Context, *SearchUsersReq) (*SearchUsersResp, error)
GetUserByUsername(context.Context, *GetUserByUsernameReq) (*GetUserByUsernameResp, error)
Login(context.Context, *LoginReq) (*LoginResp, error)
Register(context.Context, *RegisterReq) (*RegisterResp, error)
ValidateToken(context.Context, *ValidateTokenReq) (*ValidateTokenResp, error)
CheckPermission(context.Context, *CheckPermissionReq) (*CheckPermissionResp, error)
Logout(context.Context, *LogoutReq) (*LogoutResp, error)
ResetPassword(context.Context, *ResetPasswordReq) (*ResetPasswordResp, error)
SwitchRole(context.Context, *SwitchRoleReq) (*SwitchRoleResp, error)
// -----------------------userFollows-----------------------
AddUserFollows(context.Context, *AddUserFollowsReq) (*AddUserFollowsResp, error)
UpdateUserFollows(context.Context, *UpdateUserFollowsReq) (*UpdateUserFollowsResp, error)
DelUserFollows(context.Context, *DelUserFollowsReq) (*DelUserFollowsResp, error)
GetUserFollowsById(context.Context, *GetUserFollowsByIdReq) (*GetUserFollowsByIdResp, error)
SearchUserFollows(context.Context, *SearchUserFollowsReq) (*SearchUserFollowsResp, error)
// -----------------------userPreferences-----------------------
AddUserPreferences(context.Context, *AddUserPreferencesReq) (*AddUserPreferencesResp, error)
UpdateUserPreferences(context.Context, *UpdateUserPreferencesReq) (*UpdateUserPreferencesResp, error)
DelUserPreferences(context.Context, *DelUserPreferencesReq) (*DelUserPreferencesResp, error)
GetUserPreferencesById(context.Context, *GetUserPreferencesByIdReq) (*GetUserPreferencesByIdResp, error)
SearchUserPreferences(context.Context, *SearchUserPreferencesReq) (*SearchUserPreferencesResp, error)
mustEmbedUnimplementedUsercenterServer()
}
@@ -219,12 +366,12 @@ func (UnimplementedUsercenterServer) DelUsers(context.Context, *DelUsersReq) (*D
func (UnimplementedUsercenterServer) GetUsersById(context.Context, *GetUsersByIdReq) (*GetUsersByIdResp, error) {
return nil, status.Error(codes.Unimplemented, "method GetUsersById not implemented")
}
func (UnimplementedUsercenterServer) GetUserByUsername(context.Context, *GetUserByUsernameReq) (*GetUserByUsernameResp, error) {
return nil, status.Error(codes.Unimplemented, "method GetUserByUsername not implemented")
}
func (UnimplementedUsercenterServer) SearchUsers(context.Context, *SearchUsersReq) (*SearchUsersResp, error) {
return nil, status.Error(codes.Unimplemented, "method SearchUsers not implemented")
}
func (UnimplementedUsercenterServer) GetUserByUsername(context.Context, *GetUserByUsernameReq) (*GetUserByUsernameResp, error) {
return nil, status.Error(codes.Unimplemented, "method GetUserByUsername not implemented")
}
func (UnimplementedUsercenterServer) Login(context.Context, *LoginReq) (*LoginResp, error) {
return nil, status.Error(codes.Unimplemented, "method Login not implemented")
}
@@ -243,6 +390,39 @@ func (UnimplementedUsercenterServer) Logout(context.Context, *LogoutReq) (*Logou
func (UnimplementedUsercenterServer) ResetPassword(context.Context, *ResetPasswordReq) (*ResetPasswordResp, error) {
return nil, status.Error(codes.Unimplemented, "method ResetPassword not implemented")
}
func (UnimplementedUsercenterServer) SwitchRole(context.Context, *SwitchRoleReq) (*SwitchRoleResp, error) {
return nil, status.Error(codes.Unimplemented, "method SwitchRole not implemented")
}
func (UnimplementedUsercenterServer) AddUserFollows(context.Context, *AddUserFollowsReq) (*AddUserFollowsResp, error) {
return nil, status.Error(codes.Unimplemented, "method AddUserFollows not implemented")
}
func (UnimplementedUsercenterServer) UpdateUserFollows(context.Context, *UpdateUserFollowsReq) (*UpdateUserFollowsResp, error) {
return nil, status.Error(codes.Unimplemented, "method UpdateUserFollows not implemented")
}
func (UnimplementedUsercenterServer) DelUserFollows(context.Context, *DelUserFollowsReq) (*DelUserFollowsResp, error) {
return nil, status.Error(codes.Unimplemented, "method DelUserFollows not implemented")
}
func (UnimplementedUsercenterServer) GetUserFollowsById(context.Context, *GetUserFollowsByIdReq) (*GetUserFollowsByIdResp, error) {
return nil, status.Error(codes.Unimplemented, "method GetUserFollowsById not implemented")
}
func (UnimplementedUsercenterServer) SearchUserFollows(context.Context, *SearchUserFollowsReq) (*SearchUserFollowsResp, error) {
return nil, status.Error(codes.Unimplemented, "method SearchUserFollows not implemented")
}
func (UnimplementedUsercenterServer) AddUserPreferences(context.Context, *AddUserPreferencesReq) (*AddUserPreferencesResp, error) {
return nil, status.Error(codes.Unimplemented, "method AddUserPreferences not implemented")
}
func (UnimplementedUsercenterServer) UpdateUserPreferences(context.Context, *UpdateUserPreferencesReq) (*UpdateUserPreferencesResp, error) {
return nil, status.Error(codes.Unimplemented, "method UpdateUserPreferences not implemented")
}
func (UnimplementedUsercenterServer) DelUserPreferences(context.Context, *DelUserPreferencesReq) (*DelUserPreferencesResp, error) {
return nil, status.Error(codes.Unimplemented, "method DelUserPreferences not implemented")
}
func (UnimplementedUsercenterServer) GetUserPreferencesById(context.Context, *GetUserPreferencesByIdReq) (*GetUserPreferencesByIdResp, error) {
return nil, status.Error(codes.Unimplemented, "method GetUserPreferencesById not implemented")
}
func (UnimplementedUsercenterServer) SearchUserPreferences(context.Context, *SearchUserPreferencesReq) (*SearchUserPreferencesResp, error) {
return nil, status.Error(codes.Unimplemented, "method SearchUserPreferences not implemented")
}
func (UnimplementedUsercenterServer) mustEmbedUnimplementedUsercenterServer() {}
func (UnimplementedUsercenterServer) testEmbeddedByValue() {}
@@ -336,24 +516,6 @@ func _Usercenter_GetUsersById_Handler(srv interface{}, ctx context.Context, dec
return interceptor(ctx, in, info, handler)
}
func _Usercenter_GetUserByUsername_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetUserByUsernameReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UsercenterServer).GetUserByUsername(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Usercenter_GetUserByUsername_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UsercenterServer).GetUserByUsername(ctx, req.(*GetUserByUsernameReq))
}
return interceptor(ctx, in, info, handler)
}
func _Usercenter_SearchUsers_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SearchUsersReq)
if err := dec(in); err != nil {
@@ -372,6 +534,24 @@ func _Usercenter_SearchUsers_Handler(srv interface{}, ctx context.Context, dec f
return interceptor(ctx, in, info, handler)
}
func _Usercenter_GetUserByUsername_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetUserByUsernameReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UsercenterServer).GetUserByUsername(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Usercenter_GetUserByUsername_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UsercenterServer).GetUserByUsername(ctx, req.(*GetUserByUsernameReq))
}
return interceptor(ctx, in, info, handler)
}
func _Usercenter_Login_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(LoginReq)
if err := dec(in); err != nil {
@@ -480,6 +660,204 @@ func _Usercenter_ResetPassword_Handler(srv interface{}, ctx context.Context, dec
return interceptor(ctx, in, info, handler)
}
func _Usercenter_SwitchRole_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SwitchRoleReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UsercenterServer).SwitchRole(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Usercenter_SwitchRole_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UsercenterServer).SwitchRole(ctx, req.(*SwitchRoleReq))
}
return interceptor(ctx, in, info, handler)
}
func _Usercenter_AddUserFollows_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(AddUserFollowsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UsercenterServer).AddUserFollows(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Usercenter_AddUserFollows_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UsercenterServer).AddUserFollows(ctx, req.(*AddUserFollowsReq))
}
return interceptor(ctx, in, info, handler)
}
func _Usercenter_UpdateUserFollows_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UpdateUserFollowsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UsercenterServer).UpdateUserFollows(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Usercenter_UpdateUserFollows_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UsercenterServer).UpdateUserFollows(ctx, req.(*UpdateUserFollowsReq))
}
return interceptor(ctx, in, info, handler)
}
func _Usercenter_DelUserFollows_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(DelUserFollowsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UsercenterServer).DelUserFollows(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Usercenter_DelUserFollows_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UsercenterServer).DelUserFollows(ctx, req.(*DelUserFollowsReq))
}
return interceptor(ctx, in, info, handler)
}
func _Usercenter_GetUserFollowsById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetUserFollowsByIdReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UsercenterServer).GetUserFollowsById(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Usercenter_GetUserFollowsById_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UsercenterServer).GetUserFollowsById(ctx, req.(*GetUserFollowsByIdReq))
}
return interceptor(ctx, in, info, handler)
}
func _Usercenter_SearchUserFollows_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SearchUserFollowsReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UsercenterServer).SearchUserFollows(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Usercenter_SearchUserFollows_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UsercenterServer).SearchUserFollows(ctx, req.(*SearchUserFollowsReq))
}
return interceptor(ctx, in, info, handler)
}
func _Usercenter_AddUserPreferences_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(AddUserPreferencesReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UsercenterServer).AddUserPreferences(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Usercenter_AddUserPreferences_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UsercenterServer).AddUserPreferences(ctx, req.(*AddUserPreferencesReq))
}
return interceptor(ctx, in, info, handler)
}
func _Usercenter_UpdateUserPreferences_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UpdateUserPreferencesReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UsercenterServer).UpdateUserPreferences(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Usercenter_UpdateUserPreferences_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UsercenterServer).UpdateUserPreferences(ctx, req.(*UpdateUserPreferencesReq))
}
return interceptor(ctx, in, info, handler)
}
func _Usercenter_DelUserPreferences_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(DelUserPreferencesReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UsercenterServer).DelUserPreferences(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Usercenter_DelUserPreferences_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UsercenterServer).DelUserPreferences(ctx, req.(*DelUserPreferencesReq))
}
return interceptor(ctx, in, info, handler)
}
func _Usercenter_GetUserPreferencesById_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetUserPreferencesByIdReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UsercenterServer).GetUserPreferencesById(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Usercenter_GetUserPreferencesById_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UsercenterServer).GetUserPreferencesById(ctx, req.(*GetUserPreferencesByIdReq))
}
return interceptor(ctx, in, info, handler)
}
func _Usercenter_SearchUserPreferences_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(SearchUserPreferencesReq)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(UsercenterServer).SearchUserPreferences(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Usercenter_SearchUserPreferences_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(UsercenterServer).SearchUserPreferences(ctx, req.(*SearchUserPreferencesReq))
}
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)
@@ -503,14 +881,14 @@ var Usercenter_ServiceDesc = grpc.ServiceDesc{
MethodName: "GetUsersById",
Handler: _Usercenter_GetUsersById_Handler,
},
{
MethodName: "GetUserByUsername",
Handler: _Usercenter_GetUserByUsername_Handler,
},
{
MethodName: "SearchUsers",
Handler: _Usercenter_SearchUsers_Handler,
},
{
MethodName: "GetUserByUsername",
Handler: _Usercenter_GetUserByUsername_Handler,
},
{
MethodName: "Login",
Handler: _Usercenter_Login_Handler,
@@ -535,6 +913,50 @@ var Usercenter_ServiceDesc = grpc.ServiceDesc{
MethodName: "ResetPassword",
Handler: _Usercenter_ResetPassword_Handler,
},
{
MethodName: "SwitchRole",
Handler: _Usercenter_SwitchRole_Handler,
},
{
MethodName: "AddUserFollows",
Handler: _Usercenter_AddUserFollows_Handler,
},
{
MethodName: "UpdateUserFollows",
Handler: _Usercenter_UpdateUserFollows_Handler,
},
{
MethodName: "DelUserFollows",
Handler: _Usercenter_DelUserFollows_Handler,
},
{
MethodName: "GetUserFollowsById",
Handler: _Usercenter_GetUserFollowsById_Handler,
},
{
MethodName: "SearchUserFollows",
Handler: _Usercenter_SearchUserFollows_Handler,
},
{
MethodName: "AddUserPreferences",
Handler: _Usercenter_AddUserPreferences_Handler,
},
{
MethodName: "UpdateUserPreferences",
Handler: _Usercenter_UpdateUserPreferences_Handler,
},
{
MethodName: "DelUserPreferences",
Handler: _Usercenter_DelUserPreferences_Handler,
},
{
MethodName: "GetUserPreferencesById",
Handler: _Usercenter_GetUserPreferencesById_Handler,
},
{
MethodName: "SearchUserPreferences",
Handler: _Usercenter_SearchUserPreferences_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "users.proto",
+125 -31
View File
@@ -14,31 +14,55 @@ import (
)
type (
AddUsersReq = pb.AddUsersReq
AddUsersResp = pb.AddUsersResp
CheckPermissionReq = pb.CheckPermissionReq
CheckPermissionResp = pb.CheckPermissionResp
DelUsersReq = pb.DelUsersReq
DelUsersResp = pb.DelUsersResp
GetUserByUsernameReq = pb.GetUserByUsernameReq
GetUserByUsernameResp = pb.GetUserByUsernameResp
GetUsersByIdReq = pb.GetUsersByIdReq
GetUsersByIdResp = pb.GetUsersByIdResp
LoginReq = pb.LoginReq
LoginResp = pb.LoginResp
LogoutReq = pb.LogoutReq
LogoutResp = pb.LogoutResp
RegisterReq = pb.RegisterReq
RegisterResp = pb.RegisterResp
ResetPasswordReq = pb.ResetPasswordReq
ResetPasswordResp = pb.ResetPasswordResp
SearchUsersReq = pb.SearchUsersReq
SearchUsersResp = pb.SearchUsersResp
UpdateUsersReq = pb.UpdateUsersReq
UpdateUsersResp = pb.UpdateUsersResp
Users = pb.Users
ValidateTokenReq = pb.ValidateTokenReq
ValidateTokenResp = pb.ValidateTokenResp
AddUserFollowsReq = pb.AddUserFollowsReq
AddUserFollowsResp = pb.AddUserFollowsResp
AddUserPreferencesReq = pb.AddUserPreferencesReq
AddUserPreferencesResp = pb.AddUserPreferencesResp
AddUsersReq = pb.AddUsersReq
AddUsersResp = pb.AddUsersResp
CheckPermissionReq = pb.CheckPermissionReq
CheckPermissionResp = pb.CheckPermissionResp
DelUserFollowsReq = pb.DelUserFollowsReq
DelUserFollowsResp = pb.DelUserFollowsResp
DelUserPreferencesReq = pb.DelUserPreferencesReq
DelUserPreferencesResp = pb.DelUserPreferencesResp
DelUsersReq = pb.DelUsersReq
DelUsersResp = pb.DelUsersResp
GetUserByUsernameReq = pb.GetUserByUsernameReq
GetUserByUsernameResp = pb.GetUserByUsernameResp
GetUserFollowsByIdReq = pb.GetUserFollowsByIdReq
GetUserFollowsByIdResp = pb.GetUserFollowsByIdResp
GetUserPreferencesByIdReq = pb.GetUserPreferencesByIdReq
GetUserPreferencesByIdResp = pb.GetUserPreferencesByIdResp
GetUsersByIdReq = pb.GetUsersByIdReq
GetUsersByIdResp = pb.GetUsersByIdResp
LoginReq = pb.LoginReq
LoginResp = pb.LoginResp
LogoutReq = pb.LogoutReq
LogoutResp = pb.LogoutResp
RegisterReq = pb.RegisterReq
RegisterResp = pb.RegisterResp
ResetPasswordReq = pb.ResetPasswordReq
ResetPasswordResp = pb.ResetPasswordResp
SearchUserFollowsReq = pb.SearchUserFollowsReq
SearchUserFollowsResp = pb.SearchUserFollowsResp
SearchUserPreferencesReq = pb.SearchUserPreferencesReq
SearchUserPreferencesResp = pb.SearchUserPreferencesResp
SearchUsersReq = pb.SearchUsersReq
SearchUsersResp = pb.SearchUsersResp
SwitchRoleReq = pb.SwitchRoleReq
SwitchRoleResp = pb.SwitchRoleResp
UpdateUserFollowsReq = pb.UpdateUserFollowsReq
UpdateUserFollowsResp = pb.UpdateUserFollowsResp
UpdateUserPreferencesReq = pb.UpdateUserPreferencesReq
UpdateUserPreferencesResp = pb.UpdateUserPreferencesResp
UpdateUsersReq = pb.UpdateUsersReq
UpdateUsersResp = pb.UpdateUsersResp
UserFollows = pb.UserFollows
UserPreferences = pb.UserPreferences
Users = pb.Users
ValidateTokenReq = pb.ValidateTokenReq
ValidateTokenResp = pb.ValidateTokenResp
Usercenter interface {
// -----------------------users-----------------------
@@ -46,14 +70,27 @@ type (
UpdateUsers(ctx context.Context, in *UpdateUsersReq, opts ...grpc.CallOption) (*UpdateUsersResp, error)
DelUsers(ctx context.Context, in *DelUsersReq, opts ...grpc.CallOption) (*DelUsersResp, error)
GetUsersById(ctx context.Context, in *GetUsersByIdReq, opts ...grpc.CallOption) (*GetUsersByIdResp, error)
GetUserByUsername(ctx context.Context, in *GetUserByUsernameReq, opts ...grpc.CallOption) (*GetUserByUsernameResp, error)
SearchUsers(ctx context.Context, in *SearchUsersReq, opts ...grpc.CallOption) (*SearchUsersResp, error)
GetUserByUsername(ctx context.Context, in *GetUserByUsernameReq, opts ...grpc.CallOption) (*GetUserByUsernameResp, error)
Login(ctx context.Context, in *LoginReq, opts ...grpc.CallOption) (*LoginResp, error)
Register(ctx context.Context, in *RegisterReq, opts ...grpc.CallOption) (*RegisterResp, error)
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)
SwitchRole(ctx context.Context, in *SwitchRoleReq, opts ...grpc.CallOption) (*SwitchRoleResp, error)
// -----------------------userFollows-----------------------
AddUserFollows(ctx context.Context, in *AddUserFollowsReq, opts ...grpc.CallOption) (*AddUserFollowsResp, error)
UpdateUserFollows(ctx context.Context, in *UpdateUserFollowsReq, opts ...grpc.CallOption) (*UpdateUserFollowsResp, error)
DelUserFollows(ctx context.Context, in *DelUserFollowsReq, opts ...grpc.CallOption) (*DelUserFollowsResp, error)
GetUserFollowsById(ctx context.Context, in *GetUserFollowsByIdReq, opts ...grpc.CallOption) (*GetUserFollowsByIdResp, error)
SearchUserFollows(ctx context.Context, in *SearchUserFollowsReq, opts ...grpc.CallOption) (*SearchUserFollowsResp, error)
// -----------------------userPreferences-----------------------
AddUserPreferences(ctx context.Context, in *AddUserPreferencesReq, opts ...grpc.CallOption) (*AddUserPreferencesResp, error)
UpdateUserPreferences(ctx context.Context, in *UpdateUserPreferencesReq, opts ...grpc.CallOption) (*UpdateUserPreferencesResp, error)
DelUserPreferences(ctx context.Context, in *DelUserPreferencesReq, opts ...grpc.CallOption) (*DelUserPreferencesResp, error)
GetUserPreferencesById(ctx context.Context, in *GetUserPreferencesByIdReq, opts ...grpc.CallOption) (*GetUserPreferencesByIdResp, error)
SearchUserPreferences(ctx context.Context, in *SearchUserPreferencesReq, opts ...grpc.CallOption) (*SearchUserPreferencesResp, error)
}
defaultUsercenter struct {
@@ -88,16 +125,16 @@ func (m *defaultUsercenter) GetUsersById(ctx context.Context, in *GetUsersByIdRe
return client.GetUsersById(ctx, in, opts...)
}
func (m *defaultUsercenter) GetUserByUsername(ctx context.Context, in *GetUserByUsernameReq, opts ...grpc.CallOption) (*GetUserByUsernameResp, error) {
client := pb.NewUsercenterClient(m.cli.Conn())
return client.GetUserByUsername(ctx, in, opts...)
}
func (m *defaultUsercenter) SearchUsers(ctx context.Context, in *SearchUsersReq, opts ...grpc.CallOption) (*SearchUsersResp, error) {
client := pb.NewUsercenterClient(m.cli.Conn())
return client.SearchUsers(ctx, in, opts...)
}
func (m *defaultUsercenter) GetUserByUsername(ctx context.Context, in *GetUserByUsernameReq, opts ...grpc.CallOption) (*GetUserByUsernameResp, error) {
client := pb.NewUsercenterClient(m.cli.Conn())
return client.GetUserByUsername(ctx, in, opts...)
}
func (m *defaultUsercenter) Login(ctx context.Context, in *LoginReq, opts ...grpc.CallOption) (*LoginResp, error) {
client := pb.NewUsercenterClient(m.cli.Conn())
return client.Login(ctx, in, opts...)
@@ -127,3 +164,60 @@ func (m *defaultUsercenter) ResetPassword(ctx context.Context, in *ResetPassword
client := pb.NewUsercenterClient(m.cli.Conn())
return client.ResetPassword(ctx, in, opts...)
}
func (m *defaultUsercenter) SwitchRole(ctx context.Context, in *SwitchRoleReq, opts ...grpc.CallOption) (*SwitchRoleResp, error) {
client := pb.NewUsercenterClient(m.cli.Conn())
return client.SwitchRole(ctx, in, opts...)
}
// -----------------------userFollows-----------------------
func (m *defaultUsercenter) AddUserFollows(ctx context.Context, in *AddUserFollowsReq, opts ...grpc.CallOption) (*AddUserFollowsResp, error) {
client := pb.NewUsercenterClient(m.cli.Conn())
return client.AddUserFollows(ctx, in, opts...)
}
func (m *defaultUsercenter) UpdateUserFollows(ctx context.Context, in *UpdateUserFollowsReq, opts ...grpc.CallOption) (*UpdateUserFollowsResp, error) {
client := pb.NewUsercenterClient(m.cli.Conn())
return client.UpdateUserFollows(ctx, in, opts...)
}
func (m *defaultUsercenter) DelUserFollows(ctx context.Context, in *DelUserFollowsReq, opts ...grpc.CallOption) (*DelUserFollowsResp, error) {
client := pb.NewUsercenterClient(m.cli.Conn())
return client.DelUserFollows(ctx, in, opts...)
}
func (m *defaultUsercenter) GetUserFollowsById(ctx context.Context, in *GetUserFollowsByIdReq, opts ...grpc.CallOption) (*GetUserFollowsByIdResp, error) {
client := pb.NewUsercenterClient(m.cli.Conn())
return client.GetUserFollowsById(ctx, in, opts...)
}
func (m *defaultUsercenter) SearchUserFollows(ctx context.Context, in *SearchUserFollowsReq, opts ...grpc.CallOption) (*SearchUserFollowsResp, error) {
client := pb.NewUsercenterClient(m.cli.Conn())
return client.SearchUserFollows(ctx, in, opts...)
}
// -----------------------userPreferences-----------------------
func (m *defaultUsercenter) AddUserPreferences(ctx context.Context, in *AddUserPreferencesReq, opts ...grpc.CallOption) (*AddUserPreferencesResp, error) {
client := pb.NewUsercenterClient(m.cli.Conn())
return client.AddUserPreferences(ctx, in, opts...)
}
func (m *defaultUsercenter) UpdateUserPreferences(ctx context.Context, in *UpdateUserPreferencesReq, opts ...grpc.CallOption) (*UpdateUserPreferencesResp, error) {
client := pb.NewUsercenterClient(m.cli.Conn())
return client.UpdateUserPreferences(ctx, in, opts...)
}
func (m *defaultUsercenter) DelUserPreferences(ctx context.Context, in *DelUserPreferencesReq, opts ...grpc.CallOption) (*DelUserPreferencesResp, error) {
client := pb.NewUsercenterClient(m.cli.Conn())
return client.DelUserPreferences(ctx, in, opts...)
}
func (m *defaultUsercenter) GetUserPreferencesById(ctx context.Context, in *GetUserPreferencesByIdReq, opts ...grpc.CallOption) (*GetUserPreferencesByIdResp, error) {
client := pb.NewUsercenterClient(m.cli.Conn())
return client.GetUserPreferencesById(ctx, in, opts...)
}
func (m *defaultUsercenter) SearchUserPreferences(ctx context.Context, in *SearchUserPreferencesReq, opts ...grpc.CallOption) (*SearchUserPreferencesResp, error) {
client := pb.NewUsercenterClient(m.cli.Conn())
return client.SearchUserPreferences(ctx, in, opts...)
}