添加管理员控制器,api控制器功能

This commit is contained in:
南浔 2024-11-07 23:25:04 +08:00
commit 23c4126bc0
26 changed files with 1221 additions and 12 deletions

View File

@ -11,6 +11,8 @@ namespace Apimanager_backend.Config
CreateMap<User,UserInfoDto>();
CreateMap<CreateUserDto, User>()
.ForMember(dest => dest.PassHash, opt => opt.MapFrom(src => src.Password));
CreateMap<Api, ApiInfoDto>();
CreateMap<CreateApiInfo, Api>();
}
}
}

View File

@ -100,6 +100,7 @@ namespace Apimanager_backend.Controllers
message:"Success",
data:null
);
return Ok(res);
}
#endregion
#region
@ -115,6 +116,7 @@ namespace Apimanager_backend.Controllers
message: "Success",
data: userInfo
);
return Ok(res);
}
catch(BaseException e)
{
@ -129,5 +131,19 @@ namespace Apimanager_backend.Controllers
}
#endregion
#region
[HttpGet]
[Authorize(Roles = "Admin")]
public async Task<ActionResult<ResponseBase<int>>> UserCount()
{
int count = await adminService.UserCountAsync();
var res = new ResponseBase<int>(
code:1000,
message:"Success",
data:count
);
return Ok(res);
}
#endregion
}
}

View File

@ -0,0 +1,179 @@
using Apimanager_backend.Dtos;
using Apimanager_backend.Exceptions;
using Apimanager_backend.Services;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using StackExchange.Redis;
namespace Apimanager_backend.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class ApisController : ControllerBase
{
private readonly IApiService apiService;
private readonly ILogger<ApisController> logger;
public ApisController(IApiService apiService,ILogger<ApisController> logger)
{
this.apiService = apiService;
this.logger = logger;
}
#region API信息
[HttpGet]
[Authorize(Roles = "User")]
public async Task<ActionResult<ResponseBase<ApiInfoDto>>> ApiInfo(int apiId)
{
try
{
var apiInfo = await apiService.GetApiInfoAsync(apiId);
var res = new ResponseBase<ApiInfoDto>(
code: 1000,
message: "Success",
data: apiInfo
);
return Ok(res);
}catch(BaseException e)
{
var res = new ResponseBase<ApiInfoDto>(
code: e.code,
message: e.message,
data: null
);
return NotFound(res);
}
}
#endregion
#region API列表
[HttpGet]
[Authorize(Roles = "User")]
public async Task<ActionResult<ResponseBase<List<ApiInfoDto>>>> ApiList(int pageIndex,int pageSize,bool desc)
{
var list = await apiService.GetApisAsync(pageIndex, pageSize, desc);
var res = new ResponseBase<List<ApiInfoDto>>(
code:1000,
message:"Success",
data:list
);
return Ok(res);
}
#endregion
#region
[HttpPost]
[Authorize(Roles = "Admin")]
public async Task<ActionResult<ResponseBase<ApiInfoDto>>> AddApi([FromBody]CreateApiInfo createApiInfo)
{
var apiInfo = await apiService.AddApiAsync(createApiInfo);
var res = new ResponseBase<ApiInfoDto>(
code:1000,
message:"Success",
data: apiInfo
);
return Ok(res);
}
#endregion
#region
[HttpDelete]
[Authorize(Roles = "Admin")]
public async Task<ActionResult<ResponseBase<object?>>> DeleteApi(int apiId)
{
try
{
await apiService.DeleteApiAsync(apiId);
var res = new ResponseBase<object?>(
code: 1000,
message: "Success",
data: null
);
return Ok(res);
}catch(BaseException e)
{
var res = new ResponseBase<object?>(
code: e.code,
message: e.message,
data: null
);
return NotFound(res);
}
}
#endregion
#region api信息
[HttpPost]
[Authorize(Roles = "Admin")]
public async Task<ActionResult<ResponseBase<ApiInfoDto>>> UpdateApi(int apiId,UpdateApiDto updateApiDto)
{
try
{
//更新
var apiInfo = await apiService.UpdateApiAsync(apiId, updateApiDto);
var res = new ResponseBase<ApiInfoDto>(
code: 1000,
message: "Success",
data: apiInfo
);
return Ok(res);
}catch(BaseException e)
{
var res = new ResponseBase<ApiInfoDto>(
code: e.code,
message: e.message,
data: null
);
return NotFound(res);
}
}
#endregion
#region APi
[HttpPost]
[Authorize(Roles = "Admin")]
public async Task<ActionResult<ResponseBase<object?>>> BanApi(int userId)
{
try
{
await apiService.OffApiAsync(userId);
var res = new ResponseBase<object?>(
code: 1000,
message: "Success",
data: null
);
return Ok(res);
}catch(BaseException e)
{
var res = new ResponseBase<object?>(
code: e.code,
message: e.message,
data: null
);
return NotFound(res);
}
}
#endregion
#region API
[HttpPost]
[Authorize(Roles = "Admin")]
public async Task<ActionResult<ResponseBase<object?>>> UnBanApi(int userId)
{
try
{
await apiService.OnApiAsync(userId);
var res = new ResponseBase<object?>(
code: 1000,
message: "Success",
data: null
);
return Ok(res);
}catch(BaseException e)
{
var res = new ResponseBase<object?>(
code: e.code,
message: e.message,
data: null
);
return NotFound(res);
}
}
#endregion
}
}

