.Net6 + GraphQL + MongoDb 项目搭建
介绍
讲一下GraphQL的各种特性和如何使用,让大家感受下。
CODE4NOTHING大佬之前在博客园更新了一些GraphQL的知识是和EF的结合使用,文章使用的实体模型来自于CODE4NOTHING大佬。
本节主要将项目的结构简单搭建下
正文
新建一个空的.Net6 项目,不需要引入Swagger, 项目引入一下库,我们使用的MongoDb来做持久化
<ItemGroup>
<PackageReference Include="GraphQL.Server.Ui.Voyager" Version="7.1.1" />
<PackageReference Include="HotChocolate.AspNetCore" Version="12.15.0" />
<PackageReference Include="HotChocolate.Data" Version="12.15.0" />
<PackageReference Include="HotChocolate.Data.MongoDb" Version="12.15.0" />
<PackageReference Include="MongoDB.Driver" Version="2.19.0" />
<PackageReference Include="MongoDB.Driver.Core" Version="2.19.0" />
</ItemGroup>
为了接下来方便使用MongoDb我们先做一下简单封装,新建Db文件夹存放
public class DatabaseSettings
{
public string ConnectionString { get; set; } = null!;
public string DatabaseName { get; set; } = null!;
}
public class BaseDbContext
{
public BaseDbContext(IOptions<DatabaseSettings> bookStoreDatabaseSettings)
{
var mongoConnectionUrl = new MongoUrl(bookStoreDatabaseSettings.Value.ConnectionString);
var mongoClientSettings = MongoClientSettings.FromUrl(mongoConnectionUrl);
mongoClientSettings.ClusterConfigurator = cb => {
cb.Subscribe<CommandStartedEvent>(e => {
Console.WriteLine($"{e.CommandName} - {e.Command.ToJson()}");
});
};
Client = new MongoClient(
mongoClientSettings);
Database = Client.GetDatabase(
bookStoreDatabaseSettings.Value.DatabaseName);
}
/// <summary>
/// MongoClient
/// </summary>
public IMongoClient Client { get; private set; } = default!;
public IMongoDatabase Database { get; private set; } = default!;
}
public class DbContext : BaseDbContext
{
/// <summary>
///
/// </summary>
public IMongoCollection<Post> Post => Database.GetCollection<Post>("post");
public IMongoCollection<Comment> Comments => Database.GetCollection<Comment>("Comment");
public DbContext(IOptions<DatabaseSettings> bookStoreDatabaseSettings) : base(bookStoreDatabaseSettings)
{
}
}
appsetting.json
加上数据库链接
"DatabaseSettings": {
"ConnectionString": "mongodb://localhost:27017",
"DatabaseName": "GQL_Example"
},
新建Post和Comment实体, 新建Model文件夹存放
public class Post
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public string Abstraction { get; set; }
public string Content { get; set; }
public string Link { get; set; }
public DateTime PublishedAt { get; set; }
public IReadOnlyList<Comment> Comments { get; init; }
}
public class Comment
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string? Id { get; set; }
public string? Content { get; set; }
public string? Name { get; set; }
public DateTime CreatedAt { get; set; }
}
初始化Program
using Gql.EmptyExample;
using Gql.EmptyExample.Posts.Core.Domain;
using GraphQL.Server.Ui.Voyager;
using HotChocolate.Types.Pagination;
using MongoDB.Bson;
var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<DatabaseSettings>(
builder.Configuration.GetSection("DatabaseSettings"));
builder.Services.AddSingleton<DbContext>();
builder.Services
.AddGraphQLServer();
// Add services to the container.
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseRouting().UseEndpoints(endpoints =>
{
endpoints.MapGraphQL();
});
app.UseGraphQLVoyager("/graphql-voyager", new VoyagerOptions { GraphQLEndPoint = "/graphql" });
}
// Configure the HTTP request pipeline.
app.UseHttpsRedirection();
app.Run();
结语
本系列主要将GraphQL的使用,示例项目不能应用于生产,后续发一些GraphQL库出来讲解生产中的实际应用
联系作者:加群:867095512 @MrChuJiu