.NET 云原生架构师训练营(模块二 基础巩固 MongoDB API重构)--学习笔记

简介: - Lighter.Domain- Lighter.Application.Contract- Lighter.Application- LighterApi- Lighter.Application.Tests

2.5.8 MongoDB -- API重构

  • Lighter.Domain
  • Lighter.Application.Contract
  • Lighter.Application
  • LighterApi
  • Lighter.Application.Tests

Lighter.Domain

将数据实体转移到 Lighter.Domain 层

36.jpg

Lighter.Application.Contract

将业务从controller 抽取到 Lighter.Application 层,并为业务建立抽象接口 Lighter.Application.Contract层

37.jpg

IQuestionService

namespace Lighter.Application.Contracts
{
    public interface IQuestionService
    {
        Task<Question> GetAsync(string id, CancellationToken cancellationToken);
        Task<QuestionAnswerReponse> GetWithAnswerAsync(string id, CancellationToken cancellationToken);
        Task<List<Question>> GetListAsync(List<string> tags, CancellationToken cancellationToken, string sort = "createdAt", int skip = 0, int limit = 10);
        Task<Question> CreateAsync(Question question, CancellationToken cancellationToken);
        Task UpdateAsync(string id, QuestionUpdateRequest request, CancellationToken cancellationToken);
        Task<Answer> AnswerAsync(string id, AnswerRequest request, CancellationToken cancellationToken);
        Task CommentAsync(string id, CommentRequest request, CancellationToken cancellationToken);
        Task UpAsync(string id, CancellationToken cancellationToken);
        Task DownAsync(string id, CancellationToken cancellationToken);
    }
}

Lighter.Application

实现业务接口

38.jpg

QuestionService

namespace Lighter.Application
{
    public class QuestionService : IQuestionService
    {
        private readonly IMongoCollection<Question> _questionCollection;
        private readonly IMongoCollection<Vote> _voteCollection;
        private readonly IMongoCollection<Answer> _answerCollection;

        public QuestionService(IMongoClient mongoClient)
        {
            var database = mongoClient.GetDatabase("lighter");

            _questionCollection = database.GetCollection<Question>("questions");
            _voteCollection = database.GetCollection<Vote>("votes");
            _answerCollection = database.GetCollection<Answer>("answers");
        }

        public async Task<Question> GetAsync(string id, CancellationToken cancellationToken)
        {
            // linq 查询
            var question = await _questionCollection.AsQueryable()
                .FirstOrDefaultAsync(q => q.Id == id, cancellationToken: cancellationToken);

            //// mongo 查询表达式
            ////var filter = Builders<Question>.Filter.Eq(q => q.Id, id);

            //// 构造空查询条件的表达式
            //var filter = string.IsNullOrEmpty(id)
            //    ? Builders<Question>.Filter.Empty
            //    : Builders<Question>.Filter.Eq(q => q.Id, id);

            //// 多段拼接 filter
            //var filter2 = Builders<Question>.Filter.And(filter, Builders<Question>.Filter.Eq(q => q.TenantId, "001"));
            //await _questionCollection.Find(filter).FirstOrDefaultAsync(cancellationToken);

            return question;
        }

        public async Task<List<Question>> GetListAsync(List<string> tags, CancellationToken cancellationToken, string sort = "createdAt", int skip = 0, int limit = 10)
        {
            //// linq 查询
            //await _questionCollection.AsQueryable().Where(q => q.ViewCount > 10)
            //    .ToListAsync(cancellationToken: cancellationToken);

            var filter = Builders<Question>.Filter.Empty;

            if (tags != null && tags.Any())
            {
                filter = Builders<Question>.Filter.AnyIn(q => q.Tags, tags);
            }

            var sortDefinition = Builders<Question>.Sort.Descending(new StringFieldDefinition<Question>(sort));

            var result = await _questionCollection
                .Find(filter)
                .Sort(sortDefinition)
                .Skip(skip)
                .Limit(limit)
                .ToListAsync(cancellationToken: cancellationToken);

            return result;
        }