View File

@ -0,0 +1,19 @@
using Apimanager_backend.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
namespace Apimanager_backend.Data
{
public class ApiRequestExampleConfig : IEntityTypeConfiguration<ApiRequestExample>
{
public void Configure(EntityTypeBuilder<ApiRequestExample> builder)
{
//主键
builder.HasKey(x => x.Id);
//外键
builder.HasOne(x => x.Api)
.WithMany(u => u.ApiRequestExamples)
.HasForeignKey(x => x.ApiId);
}
}
}

View File

@ -0,0 +1,17 @@
using System.ComponentModel.DataAnnotations;
namespace Apimanager_backend.Dtos
{
public class AddPackageDto
{
[Required(ErrorMessage = "套餐名称必填")]
[MaxLength(20,ErrorMessage = "套餐名称最大20字符")]
public string Name { get; set; }
[Required(ErrorMessage = "调用次数必填")]
public int CallLimit { get; set; }
[Required(ErrorMessage = "价格必填")]
public decimal Price { get; set; }
[Required(ErrorMessage = "分钟调用限制必填")]
public int OneMinuteLimit { get; set; }
}
}

View File

@ -2,7 +2,7 @@
{
public class AdminUpdateUserDto
{
public string Password { get; set; }
public decimal Balance { get; set; }
public string? Password { get; set; }
public decimal? Balance { get; set; }
}
}

View File

@ -0,0 +1,16 @@
using Apimanager_backend.Models;
namespace Apimanager_backend.Dtos
{
public class ApiInfoDto
{
public int Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public string Endpoint { get; set; }
public ApiMethod Method { get; set; }
public bool IsThirdParty { get; set; }
public bool IsActive { get; set; }
public Apipackage? Package { get; set; }
}
}

View File

@ -15,6 +15,12 @@
this.Message = message;
this.Data = data;
}
public ResponseBase(T data)
{
this.Code = 1000;
this.Message = "Success";
this.Data = data;
}
public ResponseBase() { }
}
}

View File

@ -0,0 +1,22 @@
using Apimanager_backend.Models;
using System.ComponentModel.DataAnnotations;
namespace Apimanager_backend.Dtos
{
public class CreateApiInfo
{
[Required(ErrorMessage = "API名称必填")]
[MaxLength(50,ErrorMessage = "API名称最大50字符")]
public string Name { get; set; }
public string Description { get; set; } = string.Empty;
[Required(ErrorMessage = "调用端点必填")]
public string Endpoint { get; set; }
[Required(ErrorMessage = "调用方式必填")]
[MaxLength(20,ErrorMessage = "调用方式最大20字符")]
public ApiMethod Method { get; set; }
public int? PackageId { get; set; }
[Required(ErrorMessage = "是否为三方接口必选")]
public bool IsThirdParty { get; set; }
}
}

View File

@ -0,0 +1,12 @@
namespace Apimanager_backend.Dtos
{
public class PackageInfoDto
{
public int Id { get; set; }
public string Name { get; set; }
public int CallLimit { get; set; }
public decimal Price { get; set; }
public int OneMinuteLimit { get; set; }
}
}

View File

