initial commit

This commit is contained in:
2025-05-22 19:39:08 +08:00
commit 531bb42d01
103 changed files with 10291 additions and 0 deletions

39
category/category.go Normal file
View File

@ -0,0 +1,39 @@
package main
import (
"flag"
"fmt"
"godemo/category/category"
"godemo/category/internal/config"
"godemo/category/internal/server"
"godemo/category/internal/svc"
"github.com/zeromicro/go-zero/core/conf"
"github.com/zeromicro/go-zero/core/service"
"github.com/zeromicro/go-zero/zrpc"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
var configFile = flag.String("f", "etc/category.yaml", "the config file")
func main() {
flag.Parse()
var c config.Config
conf.MustLoad(*configFile, &c)
ctx := svc.NewServiceContext(c)
s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {
category.RegisterCategoryServer(grpcServer, server.NewCategoryServer(ctx))
if c.Mode == service.DevMode || c.Mode == service.TestMode {
reflection.Register(grpcServer)
}
})
defer s.Stop()
fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)
s.Start()
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,591 @@
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
// versions:
// - protoc-gen-go-grpc v1.5.1
// - protoc v3.19.4
// source: rpc/category.proto
package category
import (
context "context"
grpc "google.golang.org/grpc"
codes "google.golang.org/grpc/codes"
status "google.golang.org/grpc/status"
)
// This is a compile-time assertion to ensure that this generated file
// is compatible with the grpc package it is being compiled against.
// Requires gRPC-Go v1.64.0 or later.
const _ = grpc.SupportPackageIsVersion9
const (
Category_Ping_FullMethodName = "/category.Category/Ping"
Category_CreateCategory_FullMethodName = "/category.Category/CreateCategory"
Category_UpdateCategory_FullMethodName = "/category.Category/UpdateCategory"
Category_DeleteCategory_FullMethodName = "/category.Category/DeleteCategory"
Category_GetCategory_FullMethodName = "/category.Category/GetCategory"
Category_GetChildren_FullMethodName = "/category.Category/GetChildren"
Category_GetTree_FullMethodName = "/category.Category/GetTree"
Category_MoveCategory_FullMethodName = "/category.Category/MoveCategory"
Category_GetAncestorPath_FullMethodName = "/category.Category/GetAncestorPath"
Category_BatchCreateCategories_FullMethodName = "/category.Category/BatchCreateCategories"
Category_BatchUpdateCategories_FullMethodName = "/category.Category/BatchUpdateCategories"
Category_ListCategories_FullMethodName = "/category.Category/ListCategories"
Category_CheckAlias_FullMethodName = "/category.Category/CheckAlias"
)
// CategoryClient is the client API for Category service.
//
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
//
// 分类服务 - 分类管理、树形结构操作、批量处理
type CategoryClient interface {
// 健康检查
Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error)
// 分类基础操作
CreateCategory(ctx context.Context, in *CreateCategoryRequest, opts ...grpc.CallOption) (*CategoryInfoResponse, error)
UpdateCategory(ctx context.Context, in *UpdateCategoryRequest, opts ...grpc.CallOption) (*CategoryInfoResponse, error)
DeleteCategory(ctx context.Context, in *DeleteCategoryRequest, opts ...grpc.CallOption) (*DeleteResponse, error)
GetCategory(ctx context.Context, in *GetCategoryRequest, opts ...grpc.CallOption) (*CategoryInfoResponse, error)
// 层级结构操作
GetChildren(ctx context.Context, in *GetChildrenRequest, opts ...grpc.CallOption) (*CategoryListResponse, error)
GetTree(ctx context.Context, in *GetTreeRequest, opts ...grpc.CallOption) (*CategoryTreeResponse, error)
MoveCategory(ctx context.Context, in *MoveCategoryRequest, opts ...grpc.CallOption) (*CategoryInfoResponse, error)
GetAncestorPath(ctx context.Context, in *GetAncestorPathRequest, opts ...grpc.CallOption) (*CategoryPathResponse, error)
// 批量操作
BatchCreateCategories(ctx context.Context, in *BatchCreateRequest, opts ...grpc.CallOption) (*BatchCreateResponse, error)
BatchUpdateCategories(ctx context.Context, in *BatchUpdateRequest, opts ...grpc.CallOption) (*BatchUpdateResponse, error)
// 查询过滤
ListCategories(ctx context.Context, in *ListCategoryRequest, opts ...grpc.CallOption) (*CategoryListResponse, error)
CheckAlias(ctx context.Context, in *CheckAliasRequest, opts ...grpc.CallOption) (*CheckAliasResponse, error)
}
type categoryClient struct {
cc grpc.ClientConnInterface
}
func NewCategoryClient(cc grpc.ClientConnInterface) CategoryClient {
return &categoryClient{cc}
}
func (c *categoryClient) Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(PingResponse)
err := c.cc.Invoke(ctx, Category_Ping_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *categoryClient) CreateCategory(ctx context.Context, in *CreateCategoryRequest, opts ...grpc.CallOption) (*CategoryInfoResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CategoryInfoResponse)
err := c.cc.Invoke(ctx, Category_CreateCategory_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *categoryClient) UpdateCategory(ctx context.Context, in *UpdateCategoryRequest, opts ...grpc.CallOption) (*CategoryInfoResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CategoryInfoResponse)
err := c.cc.Invoke(ctx, Category_UpdateCategory_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *categoryClient) DeleteCategory(ctx context.Context, in *DeleteCategoryRequest, opts ...grpc.CallOption) (*DeleteResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(DeleteResponse)
err := c.cc.Invoke(ctx, Category_DeleteCategory_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *categoryClient) GetCategory(ctx context.Context, in *GetCategoryRequest, opts ...grpc.CallOption) (*CategoryInfoResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CategoryInfoResponse)
err := c.cc.Invoke(ctx, Category_GetCategory_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *categoryClient) GetChildren(ctx context.Context, in *GetChildrenRequest, opts ...grpc.CallOption) (*CategoryListResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CategoryListResponse)
err := c.cc.Invoke(ctx, Category_GetChildren_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *categoryClient) GetTree(ctx context.Context, in *GetTreeRequest, opts ...grpc.CallOption) (*CategoryTreeResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CategoryTreeResponse)
err := c.cc.Invoke(ctx, Category_GetTree_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *categoryClient) MoveCategory(ctx context.Context, in *MoveCategoryRequest, opts ...grpc.CallOption) (*CategoryInfoResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CategoryInfoResponse)
err := c.cc.Invoke(ctx, Category_MoveCategory_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *categoryClient) GetAncestorPath(ctx context.Context, in *GetAncestorPathRequest, opts ...grpc.CallOption) (*CategoryPathResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CategoryPathResponse)
err := c.cc.Invoke(ctx, Category_GetAncestorPath_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *categoryClient) BatchCreateCategories(ctx context.Context, in *BatchCreateRequest, opts ...grpc.CallOption) (*BatchCreateResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(BatchCreateResponse)
err := c.cc.Invoke(ctx, Category_BatchCreateCategories_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *categoryClient) BatchUpdateCategories(ctx context.Context, in *BatchUpdateRequest, opts ...grpc.CallOption) (*BatchUpdateResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(BatchUpdateResponse)
err := c.cc.Invoke(ctx, Category_BatchUpdateCategories_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *categoryClient) ListCategories(ctx context.Context, in *ListCategoryRequest, opts ...grpc.CallOption) (*CategoryListResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CategoryListResponse)
err := c.cc.Invoke(ctx, Category_ListCategories_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
func (c *categoryClient) CheckAlias(ctx context.Context, in *CheckAliasRequest, opts ...grpc.CallOption) (*CheckAliasResponse, error) {
cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
out := new(CheckAliasResponse)
err := c.cc.Invoke(ctx, Category_CheckAlias_FullMethodName, in, out, cOpts...)
if err != nil {
return nil, err
}
return out, nil
}
// CategoryServer is the server API for Category service.
// All implementations must embed UnimplementedCategoryServer
// for forward compatibility.
//
// 分类服务 - 分类管理、树形结构操作、批量处理
type CategoryServer interface {
// 健康检查
Ping(context.Context, *PingRequest) (*PingResponse, error)
// 分类基础操作
CreateCategory(context.Context, *CreateCategoryRequest) (*CategoryInfoResponse, error)
UpdateCategory(context.Context, *UpdateCategoryRequest) (*CategoryInfoResponse, error)
DeleteCategory(context.Context, *DeleteCategoryRequest) (*DeleteResponse, error)
GetCategory(context.Context, *GetCategoryRequest) (*CategoryInfoResponse, error)
// 层级结构操作
GetChildren(context.Context, *GetChildrenRequest) (*CategoryListResponse, error)
GetTree(context.Context, *GetTreeRequest) (*CategoryTreeResponse, error)
MoveCategory(context.Context, *MoveCategoryRequest) (*CategoryInfoResponse, error)
GetAncestorPath(context.Context, *GetAncestorPathRequest) (*CategoryPathResponse, error)
// 批量操作
BatchCreateCategories(context.Context, *BatchCreateRequest) (*BatchCreateResponse, error)
BatchUpdateCategories(context.Context, *BatchUpdateRequest) (*BatchUpdateResponse, error)
// 查询过滤
ListCategories(context.Context, *ListCategoryRequest) (*CategoryListResponse, error)
CheckAlias(context.Context, *CheckAliasRequest) (*CheckAliasResponse, error)
mustEmbedUnimplementedCategoryServer()
}
// UnimplementedCategoryServer must be embedded to have
// forward compatible implementations.
//
// NOTE: this should be embedded by value instead of pointer to avoid a nil
// pointer dereference when methods are called.
type UnimplementedCategoryServer struct{}
func (UnimplementedCategoryServer) Ping(context.Context, *PingRequest) (*PingResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method Ping not implemented")
}
func (UnimplementedCategoryServer) CreateCategory(context.Context, *CreateCategoryRequest) (*CategoryInfoResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method CreateCategory not implemented")
}
func (UnimplementedCategoryServer) UpdateCategory(context.Context, *UpdateCategoryRequest) (*CategoryInfoResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method UpdateCategory not implemented")
}
func (UnimplementedCategoryServer) DeleteCategory(context.Context, *DeleteCategoryRequest) (*DeleteResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method DeleteCategory not implemented")
}
func (UnimplementedCategoryServer) GetCategory(context.Context, *GetCategoryRequest) (*CategoryInfoResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetCategory not implemented")
}
func (UnimplementedCategoryServer) GetChildren(context.Context, *GetChildrenRequest) (*CategoryListResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetChildren not implemented")
}
func (UnimplementedCategoryServer) GetTree(context.Context, *GetTreeRequest) (*CategoryTreeResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetTree not implemented")
}
func (UnimplementedCategoryServer) MoveCategory(context.Context, *MoveCategoryRequest) (*CategoryInfoResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method MoveCategory not implemented")
}
func (UnimplementedCategoryServer) GetAncestorPath(context.Context, *GetAncestorPathRequest) (*CategoryPathResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method GetAncestorPath not implemented")
}
func (UnimplementedCategoryServer) BatchCreateCategories(context.Context, *BatchCreateRequest) (*BatchCreateResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method BatchCreateCategories not implemented")
}
func (UnimplementedCategoryServer) BatchUpdateCategories(context.Context, *BatchUpdateRequest) (*BatchUpdateResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method BatchUpdateCategories not implemented")
}
func (UnimplementedCategoryServer) ListCategories(context.Context, *ListCategoryRequest) (*CategoryListResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method ListCategories not implemented")
}
func (UnimplementedCategoryServer) CheckAlias(context.Context, *CheckAliasRequest) (*CheckAliasResponse, error) {
return nil, status.Errorf(codes.Unimplemented, "method CheckAlias not implemented")
}
func (UnimplementedCategoryServer) mustEmbedUnimplementedCategoryServer() {}
func (UnimplementedCategoryServer) testEmbeddedByValue() {}
// UnsafeCategoryServer may be embedded to opt out of forward compatibility for this service.
// Use of this interface is not recommended, as added methods to CategoryServer will
// result in compilation errors.
type UnsafeCategoryServer interface {
mustEmbedUnimplementedCategoryServer()
}
func RegisterCategoryServer(s grpc.ServiceRegistrar, srv CategoryServer) {
// If the following call pancis, it indicates UnimplementedCategoryServer was
// embedded by pointer and is nil. This will cause panics if an
// unimplemented method is ever invoked, so we test this at initialization
// time to prevent it from happening at runtime later due to I/O.
if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
t.testEmbeddedByValue()
}
s.RegisterService(&Category_ServiceDesc, srv)
}
func _Category_Ping_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(PingRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CategoryServer).Ping(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Category_Ping_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CategoryServer).Ping(ctx, req.(*PingRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Category_CreateCategory_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CreateCategoryRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CategoryServer).CreateCategory(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Category_CreateCategory_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CategoryServer).CreateCategory(ctx, req.(*CreateCategoryRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Category_UpdateCategory_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(UpdateCategoryRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CategoryServer).UpdateCategory(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Category_UpdateCategory_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CategoryServer).UpdateCategory(ctx, req.(*UpdateCategoryRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Category_DeleteCategory_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(DeleteCategoryRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CategoryServer).DeleteCategory(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Category_DeleteCategory_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CategoryServer).DeleteCategory(ctx, req.(*DeleteCategoryRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Category_GetCategory_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetCategoryRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CategoryServer).GetCategory(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Category_GetCategory_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CategoryServer).GetCategory(ctx, req.(*GetCategoryRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Category_GetChildren_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetChildrenRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CategoryServer).GetChildren(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Category_GetChildren_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CategoryServer).GetChildren(ctx, req.(*GetChildrenRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Category_GetTree_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetTreeRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CategoryServer).GetTree(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Category_GetTree_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CategoryServer).GetTree(ctx, req.(*GetTreeRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Category_MoveCategory_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(MoveCategoryRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CategoryServer).MoveCategory(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Category_MoveCategory_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CategoryServer).MoveCategory(ctx, req.(*MoveCategoryRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Category_GetAncestorPath_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(GetAncestorPathRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CategoryServer).GetAncestorPath(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Category_GetAncestorPath_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CategoryServer).GetAncestorPath(ctx, req.(*GetAncestorPathRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Category_BatchCreateCategories_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(BatchCreateRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CategoryServer).BatchCreateCategories(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Category_BatchCreateCategories_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CategoryServer).BatchCreateCategories(ctx, req.(*BatchCreateRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Category_BatchUpdateCategories_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(BatchUpdateRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CategoryServer).BatchUpdateCategories(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Category_BatchUpdateCategories_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CategoryServer).BatchUpdateCategories(ctx, req.(*BatchUpdateRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Category_ListCategories_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(ListCategoryRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CategoryServer).ListCategories(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Category_ListCategories_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CategoryServer).ListCategories(ctx, req.(*ListCategoryRequest))
}
return interceptor(ctx, in, info, handler)
}
func _Category_CheckAlias_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
in := new(CheckAliasRequest)
if err := dec(in); err != nil {
return nil, err
}
if interceptor == nil {
return srv.(CategoryServer).CheckAlias(ctx, in)
}
info := &grpc.UnaryServerInfo{
Server: srv,
FullMethod: Category_CheckAlias_FullMethodName,
}
handler := func(ctx context.Context, req interface{}) (interface{}, error) {
return srv.(CategoryServer).CheckAlias(ctx, req.(*CheckAliasRequest))
}
return interceptor(ctx, in, info, handler)
}
// Category_ServiceDesc is the grpc.ServiceDesc for Category service.
// It's only intended for direct use with grpc.RegisterService,
// and not to be introspected or modified (even as a copy)
var Category_ServiceDesc = grpc.ServiceDesc{
ServiceName: "category.Category",
HandlerType: (*CategoryServer)(nil),
Methods: []grpc.MethodDesc{
{
MethodName: "Ping",
Handler: _Category_Ping_Handler,
},
{
MethodName: "CreateCategory",
Handler: _Category_CreateCategory_Handler,
},
{
MethodName: "UpdateCategory",
Handler: _Category_UpdateCategory_Handler,
},
{
MethodName: "DeleteCategory",
Handler: _Category_DeleteCategory_Handler,
},
{
MethodName: "GetCategory",
Handler: _Category_GetCategory_Handler,
},
{
MethodName: "GetChildren",
Handler: _Category_GetChildren_Handler,
},
{
MethodName: "GetTree",
Handler: _Category_GetTree_Handler,
},
{
MethodName: "MoveCategory",
Handler: _Category_MoveCategory_Handler,
},
{
MethodName: "GetAncestorPath",
Handler: _Category_GetAncestorPath_Handler,
},
{
MethodName: "BatchCreateCategories",
Handler: _Category_BatchCreateCategories_Handler,
},
{
MethodName: "BatchUpdateCategories",
Handler: _Category_BatchUpdateCategories_Handler,
},
{
MethodName: "ListCategories",
Handler: _Category_ListCategories_Handler,
},
{
MethodName: "CheckAlias",
Handler: _Category_CheckAlias_Handler,
},
},
Streams: []grpc.StreamDesc{},
Metadata: "rpc/category.proto",
}

View File

@ -0,0 +1,142 @@
// Code generated by goctl. DO NOT EDIT.
// goctl 1.8.3
// Source: category.proto
package categoryclient
import (
"context"
"godemo/category/category"
"github.com/zeromicro/go-zero/zrpc"
"google.golang.org/grpc"
)
type (
BatchCreateRequest = category.BatchCreateRequest
BatchCreateResponse = category.BatchCreateResponse
BatchUpdateRequest = category.BatchUpdateRequest
BatchUpdateResponse = category.BatchUpdateResponse
CategoryInfo = category.CategoryInfo
CategoryInfoResponse = category.CategoryInfoResponse
CategoryListResponse = category.CategoryListResponse
CategoryPathResponse = category.CategoryPathResponse
CategoryTreeResponse = category.CategoryTreeResponse
CategoryTreeResponse_TreeNode = category.CategoryTreeResponse_TreeNode
CheckAliasRequest = category.CheckAliasRequest
CheckAliasResponse = category.CheckAliasResponse
CreateCategoryRequest = category.CreateCategoryRequest
DeleteCategoryRequest = category.DeleteCategoryRequest
DeleteResponse = category.DeleteResponse
GetAncestorPathRequest = category.GetAncestorPathRequest
GetCategoryRequest = category.GetCategoryRequest
GetChildrenRequest = category.GetChildrenRequest
GetTreeRequest = category.GetTreeRequest
ListCategoryRequest = category.ListCategoryRequest
MoveCategoryRequest = category.MoveCategoryRequest
PingRequest = category.PingRequest
PingResponse = category.PingResponse
UpdateCategoryRequest = category.UpdateCategoryRequest
Category interface {
// 健康检查
Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error)
// 分类基础操作
CreateCategory(ctx context.Context, in *CreateCategoryRequest, opts ...grpc.CallOption) (*CategoryInfoResponse, error)
UpdateCategory(ctx context.Context, in *UpdateCategoryRequest, opts ...grpc.CallOption) (*CategoryInfoResponse, error)
DeleteCategory(ctx context.Context, in *DeleteCategoryRequest, opts ...grpc.CallOption) (*DeleteResponse, error)
GetCategory(ctx context.Context, in *GetCategoryRequest, opts ...grpc.CallOption) (*CategoryInfoResponse, error)
// 层级结构操作
GetChildren(ctx context.Context, in *GetChildrenRequest, opts ...grpc.CallOption) (*CategoryListResponse, error)
GetTree(ctx context.Context, in *GetTreeRequest, opts ...grpc.CallOption) (*CategoryTreeResponse, error)
MoveCategory(ctx context.Context, in *MoveCategoryRequest, opts ...grpc.CallOption) (*CategoryInfoResponse, error)
GetAncestorPath(ctx context.Context, in *GetAncestorPathRequest, opts ...grpc.CallOption) (*CategoryPathResponse, error)
// 批量操作
BatchCreateCategories(ctx context.Context, in *BatchCreateRequest, opts ...grpc.CallOption) (*BatchCreateResponse, error)
BatchUpdateCategories(ctx context.Context, in *BatchUpdateRequest, opts ...grpc.CallOption) (*BatchUpdateResponse, error)
// 查询过滤
ListCategories(ctx context.Context, in *ListCategoryRequest, opts ...grpc.CallOption) (*CategoryListResponse, error)
CheckAlias(ctx context.Context, in *CheckAliasRequest, opts ...grpc.CallOption) (*CheckAliasResponse, error)
}
defaultCategory struct {
cli zrpc.Client
}
)
func NewCategory(cli zrpc.Client) Category {
return &defaultCategory{
cli: cli,
}
}
// 健康检查
func (m *defaultCategory) Ping(ctx context.Context, in *PingRequest, opts ...grpc.CallOption) (*PingResponse, error) {
client := category.NewCategoryClient(m.cli.Conn())
return client.Ping(ctx, in, opts...)
}
// 分类基础操作
func (m *defaultCategory) CreateCategory(ctx context.Context, in *CreateCategoryRequest, opts ...grpc.CallOption) (*CategoryInfoResponse, error) {
client := category.NewCategoryClient(m.cli.Conn())
return client.CreateCategory(ctx, in, opts...)
}
func (m *defaultCategory) UpdateCategory(ctx context.Context, in *UpdateCategoryRequest, opts ...grpc.CallOption) (*CategoryInfoResponse, error) {
client := category.NewCategoryClient(m.cli.Conn())
return client.UpdateCategory(ctx, in, opts...)
}
func (m *defaultCategory) DeleteCategory(ctx context.Context, in *DeleteCategoryRequest, opts ...grpc.CallOption) (*DeleteResponse, error) {
client := category.NewCategoryClient(m.cli.Conn())
return client.DeleteCategory(ctx, in, opts...)
}
func (m *defaultCategory) GetCategory(ctx context.Context, in *GetCategoryRequest, opts ...grpc.CallOption) (*CategoryInfoResponse, error) {
client := category.NewCategoryClient(m.cli.Conn())
return client.GetCategory(ctx, in, opts...)
}
// 层级结构操作
func (m *defaultCategory) GetChildren(ctx context.Context, in *GetChildrenRequest, opts ...grpc.CallOption) (*CategoryListResponse, error) {
client := category.NewCategoryClient(m.cli.Conn())
return client.GetChildren(ctx, in, opts...)
}
func (m *defaultCategory) GetTree(ctx context.Context, in *GetTreeRequest, opts ...grpc.CallOption) (*CategoryTreeResponse, error) {
client := category.NewCategoryClient(m.cli.Conn())
return client.GetTree(ctx, in, opts...)
}
func (m *defaultCategory) MoveCategory(ctx context.Context, in *MoveCategoryRequest, opts ...grpc.CallOption) (*CategoryInfoResponse, error) {
client := category.NewCategoryClient(m.cli.Conn())
return client.MoveCategory(ctx, in, opts...)
}
func (m *defaultCategory) GetAncestorPath(ctx context.Context, in *GetAncestorPathRequest, opts ...grpc.CallOption) (*CategoryPathResponse, error) {
client := category.NewCategoryClient(m.cli.Conn())
return client.GetAncestorPath(ctx, in, opts...)
}
// 批量操作
func (m *defaultCategory) BatchCreateCategories(ctx context.Context, in *BatchCreateRequest, opts ...grpc.CallOption) (*BatchCreateResponse, error) {
client := category.NewCategoryClient(m.cli.Conn())
return client.BatchCreateCategories(ctx, in, opts...)
}
func (m *defaultCategory) BatchUpdateCategories(ctx context.Context, in *BatchUpdateRequest, opts ...grpc.CallOption) (*BatchUpdateResponse, error) {
client := category.NewCategoryClient(m.cli.Conn())
return client.BatchUpdateCategories(ctx, in, opts...)
}
// 查询过滤
func (m *defaultCategory) ListCategories(ctx context.Context, in *ListCategoryRequest, opts ...grpc.CallOption) (*CategoryListResponse, error) {
client := category.NewCategoryClient(m.cli.Conn())
return client.ListCategories(ctx, in, opts...)
}
func (m *defaultCategory) CheckAlias(ctx context.Context, in *CheckAliasRequest, opts ...grpc.CallOption) (*CheckAliasResponse, error) {
client := category.NewCategoryClient(m.cli.Conn())
return client.CheckAlias(ctx, in, opts...)
}

View File

@ -0,0 +1,13 @@
Name: category.rpc
ListenOn: 0.0.0.0:60300
Mode: dev
Etcd:
Hosts:
- 127.0.0.1:2379
Key: category.rpc
DB:
DataSource: postgres://postgres:postgres@localhost:5432/godemo?sslmode=disable
MaxOpenConns: 100
MaxIdleConns: 20
ConnMaxLifetime: 3600

View File

@ -0,0 +1,13 @@
package config
import "github.com/zeromicro/go-zero/zrpc"
type Config struct {
zrpc.RpcServerConf
DB struct {
DataSource string
MaxOpenConns int
MaxIdleConns int
ConnMaxLifetime int
}
}

View File

@ -0,0 +1,31 @@
package logic
import (
"context"
"godemo/category/category"
"godemo/category/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type BatchCreateCategoriesLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewBatchCreateCategoriesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BatchCreateCategoriesLogic {
return &BatchCreateCategoriesLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// 批量操作
func (l *BatchCreateCategoriesLogic) BatchCreateCategories(in *category.BatchCreateRequest) (*category.BatchCreateResponse, error) {
// todo: add your logic here and delete this line
return &category.BatchCreateResponse{}, nil
}

View File

@ -0,0 +1,30 @@
package logic
import (
"context"
"godemo/category/category"
"godemo/category/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type BatchUpdateCategoriesLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewBatchUpdateCategoriesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BatchUpdateCategoriesLogic {
return &BatchUpdateCategoriesLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *BatchUpdateCategoriesLogic) BatchUpdateCategories(in *category.BatchUpdateRequest) (*category.BatchUpdateResponse, error) {
// todo: add your logic here and delete this line
return &category.BatchUpdateResponse{}, nil
}

View File

@ -0,0 +1,30 @@
package logic
import (
"context"
"godemo/category/category"
"godemo/category/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type CheckAliasLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewCheckAliasLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CheckAliasLogic {
return &CheckAliasLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *CheckAliasLogic) CheckAlias(in *category.CheckAliasRequest) (*category.CheckAliasResponse, error) {
// todo: add your logic here and delete this line
return &category.CheckAliasResponse{}, nil
}

View File

@ -0,0 +1,118 @@
package logic
import (
"context"
"database/sql"
"errors"
"time"
"godemo/category/category"
"godemo/category/internal/model"
"godemo/category/internal/svc"
"github.com/google/uuid"
"github.com/zeromicro/go-zero/core/logx"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type CreateCategoryLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewCreateCategoryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateCategoryLogic {
return &CreateCategoryLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *CreateCategoryLogic) CreateCategory(in *category.CreateCategoryRequest) (*category.CategoryInfoResponse, error) {
// 参数校验
if in.SystemId == "" || in.Name == "" {
return nil, status.Error(codes.InvalidArgument, "system_id 和 name 不能为空")
}
// 检查唯一性
exists, err := l.checkCategoryExists(in)
if err != nil {
logx.Error("唯一性检查失败: ", err)
return nil, status.Error(codes.Internal, "内部错误")
}
if exists {
return nil, status.Error(codes.AlreadyExists, "分类已存在")
}
// 构建模型
newCategory := &model.Categories{
Id: uuid.New().String(),
SystemId: in.SystemId,
Name: in.Name,
Alias: toNullString(in.Alias),
ParentId: toNullString(in.ParentId),
Description: toNullString(in.Description),
CreatedAt: time.Now(),
UpdatedAt: sql.NullTime{Time: time.Now(), Valid: true},
}
// 插入数据库
if _, err := l.svcCtx.CategoryModel.Insert(l.ctx, newCategory); err != nil {
logx.Error("插入失败: ", err)
return nil, status.Error(codes.Internal, "创建分类失败")
}
// 返回响应
return &category.CategoryInfoResponse{
Category: &category.CategoryInfo{
Id: newCategory.Id,
SystemId: newCategory.SystemId,
Name: newCategory.Name,
Alias: in.Alias,
ParentId: in.ParentId,
Description: in.Description,
CreatedAt: newCategory.CreatedAt.Unix(),
UpdatedAt: newCategory.UpdatedAt.Time.Unix(),
},
}, nil
}
// 空字符串转换为 sql.NullString
func toNullString(s string) sql.NullString {
return sql.NullString{String: s, Valid: s != ""}
}
// 唯一性检查逻辑
func (l *CreateCategoryLogic) checkCategoryExists(in *category.CreateCategoryRequest) (bool, error) {
// 检查名称唯一性
_, err := l.svcCtx.CategoryModel.FindBySystemParentName(
l.ctx,
in.SystemId,
in.ParentId,
in.Name,
)
if err == nil {
return true, nil
} else if !errors.Is(err, model.ErrNotFound) {
return false, err
}
// 检查别名唯一性(如果提供了别名)
if in.Alias != "" {
_, err := l.svcCtx.CategoryModel.FindBySystemParentAlias(
l.ctx,
in.SystemId,
in.ParentId,
in.Alias,
)
if err == nil {
return true, nil
} else if !errors.Is(err, model.ErrNotFound) {
return false, err
}
}
return false, nil
}

View File

@ -0,0 +1,91 @@
package logic
import (
"context"
"errors"
"fmt"
"godemo/category/category"
"godemo/category/internal/model"
"godemo/category/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type DeleteCategoryLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewDeleteCategoryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DeleteCategoryLogic {
return &DeleteCategoryLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *DeleteCategoryLogic) DeleteCategory(in *category.DeleteCategoryRequest) (*category.DeleteResponse, error) {
// 1. 参数校验
if in.Id == "" {
return nil, status.Error(codes.InvalidArgument, "分类ID不能为空")
}
// 2. 检查分类是否存在
_, err := l.svcCtx.CategoryModel.FindOne(l.ctx, in.Id)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
return nil, status.Error(codes.NotFound, "分类不存在")
}
l.Logger.Errorf("查询分类失败: %v", err)
return nil, status.Error(codes.Internal, "内部错误")
}
// 3. 开启事务执行删除
err = l.svcCtx.CategoryModel.Transact(l.ctx, func(ctx context.Context, session sqlx.Session) error {
// 3.1 处理子分类根据外键约束自动级联删除或设为NULL
if err := l.handleChildren(ctx, session, in.Id); err != nil {
return err
}
// 3.2 删除主分类
if err := l.svcCtx.CategoryModel.WithSession(session).Delete(ctx, in.Id); err != nil {
return fmt.Errorf("删除分类失败: %w", err)
}
return nil
})
if err != nil {
l.Logger.Errorf("删除分类事务失败: %v", err)
return nil, status.Error(codes.Internal, "删除分类失败")
}
return &category.DeleteResponse{
Success: true,
}, nil
}
// handleChildren 处理子分类(根据外键约束配置决定行为)
func (l *DeleteCategoryLogic) handleChildren(ctx context.Context, session sqlx.Session, parentID string) error {
// 如果外键是 ON DELETE SET NULL需要显式更新子分类
if l.needUpdateChildren() {
query := "UPDATE categories SET parent_id = NULL WHERE parent_id = $1"
if _, err := session.ExecCtx(ctx, query, parentID); err != nil {
return fmt.Errorf("更新子分类失败: %w", err)
}
}
// 如果是 ON DELETE CASCADE 则无需额外处理
return nil
}
// needUpdateChildren 根据配置决定是否需要更新子分类
func (l *DeleteCategoryLogic) needUpdateChildren() bool {
// 这里根据实际数据库外键约束配置返回
// 可以在 config 中添加配置项控制行为
return false // 默认假设是 ON DELETE CASCADE
}

View File

@ -0,0 +1,30 @@
package logic
import (
"context"
"godemo/category/category"
"godemo/category/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type GetAncestorPathLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewGetAncestorPathLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAncestorPathLogic {
return &GetAncestorPathLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *GetAncestorPathLogic) GetAncestorPath(in *category.GetAncestorPathRequest) (*category.CategoryPathResponse, error) {
// todo: add your logic here and delete this line
return &category.CategoryPathResponse{}, nil
}

View File

@ -0,0 +1,85 @@
package logic
import (
"context"
"errors"
"godemo/category/category"
"godemo/category/internal/model"
"godemo/category/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type GetCategoryLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewGetCategoryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCategoryLogic {
return &GetCategoryLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *GetCategoryLogic) GetCategory(in *category.GetCategoryRequest) (*category.CategoryInfoResponse, error) {
// 1. 参数校验
if in.Id == "" {
return nil, status.Error(codes.InvalidArgument, "分类ID不能为空")
}
// 2. 查询数据库
categoryData, err := l.svcCtx.CategoryModel.FindOne(l.ctx, in.Id)
if err != nil {
if errors.Is(err, model.ErrNotFound) {
l.Logger.Errorf("分类不存在, ID: %s", in.Id)
return nil, status.Error(codes.NotFound, "分类不存在")
}
l.Logger.Errorf("数据库查询失败: %v", err)
return nil, status.Error(codes.Internal, "内部错误")
}
// 3. 转换响应格式
return l.convertToResponse(categoryData), nil
}
func (l *GetCategoryLogic) convertToResponse(c *model.Categories) *category.CategoryInfoResponse {
// 处理可能为空的字段
var alias, parentID, description string
if c.Alias.Valid {
alias = c.Alias.String
}
if c.ParentId.Valid {
parentID = c.ParentId.String
}
if c.Description.Valid {
description = c.Description.String
}
// 处理时间戳
var updatedAt int64
if c.UpdatedAt.Valid {
updatedAt = c.UpdatedAt.Time.Unix()
} else {
updatedAt = c.CreatedAt.Unix() // 如果未更新过,使用创建时间
}
return &category.CategoryInfoResponse{
Category: &category.CategoryInfo{
Id: c.Id,
SystemId: c.SystemId,
Name: c.Name,
Alias: alias,
ParentId: parentID,
Description: description,
CreatedAt: c.CreatedAt.Unix(),
UpdatedAt: updatedAt,
},
}
}

View File

@ -0,0 +1,31 @@
package logic
import (
"context"
"godemo/category/category"
"godemo/category/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type GetChildrenLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewGetChildrenLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetChildrenLogic {
return &GetChildrenLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// 层级结构操作
func (l *GetChildrenLogic) GetChildren(in *category.GetChildrenRequest) (*category.CategoryListResponse, error) {
// todo: add your logic here and delete this line
return &category.CategoryListResponse{}, nil
}

View File

@ -0,0 +1,30 @@
package logic
import (
"context"
"godemo/category/category"
"godemo/category/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type GetTreeLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewGetTreeLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetTreeLogic {
return &GetTreeLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *GetTreeLogic) GetTree(in *category.GetTreeRequest) (*category.CategoryTreeResponse, error) {
// todo: add your logic here and delete this line
return &category.CategoryTreeResponse{}, nil
}

View File

@ -0,0 +1,31 @@
package logic
import (
"context"
"godemo/category/category"
"godemo/category/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type ListCategoriesLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewListCategoriesLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListCategoriesLogic {
return &ListCategoriesLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// 查询过滤
func (l *ListCategoriesLogic) ListCategories(in *category.ListCategoryRequest) (*category.CategoryListResponse, error) {
// todo: add your logic here and delete this line
return &category.CategoryListResponse{}, nil
}

View File

@ -0,0 +1,30 @@
package logic
import (
"context"
"godemo/category/category"
"godemo/category/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type MoveCategoryLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewMoveCategoryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MoveCategoryLogic {
return &MoveCategoryLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *MoveCategoryLogic) MoveCategory(in *category.MoveCategoryRequest) (*category.CategoryInfoResponse, error) {
// todo: add your logic here and delete this line
return &category.CategoryInfoResponse{}, nil
}

View File

@ -0,0 +1,31 @@
package logic
import (
"context"
"godemo/category/category"
"godemo/category/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
)
type PingLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewPingLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PingLogic {
return &PingLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
// 健康检查
func (l *PingLogic) Ping(in *category.PingRequest) (*category.PingResponse, error) {
// todo: add your logic here and delete this line
return &category.PingResponse{}, nil
}

View File

@ -0,0 +1,218 @@
package logic
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
"godemo/category/category"
"godemo/category/internal/model"
"godemo/category/internal/svc"
"github.com/zeromicro/go-zero/core/logx"
"github.com/zeromicro/go-zero/core/stores/sqlx"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type UpdateCategoryLogic struct {
ctx context.Context
svcCtx *svc.ServiceContext
logx.Logger
}
func NewUpdateCategoryLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateCategoryLogic {
return &UpdateCategoryLogic{
ctx: ctx,
svcCtx: svcCtx,
Logger: logx.WithContext(ctx),
}
}
func (l *UpdateCategoryLogic) UpdateCategory(in *category.UpdateCategoryRequest) (*category.CategoryInfoResponse, error) {
// 1. 参数校验
if err := l.validateRequest(in); err != nil {
return nil, err
}
// 2. 获取现有分类
existing, err := l.svcCtx.CategoryModel.FindOne(l.ctx, in.Id)
if err != nil {
return l.handleFindError(err, in.Id)
}
// 3. 检查更新后的名称/别名是否冲突
if err := l.checkUniqueness(in, existing); err != nil {
return nil, err
}
// 4. 构建更新模型
updatedCategory := l.buildUpdatedModel(in, existing)
// 5. 事务更新
if err := l.updateWithTransaction(updatedCategory); err != nil {
return nil, err
}
// 6. 清理缓存
// 7. 返回更新后的数据
return l.buildResponse(updatedCategory), nil
}
// 参数校验
func (l *UpdateCategoryLogic) validateRequest(in *category.UpdateCategoryRequest) error {
if in.Id == "" {
return status.Error(codes.InvalidArgument, "分类ID不能为空")
}
if in.Name == "" && in.Alias == "" && in.ParentId == "" && in.Description == "" {
return status.Error(codes.InvalidArgument, "至少需要提供一个更新字段")
}
return nil
}
// 处理查询错误
func (l *UpdateCategoryLogic) handleFindError(err error, id string) (*category.CategoryInfoResponse, error) {
if errors.Is(err, model.ErrNotFound) {
l.Logger.Errorf("分类不存在, ID: %s", id)
return nil, status.Error(codes.NotFound, "分类不存在")
}
l.Logger.Errorf("查询分类失败: %v", err)
return nil, status.Error(codes.Internal, "内部错误")
}
// 检查名称/别名唯一性
func (l *UpdateCategoryLogic) checkUniqueness(in *category.UpdateCategoryRequest, existing *model.Categories) error {
// 如果名称有修改,检查新名称是否冲突
if in.Name != "" && in.Name != existing.Name {
parentID := existing.ParentId
if in.ParentId != "" {
parentID = sql.NullString{String: in.ParentId, Valid: true}
}
_, err := l.svcCtx.CategoryModel.FindBySystemParentName(
l.ctx,
existing.SystemId,
parentID.String,
in.Name,
)
if err == nil {
return status.Error(codes.AlreadyExists, "分类名称已存在")
} else if !errors.Is(err, model.ErrNotFound) {
l.Logger.Errorf("名称唯一性检查失败: %v", err)
return status.Error(codes.Internal, "内部错误")
}
}
// 如果别名有修改,检查新别名是否冲突
if in.Alias != "" && in.Alias != existing.Alias.String {
parentID := existing.ParentId
if in.ParentId != "" {
parentID = sql.NullString{String: in.ParentId, Valid: true}
}
_, err := l.svcCtx.CategoryModel.FindBySystemParentAlias(
l.ctx,
existing.SystemId,
parentID.String,
in.Alias,
)
if err == nil {
return status.Error(codes.AlreadyExists, "分类别名已存在")
} else if !errors.Is(err, model.ErrNotFound) {
l.Logger.Errorf("别名唯一性检查失败: %v", err)
return status.Error(codes.Internal, "内部错误")
}
}
return nil
}
// 构建更新后的模型
func (l *UpdateCategoryLogic) buildUpdatedModel(in *category.UpdateCategoryRequest, existing *model.Categories) *model.Categories {
updated := *existing // 复制原有值
// 只更新提供的字段
if in.Name != "" {
updated.Name = in.Name
}
if in.Alias != "" {
updated.Alias = sql.NullString{String: in.Alias, Valid: true}
} else if in.Alias == "" && existing.Alias.Valid {
// 明确传递空字符串表示清空别名
updated.Alias = sql.NullString{Valid: false}
}
if in.ParentId != "" {
if in.ParentId == "NULL" { // 特殊值表示设为NULL
updated.ParentId = sql.NullString{Valid: false}
} else {
updated.ParentId = sql.NullString{String: in.ParentId, Valid: true}
}
}
if in.Description != "" {
updated.Description = sql.NullString{String: in.Description, Valid: true}
} else if in.Description == "" && existing.Description.Valid {
// 明确传递空字符串表示清空描述
updated.Description = sql.NullString{Valid: false}
}
updated.UpdatedAt = sql.NullTime{Time: time.Now(), Valid: true}
return &updated
}
// 事务更新
func (l *UpdateCategoryLogic) updateWithTransaction(updated *model.Categories) error {
return l.svcCtx.CategoryModel.Transact(l.ctx, func(ctx context.Context, session sqlx.Session) error {
// 检查父分类是否存在(如果修改了父分类)
if updated.ParentId.Valid && updated.ParentId.String != "" {
if _, err := l.svcCtx.CategoryModel.WithSession(session).FindOne(ctx, updated.ParentId.String); err != nil {
if errors.Is(err, model.ErrNotFound) {
return status.Error(codes.InvalidArgument, "指定的父分类不存在")
}
return fmt.Errorf("查询父分类失败: %w", err)
}
}
// 执行更新
if err := l.svcCtx.CategoryModel.WithSession(session).Update(ctx, updated); err != nil {
return fmt.Errorf("更新分类失败: %w", err)
}
return nil
})
}
// 构建响应
func (l *UpdateCategoryLogic) buildResponse(c *model.Categories) *category.CategoryInfoResponse {
resp := &category.CategoryInfoResponse{
Category: &category.CategoryInfo{
Id: c.Id,
SystemId: c.SystemId,
Name: c.Name,
CreatedAt: c.CreatedAt.Unix(),
},
}
// 处理可能为空的字段
if c.Alias.Valid {
resp.Category.Alias = c.Alias.String
}
if c.ParentId.Valid {
resp.Category.ParentId = c.ParentId.String
}
if c.Description.Valid {
resp.Category.Description = c.Description.String
}
if c.UpdatedAt.Valid {
resp.Category.UpdatedAt = c.UpdatedAt.Time.Unix()
} else {
resp.Category.UpdatedAt = c.CreatedAt.Unix()
}
return resp
}

View File

@ -0,0 +1,74 @@
package model
import (
"context"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
var _ CategoriesModel = (*customCategoriesModel)(nil)
type (
// CategoriesModel is an interface to be customized, add more methods here,
// and implement the added methods in customCategoriesModel.
CategoriesModel interface {
categoriesModel
WithSession(session sqlx.Session) CategoriesModel
Transact(ctx context.Context, fn func(ctx context.Context, session sqlx.Session) error) error
FindBySystemParentName(ctx context.Context, systemID string, parentID string, name string) (*Categories, error)
FindBySystemParentAlias(ctx context.Context, systemID string, parentID string, alias string) (*Categories, error)
}
customCategoriesModel struct {
*defaultCategoriesModel
}
)
// NewCategoriesModel returns a model for the database table.
func NewCategoriesModel(conn sqlx.SqlConn) CategoriesModel {
return &customCategoriesModel{
defaultCategoriesModel: newCategoriesModel(conn),
}
}
func (m *customCategoriesModel) WithSession(session sqlx.Session) CategoriesModel {
return NewCategoriesModel(sqlx.NewSqlConnFromSession(session))
}
func (m *customCategoriesModel) Transact(ctx context.Context, fn func(ctx context.Context, session sqlx.Session) error) error {
return m.conn.TransactCtx(ctx, func(ctx context.Context, session sqlx.Session) error {
return fn(ctx, session)
})
}
// 根据 system_id + parent_id + name 查询
func (m *customCategoriesModel) FindBySystemParentName(ctx context.Context, systemID string, parentID string, name string) (*Categories, error) {
query := `
SELECT * FROM categories
WHERE system_id = $1
AND COALESCE(parent_id, '') = COALESCE($2, '')
AND name = $3
`
var resp Categories
err := m.conn.QueryRowCtx(ctx, &resp, query, systemID, parentID, name)
if err != nil {
return nil, err
}
return &resp, nil
}
// 根据 system_id + parent_id + alias 查询
func (m *customCategoriesModel) FindBySystemParentAlias(ctx context.Context, systemID string, parentID string, alias string) (*Categories, error) {
query := `
SELECT * FROM categories
WHERE system_id = $1
AND COALESCE(parent_id, '') = COALESCE($2, '')
AND alias = $3
`
var resp Categories
err := m.conn.QueryRowCtx(ctx, &resp, query, systemID, parentID, alias)
if err != nil {
return nil, err
}
return &resp, nil
}

View File

@ -0,0 +1,122 @@
// Code generated by goctl. DO NOT EDIT.
// versions:
// goctl version: 1.8.3
package model
import (
"context"
"database/sql"
"fmt"
"strings"
"time"
"github.com/zeromicro/go-zero/core/stores/builder"
"github.com/zeromicro/go-zero/core/stores/sqlx"
"github.com/zeromicro/go-zero/core/stringx"
)
var (
categoriesFieldNames = builder.RawFieldNames(&Categories{}, true)
categoriesRows = strings.Join(categoriesFieldNames, ",")
categoriesRowsExpectAutoSet = strings.Join(stringx.Remove(categoriesFieldNames, "create_at", "create_time", "created_at", "update_at", "update_time", "updated_at"), ",")
categoriesRowsWithPlaceHolder = builder.PostgreSqlJoin(stringx.Remove(categoriesFieldNames, "id", "create_at", "create_time", "created_at", "update_at", "update_time", "updated_at"))
)
type (
categoriesModel interface {
Insert(ctx context.Context, data *Categories) (sql.Result, error)
FindOne(ctx context.Context, id string) (*Categories, error)
FindOneBySystemIdParentIdAlias(ctx context.Context, systemId string, parentId sql.NullString, alias sql.NullString) (*Categories, error)
FindOneBySystemIdParentIdName(ctx context.Context, systemId string, parentId sql.NullString, name string) (*Categories, error)
Update(ctx context.Context, data *Categories) error
Delete(ctx context.Context, id string) error
}
defaultCategoriesModel struct {
conn sqlx.SqlConn
table string
}
Categories struct {
Id string `db:"id"`
SystemId string `db:"system_id"`
Name string `db:"name"`
Alias sql.NullString `db:"alias"`
ParentId sql.NullString `db:"parent_id"`
Description sql.NullString `db:"description"`
CreatedAt time.Time `db:"created_at"`
UpdatedAt sql.NullTime `db:"updated_at"`
}
)
func newCategoriesModel(conn sqlx.SqlConn) *defaultCategoriesModel {
return &defaultCategoriesModel{
conn: conn,
table: `"public"."categories"`,
}
}
func (m *defaultCategoriesModel) Delete(ctx context.Context, id string) error {
query := fmt.Sprintf("delete from %s where id = $1", m.table)
_, err := m.conn.ExecCtx(ctx, query, id)
return err
}
func (m *defaultCategoriesModel) FindOne(ctx context.Context, id string) (*Categories, error) {
query := fmt.Sprintf("select %s from %s where id = $1 limit 1", categoriesRows, m.table)
var resp Categories
err := m.conn.QueryRowCtx(ctx, &resp, query, id)
switch err {
case nil:
return &resp, nil
case sqlx.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultCategoriesModel) FindOneBySystemIdParentIdAlias(ctx context.Context, systemId string, parentId sql.NullString, alias sql.NullString) (*Categories, error) {
var resp Categories
query := fmt.Sprintf("select %s from %s where system_id = $1 and parent_id = $2 and alias = $3 limit 1", categoriesRows, m.table)
err := m.conn.QueryRowCtx(ctx, &resp, query, systemId, parentId, alias)
switch err {
case nil:
return &resp, nil
case sqlx.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultCategoriesModel) FindOneBySystemIdParentIdName(ctx context.Context, systemId string, parentId sql.NullString, name string) (*Categories, error) {
var resp Categories
query := fmt.Sprintf("select %s from %s where system_id = $1 and parent_id = $2 and name = $3 limit 1", categoriesRows, m.table)
err := m.conn.QueryRowCtx(ctx, &resp, query, systemId, parentId, name)
switch err {
case nil:
return &resp, nil
case sqlx.ErrNotFound:
return nil, ErrNotFound
default:
return nil, err
}
}
func (m *defaultCategoriesModel) Insert(ctx context.Context, data *Categories) (sql.Result, error) {
query := fmt.Sprintf("insert into %s (%s) values ($1, $2, $3, $4, $5, $6)", m.table, categoriesRowsExpectAutoSet)
ret, err := m.conn.ExecCtx(ctx, query, data.Id, data.SystemId, data.Name, data.Alias, data.ParentId, data.Description)
return ret, err
}
func (m *defaultCategoriesModel) Update(ctx context.Context, newData *Categories) error {
query := fmt.Sprintf("update %s set %s where id = $1", m.table, categoriesRowsWithPlaceHolder)
_, err := m.conn.ExecCtx(ctx, query, newData.Id, newData.SystemId, newData.Name, newData.Alias, newData.ParentId, newData.Description)
return err
}
func (m *defaultCategoriesModel) tableName() string {
return m.table
}

View File

@ -0,0 +1,5 @@
package model
import "github.com/zeromicro/go-zero/core/stores/sqlx"
var ErrNotFound = sqlx.ErrNotFound

View File

@ -0,0 +1,94 @@
// Code generated by goctl. DO NOT EDIT.
// goctl 1.8.3
// Source: category.proto
package server
import (
"context"
"godemo/category/category"
"godemo/category/internal/logic"
"godemo/category/internal/svc"
)
type CategoryServer struct {
svcCtx *svc.ServiceContext
category.UnimplementedCategoryServer
}
func NewCategoryServer(svcCtx *svc.ServiceContext) *CategoryServer {
return &CategoryServer{
svcCtx: svcCtx,
}
}
// 健康检查
func (s *CategoryServer) Ping(ctx context.Context, in *category.PingRequest) (*category.PingResponse, error) {
l := logic.NewPingLogic(ctx, s.svcCtx)
return l.Ping(in)
}
// 分类基础操作
func (s *CategoryServer) CreateCategory(ctx context.Context, in *category.CreateCategoryRequest) (*category.CategoryInfoResponse, error) {
l := logic.NewCreateCategoryLogic(ctx, s.svcCtx)
return l.CreateCategory(in)
}
func (s *CategoryServer) UpdateCategory(ctx context.Context, in *category.UpdateCategoryRequest) (*category.CategoryInfoResponse, error) {
l := logic.NewUpdateCategoryLogic(ctx, s.svcCtx)
return l.UpdateCategory(in)
}
func (s *CategoryServer) DeleteCategory(ctx context.Context, in *category.DeleteCategoryRequest) (*category.DeleteResponse, error) {
l := logic.NewDeleteCategoryLogic(ctx, s.svcCtx)
return l.DeleteCategory(in)
}
func (s *CategoryServer) GetCategory(ctx context.Context, in *category.GetCategoryRequest) (*category.CategoryInfoResponse, error) {
l := logic.NewGetCategoryLogic(ctx, s.svcCtx)
return l.GetCategory(in)
}
// 层级结构操作
func (s *CategoryServer) GetChildren(ctx context.Context, in *category.GetChildrenRequest) (*category.CategoryListResponse, error) {
l := logic.NewGetChildrenLogic(ctx, s.svcCtx)
return l.GetChildren(in)
}
func (s *CategoryServer) GetTree(ctx context.Context, in *category.GetTreeRequest) (*category.CategoryTreeResponse, error) {
l := logic.NewGetTreeLogic(ctx, s.svcCtx)
return l.GetTree(in)
}
func (s *CategoryServer) MoveCategory(ctx context.Context, in *category.MoveCategoryRequest) (*category.CategoryInfoResponse, error) {
l := logic.NewMoveCategoryLogic(ctx, s.svcCtx)
return l.MoveCategory(in)
}
func (s *CategoryServer) GetAncestorPath(ctx context.Context, in *category.GetAncestorPathRequest) (*category.CategoryPathResponse, error) {
l := logic.NewGetAncestorPathLogic(ctx, s.svcCtx)
return l.GetAncestorPath(in)
}
// 批量操作
func (s *CategoryServer) BatchCreateCategories(ctx context.Context, in *category.BatchCreateRequest) (*category.BatchCreateResponse, error) {
l := logic.NewBatchCreateCategoriesLogic(ctx, s.svcCtx)
return l.BatchCreateCategories(in)
}
func (s *CategoryServer) BatchUpdateCategories(ctx context.Context, in *category.BatchUpdateRequest) (*category.BatchUpdateResponse, error) {
l := logic.NewBatchUpdateCategoriesLogic(ctx, s.svcCtx)
return l.BatchUpdateCategories(in)
}
// 查询过滤
func (s *CategoryServer) ListCategories(ctx context.Context, in *category.ListCategoryRequest) (*category.CategoryListResponse, error) {
l := logic.NewListCategoriesLogic(ctx, s.svcCtx)
return l.ListCategories(in)
}
func (s *CategoryServer) CheckAlias(ctx context.Context, in *category.CheckAliasRequest) (*category.CheckAliasResponse, error) {
l := logic.NewCheckAliasLogic(ctx, s.svcCtx)
return l.CheckAlias(in)
}

View File

@ -0,0 +1,22 @@
package svc
import (
"godemo/category/internal/config"
"godemo/category/internal/model"
_ "github.com/lib/pq"
"github.com/zeromicro/go-zero/core/stores/sqlx"
)
type ServiceContext struct {
Config config.Config
CategoryModel model.CategoriesModel
}
func NewServiceContext(c config.Config) *ServiceContext {
conn := sqlx.NewSqlConn("postgres", c.DB.DataSource)
return &ServiceContext{
Config: c,
CategoryModel: model.NewCategoriesModel(conn),
}
}