        public async Task<QuestionAnswerReponse> GetWithAnswerAsync(string id, CancellationToken cancellationToken)
        {
            // linq 查询
            var query = from question in _questionCollection.AsQueryable()
                where question.Id == id
                join a in _answerCollection.AsQueryable() on question.Id equals a.QuestionId into answers
                select new { question, answers };

            var result = await query.FirstOrDefaultAsync(cancellationToken);

            //// mongo 查询表达式
            //var result = await _questionCollection.Aggregate()
            //    .Match(q => q.Id == id)
            //    .Lookup<Answer, QuestionAnswerReponse>(
            //        foreignCollectionName: "answers",
            //        localField: "answers",
            //        foreignField: "questionId",
            //        @as: "AnswerList")
            //    .FirstOrDefaultAsync(cancellationToken: cancellationToken);

            return new QuestionAnswerReponse {AnswerList = result.answers};
        }

        public async Task<Answer> AnswerAsync(string id, AnswerRequest request, CancellationToken cancellationToken)
        {
            var answer = new Answer { QuestionId = id, Content = request.Content, Id = Guid.NewGuid().ToString() };
            _answerCollection.InsertOneAsync(answer, cancellationToken);

            var filter = Builders<Question>.Filter.Eq(q => q.Id, id);
            var update = Builders<Question>.Update.Push(q => q.Answers, answer.Id);

            await _questionCollection.UpdateOneAsync(filter, update, null, cancellationToken);

            return answer;
        }

        public async Task CommentAsync(string id, CommentRequest request, CancellationToken cancellationToken)
        {
            var filter = Builders<Question>.Filter.Eq(q => q.Id, id);
            var update = Builders<Question>.Update.Push(q => q.Comments,
                new Comment { Content = request.Content, CreatedAt = DateTime.Now });

            await _questionCollection.UpdateOneAsync(filter, update, null, cancellationToken);
        }

        public async Task<Question> CreateAsync(Question question, CancellationToken cancellationToken)
        {
            question.Id = Guid.NewGuid().ToString();
            await _questionCollection.InsertOneAsync(question, new InsertOneOptions { BypassDocumentValidation = false },
                cancellationToken);
            return question;
        }

        public async Task DownAsync(string id, CancellationToken cancellationToken)
        {
            var vote = new Vote
            {
                Id = Guid.NewGuid().ToString(),
                SourceType = ConstVoteSourceType.Question,
                SourceId = id,
                Direction = EnumVoteDirection.Down
            };

            await _voteCollection.InsertOneAsync(vote, cancellationToken);

            var filter = Builders<Question>.Filter.Eq(q => q.Id, id);
            var update = Builders<Question>.Update.Inc(q => q.VoteCount, -1).AddToSet(q => q.VoteDowns, vote.Id);
            await _questionCollection.UpdateOneAsync(filter, update);
        }

        public async Task UpAsync(string id, CancellationToken cancellationToken)
        {
            var vote = new Vote
            {
                Id = Guid.NewGuid().ToString(),
                SourceType = ConstVoteSourceType.Question,
                SourceId = id,
                Direction = EnumVoteDirection.Up
            };

            await _voteCollection.InsertOneAsync(vote, cancellationToken);

            var filter = Builders<Question>.Filter.Eq(q => q.Id, id);
            var update = Builders<Question>.Update.Inc(q => q.VoteCount, 1).AddToSet(q => q.VoteUps, vote.Id);
            await _questionCollection.UpdateOneAsync(filter, update);
        }

        public async Task UpdateAsync(string id, QuestionUpdateRequest request, CancellationToken cancellationToken)
        {
            var filter = Builders<Question>.Filter.Eq(q => q.Id, id);

            //var update = Builders<Question>.Update
            //    .Set(q => q.Title, request.Title)
            //    .Set(q => q.Content, request.Content)
            //    .Set(q => q.Tags, request.Tags)
            //    .Push(q => q.Comments, new Comment {Content = request.Summary, CreatedAt = DateTime.Now});

            var updateFieldList = new List<UpdateDefinition<Question>>();

            if (!string.IsNullOrWhiteSpace(request.Title))
                updateFieldList.Add(Builders<Question>.Update.Set(q => q.Title, request.Title));

            if (!string.IsNullOrWhiteSpace(request.Content))
                updateFieldList.Add(Builders<Question>.Update.Set(q => q.Content, request.Content));

            if (request.Tags != null && request.Tags.Any())
                updateFieldList.Add(Builders<Question>.Update.Set(q => q.Tags, request.Tags));

            updateFieldList.Add(Builders<Question>.Update.Push(q => q.Comments,
                new Comment { Content = request.Summary, CreatedAt = DateTime.Now }));

            var update = Builders<Question>.Update.Combine(updateFieldList);

            await _questionCollection.UpdateOneAsync(filter, update, cancellationToken: cancellationToken);
        }
    }
}