@ -0,0 +1,14 @@
using Apimanager_backend.Models;
namespace Apimanager_backend.Dtos
{
public class UpdateApiDto
{
public string? Name { get; set; }
public string? Description { get; set; }
public string? Endpoint { get; set; }
public ApiMethod? Method { get; set; }
public int? PackageId { get; set; }
}
}

View File

@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;
namespace Apimanager_backend.Dtos
{
public class UpdatePackageDto
{
[MaxLength(20, ErrorMessage = "套餐名称最大20字符")]
public string? Name { get; set; }
public int? CallLimit { get; set; }
public decimal? Price { get; set; }
public int? OneMinuteLimit { get; set; }
}
}

View File

@ -0,0 +1,493 @@
// <auto-generated />
using System;
using Apimanager_backend.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace Apimanager_backend.Migrations
{
[DbContext(typeof(ApiContext))]
[Migration("20241108013827_add-apirequestExampleTable")]
partial class addapirequestExampleTable
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "8.0.0")
.HasAnnotation("Relational:MaxIdentifierLength", 64);
modelBuilder.Entity("Apimanager_backend.Models.Api", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Endpoint")
.IsRequired()
.HasColumnType("longtext");
b.Property<bool>("IsActive")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsDelete")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsThirdParty")
.HasColumnType("tinyint(1)");
b.Property<int>("Method")
.HasColumnType("int");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("varchar(200)");
b.Property<int?>("PackageId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("PackageId");
b.ToTable("Apis");
});
modelBuilder.Entity("Apimanager_backend.Models.ApiCallLog", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int>("ApiId")
.HasColumnType("int");
b.Property<int>("CallResult")
.HasColumnType("int");
b.Property<DateTime>("CallTime")
.HasColumnType("datetime(6)");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("ApiId");
b.HasIndex("UserId");
b.ToTable("CallLogs");
});
modelBuilder.Entity("Apimanager_backend.Models.ApiRequestExample", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int>("ApiId")
.HasColumnType("int");
b.Property<string>("Request")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Response")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("ResponseType")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.HasIndex("ApiId");
b.ToTable("ApiRequestExample");
});
modelBuilder.Entity("Apimanager_backend.Models.Apipackage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int>("CallLimit")
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<DateTime>("ExpiryDate")
.HasColumnType("datetime(6)");
b.Property<string>("Name")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("varchar(20)");
b.Property<int>("OneMinuteLimit")
.HasColumnType("int");
b.Property<decimal>("Price")
.HasColumnType("decimal(65,30)");
b.HasKey("Id");
b.ToTable("Apipackages");
});
modelBuilder.Entity("Apimanager_backend.Models.Log", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Exception")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("LogLevel")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Message")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("MessageTemplate")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Properties")
.IsRequired()
.HasColumnType("longtext");
b.Property<DateTime>("Timestamp")
.HasColumnType("datetime(6)");
b.HasKey("Id");
b.ToTable("Logs");
});
modelBuilder.Entity("Apimanager_backend.Models.OperationLog", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("IpAddress")
.IsRequired()
.HasMaxLength(45)
.HasColumnType("varchar(45)");
b.Property<string>("Operation")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("varchar(20)");
b.Property<int>("TargetId")
.HasColumnType("int");
b.Property<string>("TargetType")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("varchar(50)");
b.Property<string>("UserAgent")
.IsRequired()
.HasColumnType("longtext");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("OperationLogs");
});
modelBuilder.Entity("Apimanager_backend.Models.Order", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<decimal>("Amount")
.HasColumnType("decimal(65,30)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Description")
.HasColumnType("longtext");
b.Property<string>("OrderNumber")
.IsRequired()
.HasColumnType("varchar(255)");
b.Property<int>("OrderType")
.HasColumnType("int");
b.Property<int>("Status")
.HasColumnType("int");
b.Property<string>("ThirdPartyOrderId")
.HasColumnType("varchar(255)");
b.Property<DateTime>("UpdatedAt")
.HasColumnType("datetime(6)");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("OrderNumber")
.IsUnique();
b.HasIndex("ThirdPartyOrderId")
.IsUnique();
b.HasIndex("UserId");
b.ToTable("Orders");
});
modelBuilder.Entity("Apimanager_backend.Models.User", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ApiKey")
.HasColumnType("longtext");
b.Property<decimal>("Balance")
.HasColumnType("decimal(65,30)");
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Email")
.IsRequired()
.HasColumnType("varchar(255)");
b.Property<bool>("IsBan")
.HasColumnType("tinyint(1)");
b.Property<bool>("IsDelete")
.HasColumnType("tinyint(1)");
b.Property<string>("PassHash")
.IsRequired()
.HasMaxLength(255)
.HasColumnType("varchar(255)");
b.Property<string>("Username")
.IsRequired()
.HasColumnType("varchar(255)");
b.HasKey("Id");
b.HasIndex("Email")
.IsUnique();
b.HasIndex("Username")
.IsUnique();
b.ToTable("Users");
});
modelBuilder.Entity("Apimanager_backend.Models.UserPackage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int>("PackageId")
.HasColumnType("int");
b.Property<DateTime>("PurchasedAt")
.HasColumnType("datetime(6)");
b.Property<int>("RemainingCalls")
.HasColumnType("int");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("PackageId");
b.HasIndex("UserId");
b.ToTable("UserPackages");
});
modelBuilder.Entity("Apimanager_backend.Models.UserRole", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("Role")
.IsRequired()
.HasColumnType("longtext");
b.Property<int>("UserId")
.HasColumnType("int");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("UserRoles");
});
modelBuilder.Entity("Apimanager_backend.Models.Api", b =>
{
b.HasOne("Apimanager_backend.Models.Apipackage", "Package")
.WithMany("Apis")
.HasForeignKey("PackageId");
b.Navigation("Package");
});
modelBuilder.Entity("Apimanager_backend.Models.ApiCallLog", b =>
{
b.HasOne("Apimanager_backend.Models.Api", "Api")
.WithMany("ApiCalls")
.HasForeignKey("ApiId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Apimanager_backend.Models.User", "User")
.WithMany("CallLogs")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Api");
b.Navigation("User");
});
modelBuilder.Entity("Apimanager_backend.Models.ApiRequestExample", b =>
{
b.HasOne("Apimanager_backend.Models.Api", "Api")
.WithMany("ApiRequestExamples")
.HasForeignKey("ApiId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Api");
});
modelBuilder.Entity("Apimanager_backend.Models.OperationLog", b =>
{
b.HasOne("Apimanager_backend.Models.User", "User")
.WithMany("operationLogs")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Apimanager_backend.Models.Order", b =>
{
b.HasOne("Apimanager_backend.Models.User", "User")
.WithMany("Orders")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Apimanager_backend.Models.UserPackage", b =>
{
b.HasOne("Apimanager_backend.Models.Apipackage", "Package")
.WithMany("Packages")
.HasForeignKey("PackageId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Apimanager_backend.Models.User", "User")
.WithMany("Packages")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Package");
b.Navigation("User");
});
modelBuilder.Entity("Apimanager_backend.Models.UserRole", b =>
{
b.HasOne("Apimanager_backend.Models.User", "User")
.WithMany("Roles")
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("User");
});
modelBuilder.Entity("Apimanager_backend.Models.Api", b =>
{
b.Navigation("ApiCalls");
b.Navigation("ApiRequestExamples");
});
modelBuilder.Entity("Apimanager_backend.Models.Apipackage", b =>
{
b.Navigation("Apis");
b.Navigation("Packages");
});
modelBuilder.Entity("Apimanager_backend.Models.User", b =>
{
b.Navigation("CallLogs");
b.Navigation("Orders");
b.Navigation("Packages");
b.Navigation("Roles");
b.Navigation("operationLogs");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,86 @@
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace Apimanager_backend.Migrations
{
/// <inheritdoc />
public partial class addapirequestExampleTable : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.AddColumn<string>(
name: "ApiKey",
table: "Users",
type: "longtext",
nullable: true)
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<string>(
name: "Description",
table: "Apis",
type: "longtext",
nullable: false)
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.AddColumn<int>(
name: "OneMinuteLimit",
table: "Apipackages",
type: "int",
nullable: false,
defaultValue: 0);
migrationBuilder.CreateTable(
name: "ApiRequestExample",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn),
ApiId = table.Column<int>(type: "int", nullable: false),
ResponseType = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
Request = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4"),
Response = table.Column<string>(type: "longtext", nullable: false)
.Annotation("MySql:CharSet", "utf8mb4")
},
constraints: table =>
{
table.PrimaryKey("PK_ApiRequestExample", x => x.Id);
table.ForeignKey(
name: "FK_ApiRequestExample_Apis_ApiId",
column: x => x.ApiId,
principalTable: "Apis",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
})
.Annotation("MySql:CharSet", "utf8mb4");
migrationBuilder.CreateIndex(
name: "IX_ApiRequestExample_ApiId",
table: "ApiRequestExample",
column: "ApiId");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ApiRequestExample");
migrationBuilder.DropColumn(
name: "ApiKey",
table: "Users");
migrationBuilder.DropColumn(
name: "Description",
table: "Apis");
migrationBuilder.DropColumn(
name: "OneMinuteLimit",
table: "Apipackages");
}
}
}

View File

@ -28,6 +28,10 @@ namespace Apimanager_backend.Migrations
b.Property<DateTime>("CreatedAt")
.HasColumnType("datetime(6)");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Endpoint")
.IsRequired()
.HasColumnType("longtext");
@ -86,6 +90,34 @@ namespace Apimanager_backend.Migrations
b.ToTable("CallLogs");
});
modelBuilder.Entity("Apimanager_backend.Models.ApiRequestExample", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<int>("ApiId")
.HasColumnType("int");
b.Property<string>("Request")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("Response")
.IsRequired()
.HasColumnType("longtext");
b.Property<string>("ResponseType")
.IsRequired()
.HasColumnType("longtext");
b.HasKey("Id");
b.HasIndex("ApiId");
b.ToTable("ApiRequestExample");
});
modelBuilder.Entity("Apimanager_backend.Models.Apipackage", b =>
{
b.Property<int>("Id")
@ -106,6 +138,9 @@ namespace Apimanager_backend.Migrations
.HasMaxLength(20)
.HasColumnType("varchar(20)");
b.Property<int>("OneMinuteLimit")
.HasColumnType("int");
b.Property<decimal>("Price")
.HasColumnType("decimal(65,30)");
@ -246,6 +281,9 @@ namespace Apimanager_backend.Migrations
.ValueGeneratedOnAdd()
.HasColumnType("int");
b.Property<string>("ApiKey")
.HasColumnType("longtext");
b.Property<decimal>("Balance")
.HasColumnType("decimal(65,30)");
@ -357,6 +395,17 @@ namespace Apimanager_backend.Migrations
b.Navigation("User");
});
modelBuilder.Entity("Apimanager_backend.Models.ApiRequestExample", b =>
{
b.HasOne("Apimanager_backend.Models.Api", "Api")
.WithMany("ApiRequestExamples")
.HasForeignKey("ApiId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Api");
});
modelBuilder.Entity("Apimanager_backend.Models.OperationLog", b =>
{
b.HasOne("Apimanager_backend.Models.User", "User")
@ -412,6 +461,8 @@ namespace Apimanager_backend.Migrations
modelBuilder.Entity("Apimanager_backend.Models.Api", b =>
{
b.Navigation("ApiCalls");
b.Navigation("ApiRequestExamples");
});
modelBuilder.Entity("Apimanager_backend.Models.Apipackage", b =>

View File

@ -16,6 +16,10 @@ namespace Apimanager_backend.Models
[MaxLength(200)]
[Required]
public string Name { get; set; } // varchar(20)
/// <summary>
/// 描述
/// </summary>
public string Description { get; set; } = string.Empty;
/// <summary>
/// API地址
@ -55,5 +59,6 @@ namespace Apimanager_backend.Models
//导航属性
public Apipackage? Package { get; set; }
public ICollection<ApiCallLog> ApiCalls { get; set; }
public ICollection<ApiRequestExample> ApiRequestExamples { get; set; }
}
}

View File

@ -2,9 +2,9 @@
{
public enum ApiMethod
{
GET,
POST,
PUT,
DELETE
GET = 0,
POST = 1,
PUT = 2,
DELETE = 3
}
}

View File

@ -0,0 +1,16 @@
using System.ComponentModel.DataAnnotations;
namespace Apimanager_backend.Models
{
public class ApiRequestExample
{
public int Id { get; set; }
public int ApiId { get; set; }
[Required]
public string ResponseType { get; set; }
public string Request { get; set; } = string.Empty;
public string Response { get; set; } = string.Empty;
//导航属性
public Api Api { get; set; }
}
}

View File

@ -27,10 +27,11 @@ namespace Apimanager_backend.Models
/// </summary>
public decimal Price { get; set; } // decimal(10,2)
/// <summary>
/// 套餐过期时间,可用于控制套餐是否过期
/// 每分钟调用次数限制
/// </summary>
public DateTime ExpiryDate { get; set; } // timestamp
public int OneMinuteLimit { get; set; }
/// <summary>
/// 创建时间

View File

@ -45,6 +45,10 @@ namespace Apimanager_backend.Models
/// 余额
/// </summary>
public decimal Balance { get; set; } = 0; // Decimal(10)
/// <summary>
/// api调用凭证
/// </summary>
public string? ApiKey { get; set; } = null;
/// <summary>
/// 创建时间,默认当前时间

View File

@ -20,7 +20,10 @@
/// 剩余调用次数
/// </summary>
public int RemainingCalls { get; set; }
/// <summary>
/// 套餐过期时间,可用于控制套餐是否过期
/// </summary>
public DateTime ExpiryDate { get; set; } // timestamp
/// <summary>
/// 购买时间
/// </summary>

View File

@ -101,12 +101,18 @@ namespace Apimanager_backend.Services
{
throw new BaseException(2004,"用户不存在");
}
user.PassHash = dto.Password;
user.Balance = dto.Balance;
user.PassHash = dto.Password ?? user.PassHash;
user.Balance = dto.Balance ?? user.Balance;
context.Users.Update(user);
await context.SaveChangesAsync();
return mapper.Map<UserInfoDto>(user);
}
#endregion
#region
public async Task<int> UserCountAsync()
{
return await context.Users.CountAsync();
}
#endregion
}
}

