-
Notifications
You must be signed in to change notification settings - Fork 0
/
ProductsController.cs
83 lines (67 loc) · 2.4 KB
/
ProductsController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
using MassTransit;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Model;
using Nest;
namespace products;
[ApiController]
[Route("[controller]")]
public class ProductsController : ControllerBase
{
private readonly ProductsContext _context;
private readonly IElasticClient _elasticClient;
private readonly IBusControl _busControl;
public ProductsController(ProductsContext context, IElasticClient elasticClient, IBusControl busControl)
{
_context = context;
_elasticClient = elasticClient;
_busControl = busControl;
}
[HttpGet]
public IEnumerable<Product> Get(int page = 1, int size = 10)
{
return _context.Products
.AsNoTracking()
.OrderBy(x => x.Id)
.Skip((page - 1) * size)
.Take(size);
}
[HttpGet("search/{query}")]
public async Task<IEnumerable<Product>> Search(string query, int page = 1, int size = 10)
{
var response = await _elasticClient
.SearchAsync<Product>(x => x
.From((page - 1) * size)
.Size(size)
.Query(q => q
.MultiMatch(m => m
.Fields(f => f
.Field("name")
.Field("description")
)
.Query(query)
.Fuzziness(Fuzziness.Auto)
)));
return response.Documents;
}
[HttpPost]
public async Task Post(ProductModel model)
{
var newProduct = new Product(model.Name, model.Description, model.Price);
await _context.Products.AddAsync(newProduct);
await _context.SaveChangesAsync();
await _busControl.Publish(newProduct);
}
[HttpPut("{id}")]
public async Task Put(int id, ProductModel model)
{
var product = await _context.Products.FirstOrDefaultAsync(x => x.Id == id);
if (product == null)
throw new ArgumentException("product not found");
product.Name = model.Name;
product.Description = model.Description;
product.Price = model.Price;
await _context.SaveChangesAsync();
await _busControl.Publish(product);
}
}