LighterApi

注册服务

Startup

services.AddScoped<IQuestionService, QuestionService>()
        .AddScoped<IAnswerService, AnswerService>();

调用服务

QuestionController

namespace LighterApi.Controller
{
    [ApiController]
    [Route("api/[controller]")]
    public class QuestionController : ControllerBase
    {
        private readonly IQuestionService _questionService;

        public QuestionController(IQuestionService questionService)
        {
            _questionService = questionService;
        }

        [HttpGet]
        [Route("{id}")]
        public async Task<ActionResult<Question>> GetAsync(string id, CancellationToken cancellationToken)
        {
            var question = await _questionService.GetAsync(id, cancellationToken);

            if (question == null)
                return NotFound();

            return Ok(question);
        }

        [HttpGet]
        [Route("{id}/answers")]
        public async Task<ActionResult> GetWithAnswerAsync(string id, CancellationToken cancellationToken)
        {
            var result = await _questionService.GetWithAnswerAsync(id, cancellationToken);

            if (result == null)
                return NotFound();

            return Ok(result);
        }

        [HttpGet]
        public async Task<ActionResult<List<Question>>> GetListAsync([FromQuery] List<string> tags,
            CancellationToken cancellationToken, [FromQuery] string sort = "createdAt", [FromQuery] int skip = 0,
            [FromQuery] int limit = 10)
        {
            var result = await _questionService.GetListAsync(tags, cancellationToken, sort, skip, limit);
            return Ok(result);
        }

        [HttpPost]
        public async Task<ActionResult<Question>> CreateAsync([FromBody] Question question, CancellationToken cancellationToken)
        {
            question = await _questionService.CreateAsync(question, cancellationToken);
            return StatusCode((int) HttpStatusCode.Created, question);
        }

        [HttpPatch]
        [Route("{id}")]
        public async Task<ActionResult> UpdateAsync([FromRoute] string id, [FromBody] QuestionUpdateRequest request, CancellationToken cancellationToken)
        {
            if (string.IsNullOrEmpty(request.Summary))
                throw new ArgumentNullException(nameof(request.Summary));

            await _questionService.UpdateAsync(id, request, cancellationToken);
            return Ok();
        }

        [HttpPost]
        [Route("{id}/answer")]
        public async Task<ActionResult<Answer>> AnswerAsync([FromRoute] string id, [FromBody] AnswerRequest request, CancellationToken cancellationToken)
        {
            var answer = await _questionService.AnswerAsync(id, request, cancellationToken);
            return Ok(answer);
        }

        [HttpPost]
        [Route("{id}/comment")]
        public async Task<ActionResult> CommentAsync([FromRoute] string id, [FromBody] CommentRequest request, CancellationToken cancellationToken)
        {
            await _questionService.CommentAsync(id, request, cancellationToken);
            return Ok();
        }

        [HttpPost]
        [Route("{id}/up")]
        public async Task<ActionResult> UpAsync([FromBody] string id, CancellationToken cancellationToken)
        {
            await _questionService.UpAsync(id, cancellationToken);
            return Ok();
        }

        [HttpPost]
        [Route("{id}/down")]
        public async Task<ActionResult> DownAsync([FromBody] string id, CancellationToken cancellationToken)
        {
            await _questionService.DownAsync(id, cancellationToken);
            return Ok();
        }
    }
}

Lighter.Application.Tests

建立单元测试项目,测试Lihgter.Application(需要使用到xunit、Mongo2go)

39.jpg

Mongo2go:内存级别引擎

访问 Mongo 内存数据库

SharedFixture

namespace Lighter.Application.Tests
{
    public class SharedFixture:IAsyncLifetime
    {
        private MongoDbRunner _runner;
        public MongoClient Client { get; private set; }
        public IMongoDatabase Database { get; private set; }

        public async Task InitializeAsync()
        {
            _runner = MongoDbRunner.Start();
            Client = new MongoClient(_runner.ConnectionString);
            Database = Client.GetDatabase("db");

            //var hostBuilder = Program.CreateWebHostBuilder(new string[0]);
            //var host = hostBuilder.Build();
            //ServiceProvider = host.Services;
        }

        public Task DisposeAsync()
        {
            _runner?.Dispose();
            _runner = null;
            return Task.CompletedTask;
        }
    }
}

QuestionServiceTests

namespace Lighter.Application.Tests
{

    [Collection(nameof(SharedFixture))]
    public class QuestionServiceTests
    {
        private readonly SharedFixture _fixture;