View File

@ -0,0 +1,120 @@
using Apimanager_backend.Data;
using Apimanager_backend.Dtos;
using Apimanager_backend.Exceptions;
using Apimanager_backend.Models;
using AutoMapper;
using Microsoft.EntityFrameworkCore;
namespace Apimanager_backend.Services
{
public class ApiService:IApiService
{
private readonly ApiContext context;
private readonly ILogger<ApiService> logger;
private readonly IMapper mapper;
public ApiService(ApiContext context, ILogger<ApiService> logger,IMapper mapper)
{
this.context = context;
this.logger = logger;
this.mapper = mapper;
}
#region
public async Task<ApiInfoDto> AddApiAsync(CreateApiInfo dto)
{
var api = mapper.Map<Api>(dto);
context.Apis.Add(api);
await context.SaveChangesAsync();
return mapper.Map<ApiInfoDto>(api);
}
#endregion
#region api
public async Task DeleteApiAsync(int apiId)
{
var api = await context.Apis.FirstOrDefaultAsync(x => x.Id == apiId);
if (api == null)
{
throw new BaseException(3002, "API不存在");
}
api.IsDelete = true;
context.Apis.Update(api);
await context.SaveChangesAsync();
}
#endregion
#region api信息
public async Task<ApiInfoDto> GetApiInfoAsync(int apiId)
{
var apiInfo = await context.Apis.FirstOrDefaultAsync(x => x.Id == apiId);
if (apiInfo == null)
{
throw new BaseException(3002,"API不存在");
}
return mapper.Map<ApiInfoDto>(apiInfo);
}
#endregion
#region api
public async Task OffApiAsync(int apiId)
{
var api = await context.Apis.FirstOrDefaultAsync(x => x.Id == apiId);
if (api == null)
{
throw new BaseException(3002, "API不存在");
}
api.IsActive = false;
context.Apis.Update(api);
await context.SaveChangesAsync();
}
#endregion
#region API
public async Task OnApiAsync(int apiId)
{
var api = await context.Apis.FirstOrDefaultAsync(x => x.Id == apiId);
if (api == null)
{
throw new BaseException(3002, "API不存在");
}
api.IsActive = true;
context.Apis.Update(api);
await context.SaveChangesAsync();
}
#endregion
#region
public async Task<ApiInfoDto> UpdateApiAsync(int apiId, UpdateApiDto dto)
{
var api = await context.Apis.FirstOrDefaultAsync(x => x.Id == apiId);
if(api == null)
{
throw new BaseException(3002, "API不存在");
}
api.Name = dto.Name ?? api.Name;
api.Description = dto.Description ?? api.Description;
api.Endpoint = dto.Endpoint ?? api.Endpoint;
api.Method = dto.Method ?? api.Method;
api.PackageId = dto.PackageId ?? api.PackageId;
context.Apis.Update(api);
await context.SaveChangesAsync();
return mapper.Map<ApiInfoDto>(api);
}
#endregion
#region API列表
public async Task<List<ApiInfoDto>> GetApisAsync(int pageIndex, int pageSize, bool desc)
{
IQueryable<Api> query = context.Apis.Where(x => true).OrderBy(x => x.Id);
//倒序
if (desc)
{
query.OrderDescending();
}
//分页
query = query.Skip((pageIndex - 1) * pageSize).Take(pageSize);
var list = await query.ToListAsync();
return mapper.Map<List<ApiInfoDto>>(list);
}
#endregion
#region Api总数
public async Task<int> ApiCountAsync()
{
return await context.Apis.CountAsync();
}
#endregion
}
}

View File

@ -41,5 +41,10 @@ namespace Apimanager_backend.Services
/// </summary>
/// <returns></returns>
Task<UserInfoDto> UpdateUserAsync(int userId, AdminUpdateUserDto dto);
/// <summary>
/// 用户总数
/// </summary>
/// <returns></returns>
Task<int> UserCountAsync();
}
}

View File

@ -0,0 +1,60 @@
using Apimanager_backend.Dtos;
namespace Apimanager_backend.Services
{
public interface IApiService
{
/// <summary>
/// 获取api信息
/// </summary>
/// <param name="apiId"></param>
/// <returns></returns>
public Task<ApiInfoDto> GetApiInfoAsync(int apiId);
/// <summary>
/// 添加api
/// </summary>
/// <param name="apiId"></param>
/// <param name="dto"></param>
/// <returns></returns>
public Task<ApiInfoDto> AddApiAsync(CreateApiInfo dto);
/// <summary>
/// 删除api
/// </summary>
/// <param name="apiId"></param>
/// <returns></returns>
public Task DeleteApiAsync(int apiId);
/// <summary>
/// 更新api信息
/// </summary>
/// <param name="apiId"></param>
/// <param name="dto"></param>
/// <returns></returns>
public Task<ApiInfoDto> UpdateApiAsync(int apiId,UpdateApiDto dto);
/// <summary>
/// 启用
/// </summary>
/// <param name="apiId"></param>
/// <returns></returns>
public Task OnApiAsync(int apiId);
/// <summary>
/// 禁用
/// </summary>
/// <param name="apiId"></param>
/// <returns></returns>
public Task OffApiAsync(int apiId);
/// <summary>
/// 获取APi列表
/// </summary>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="desc"></param>
/// <returns></returns>
public Task<List<ApiInfoDto>> GetApisAsync(int pageIndex, int pageSize, bool desc);
/// <summary>
/// 获取api数量
/// </summary>
/// <returns></returns>
public Task<int> ApiCountAsync();
}
}