        private readonly QuestionService _questionService;
        public QuestionServiceTests(SharedFixture fixture)
        {
            _fixture = fixture;
            _questionService = new QuestionService(_fixture.Client);
        }

        private async Task<Question> CreateOrGetOneQuestionWithNoAnswerAsync()
        {
            var collection = _fixture.Database.GetCollection<Question>("question");
            var filter = Builders<Question>.Filter.Size(q => q.Answers, 0);
            var question = await collection.Find(filter).FirstOrDefaultAsync();

            if (question != null)
                return question;

            question = new Question { Title = "问题一" };
            return await _questionService.CreateAsync(question, CancellationToken.None);
        }

        private async Task<QuestionAnswerReponse> CreateOrGetOneQuestionWithAnswerAsync()
        {
            var collection = _fixture.Database.GetCollection<Question>("question");
            var filter = Builders<Question>.Filter.SizeGt(q => q.Answers, 0);
            var question = await collection.Find(filter).FirstOrDefaultAsync();

            if (question != null)
                return await _questionService.GetWithAnswerAsync(question.Id, CancellationToken.None);

            // 不存在则创建一个没有回答的问题,再添加一个答案
            question = await CreateOrGetOneQuestionWithNoAnswerAsync();
            var answer = new AnswerRequest { Content = "问题一的回答一" };
            await _questionService.AnswerAsync(question.Id, answer, CancellationToken.None);

            return await _questionService.GetWithAnswerAsync(question.Id, CancellationToken.None);
        }

        [Fact]
        public async Task GetAsync_WrongId_ShoudReturnNull()
        {
            var result = await _questionService.GetAsync("empty", CancellationToken.None);
            result.Should().BeNull();
        }

        [Fact]
        public async Task CreateAsync_Right_ShouldBeOk()
        {
            var question = await CreateOrGetOneQuestionWithNoAnswerAsync();
            question.Should().NotBeNull();

            var result = await _questionService.GetAsync(question.Id, CancellationToken.None);
            question.Title.Should().Be(result.Title);
        }

        [Fact]
        public async Task AnswerAsync_Right_ShouldBeOk()
        {
            var question = await CreateOrGetOneQuestionWithNoAnswerAsync();
            question.Should().NotBeNull();

            var answer = new AnswerRequest { Content = "问题一的回答一" };
            await _questionService.AnswerAsync(question.Id, answer, CancellationToken.None);

            var questionWithAnswer = await _questionService.GetWithAnswerAsync(question.Id, CancellationToken.None);

            questionWithAnswer.Should().NotBeNull();
            questionWithAnswer.AnswerList.Should().NotBeEmpty();
            questionWithAnswer.AnswerList.First().Content.Should().Be(answer.Content);
        }

        [Fact]
        public async Task UpAsync_Right_ShouldBeOk()
        {
            var before = await CreateOrGetOneQuestionWithNoAnswerAsync();
            await _questionService.UpAsync(before.Id, CancellationToken.None);

            var after = await _questionService.GetAsync(before.Id, CancellationToken.None);
            after.Should().NotBeNull();
            after.VoteCount.Should().Be(before.VoteCount+1);
            after.VoteUps.Count.Should().Be(1);
        }

        [Fact]
        public async Task DownAsync_Right_ShouldBeOk()
        {
            var before = await CreateOrGetOneQuestionWithNoAnswerAsync();
            await _questionService.DownAsync(before.Id, CancellationToken.None);

            var after = await _questionService.GetAsync(before.Id, CancellationToken.None);
            after.Should().NotBeNull();
            after.VoteCount.Should().Be(before.VoteCount-1);
            after.VoteDowns.Count.Should().Be(1);
        }

        public async Task UpdateAsync_WithNoSummary_ShoudThrowException()
        {
            var before = await CreateOrGetOneQuestionWithNoAnswerAsync();
            var updateRequest = new QuestionUpdateRequest { Title = before.Title + "-updated" };
            await _questionService.UpdateAsync(before.Id, updateRequest, CancellationToken.None);

            var after = await _questionService.GetAsync(before.Id, CancellationToken.None);
            after.Should().NotBeNull();
            after.Title.Should().Be(updateRequest.Title);
        }