View File

@ -0,0 +1,43 @@
using Apimanager_backend.Dtos;
namespace Apimanager_backend.Services
{
public interface IPackageService
{
/// <summary>
/// 添加套餐
/// </summary>
/// <param name="addPackageDto"></param>
/// <returns></returns>
public Task<PackageInfoDto> AddPackageAsync(AddPackageDto addPackageDto);
/// <summary>
/// 更新套餐信息
/// </summary>
/// <param name="packageId"></param>
/// <param name="updatePackageDto"></param>
/// <returns></returns>
public Task<PackageInfoDto> UpdatePackageAsync(int packageId,UpdatePackageDto updatePackageDto);
/// <summary>
/// 删除套餐
/// </summary>
/// <param name="packageId"></param>
/// <returns></returns>
public Task DeletePackageAsync(int packageId);
/// <summary>
/// 获取套餐列表
/// </summary>
/// <param name="pageIndex"></param>
/// <param name="pageSize"></param>
/// <param name="desc"></param>
/// <returns></returns>
public Task<List<PackageInfoDto>> GetAllPackagesAsync(int pageIndex,int pageSize,bool desc);
/// <summary>
/// 获取套餐信息
/// </summary>
/// <param name="packageId"></param>
/// <returns></returns>
public Task<PackageInfoDto> PackageInfoByIdAsync(int packageId);
}
}