        [Fact]
        public async Task UpdateAsync_Right_ShoudBeOk()
        {
            var before = await CreateOrGetOneQuestionWithNoAnswerAsync();
            var updateRequest = new QuestionUpdateRequest { Title = before.Title + "-updated", Summary ="summary" };
            await _questionService.UpdateAsync(before.Id, updateRequest , CancellationToken.None);

            var after = await _questionService.GetAsync(before.Id, CancellationToken.None);
            after.Should().NotBeNull();
            after.Title.Should().Be(updateRequest.Title);
        }

        [Fact]
        public async Task UpdateAsync_Right_CommentsShouldAppend()
        {
            var before = await CreateOrGetOneQuestionWithNoAnswerAsync();
            var updateRequest = new QuestionUpdateRequest { Title = before.Title + "-updated", Summary = "summary" };
            await _questionService.UpdateAsync(before.Id, updateRequest, CancellationToken.None);

            var after = await _questionService.GetAsync(before.Id, CancellationToken.None);
            after.Comments.Should().NotBeEmpty();
            after.Comments.Count.Should().Be(before.Comments.Count+1);
        }
    }
}

运行单元测试

40.jpg

GitHub源码链接:

https://github.com/MINGSON666/Personal-Learning-Library/tree/main/ArchitectTrainingCamp

目录
相关文章
|
Java API 数据处理
Java新特性:使用Stream API重构你的数据处理
Java新特性:使用Stream API重构你的数据处理
|
人工智能 监控 API
API即生产力:电商行业如何用“数字接口”重构竞争壁垒?
电商API作为连接平台、商家、物流与支付的“数字钥匙”,正系统性破解数据孤岛、运营低效、决策滞后与体验断层等传统电商痛点。通过数据实时同步、流程自动化、智能分析与服务闭环,API助力企业提升效率、优化决策、增强用户体验,并推动全行业向智能化、数字化跃迁。
|
存储 NoSQL 前端开发
【赵渝强老师】MongoDB的分布式存储架构
MongoDB分片通过将数据分布到多台服务器,实现海量数据的高效存储与读写。其架构包含路由、配置服务器和分片服务器,支持水平扩展,结合复制集保障高可用性,适用于大规模生产环境。
892 1
|
JavaScript 前端开发 IDE
[译] 用 Typescript + Composition API 重构 Vue 3 组件
[译] 用 Typescript + Composition API 重构 Vue 3 组件
[译] 用 Typescript + Composition API 重构 Vue 3 组件
|
安全 API 区块链
数据资产化新范式:API如何重构企业增长逻辑?
在数字经济时代,数据已成为企业核心资产,而API作为连接数据与业务的桥梁,正驱动企业释放数据价值、实现业务增长。本文通过电商、金融、医疗与政务领域的典型案例,解析API如何助力企业提升效率、优化服务、拓展生态,并探讨其商业价值实现路径与未来趋势。
数据资产化新范式:API如何重构企业增长逻辑?
|
供应链 API 区块链
从库存周转率提升30%看京东API如何重构供应链效率
京东API分类全景图展示了其从商品管理到生态协同的技术中台架构,涵盖商品、交易、供应链及家政服务等多维度接口,助力电商数字化转型。
|
自然语言处理 搜索推荐 API
API即竞争力:电商平台的“数字底座”如何重构行业规则?
电商API正成为电商平台转型升级的核心驱动力。面对运营效率低、用户体验差、数据孤岛、生态协同难等挑战,API通过自动化流程、数据打通、智能决策和开放生态,全面重构电商竞争力。从订单管理到智能推荐,从跨境支付到合规安全,API已渗透至商业全链路,推动平台迈向数字化、智能化、生态化新阶段。未来,电商API不仅是技术接口,更是商业模式创新和生态话语权的关键。
|
人工智能 自然语言处理 搜索推荐
一“键”链接信任与交易:API如何重构社交电商价值链?
社交电商崛起,内容与交易融合成为增长关键。API接口作为核心技术,连接内容、交易、物流与支付,推动“种草-拔草”闭环高效运转。本文解析API如何赋能社交电商,实现数据同步、智能推荐与风控,并探讨其未来趋势。
|
供应链 安全 搜索推荐
一“键”链接全球:API如何重构跨境电商效率体系?
本文探讨API接口如何助力独立站转型跨境电商,通过商品、支付、物流等环节的全球协同,打破信息孤岛,提升运营效率与用户体验,构建高效合规的全球化业务体系。
|
存储 NoSQL MongoDB
.NET MongoDB数据仓储和工作单元模式封装
.NET MongoDB数据仓储和工作单元模式封装
404 15

推荐镜像

更多