1
+ using Dapper ;
2
+ using Discount . API . Entities ;
3
+ using Npgsql ;
4
+
5
+ namespace Discount . API . Repositories
6
+ {
7
+ public class DiscountRepository : IDiscountRepository
8
+ {
9
+ private readonly IConfiguration _configuration ;
10
+
11
+ public DiscountRepository ( IConfiguration configuration )
12
+ {
13
+ _configuration = configuration ;
14
+ }
15
+
16
+ public async Task < Coupon > GetDiscount ( string productName )
17
+ {
18
+ using var connection = new NpgsqlConnection
19
+ ( _configuration . GetValue < string > ( "DatabaseSettings:ConnectionString" ) ) ;
20
+
21
+ var coupon = await connection . QueryFirstOrDefaultAsync < Coupon >
22
+ ( "SELECT * FROM Coupon WHERE ProductName = @ProductName" , new { ProductName = productName } ) ;
23
+
24
+ if ( coupon == null )
25
+ return new Coupon
26
+ {
27
+ ProductName = "No Discount" ,
28
+ Amount = 0 ,
29
+ Description = "No Discount Desc"
30
+ } ;
31
+
32
+ return coupon ;
33
+ }
34
+
35
+ public async Task < bool > CreateDiscount ( Coupon coupon )
36
+ {
37
+ using var connection = new NpgsqlConnection
38
+ ( _configuration . GetValue < string > ( "DatabaseSettings:ConnectionString" ) ) ;
39
+
40
+ var affected =
41
+ await connection . ExecuteAsync
42
+ ( "INSERT INTO Coupon (ProductName, Description, Amount) VALUES (@ProductName, @Description, @Amount)" ,
43
+ new { ProductName = coupon . ProductName , Description = coupon . Description , Amount = coupon . Amount } ) ;
44
+
45
+ if ( affected == 0 )
46
+ return false ;
47
+
48
+ return true ;
49
+ }
50
+
51
+ public async Task < bool > UpdateDiscount ( Coupon coupon )
52
+ {
53
+ using var connection = new NpgsqlConnection ( _configuration . GetValue < string > ( "DatabaseSettings:ConnectionString" ) ) ;
54
+
55
+ var affected = await connection . ExecuteAsync
56
+ ( "UPDATE Coupon SET ProductName=@ProductName, Description = @Description, Amount = @Amount WHERE Id = @Id" ,
57
+ new { ProductName = coupon . ProductName , Description = coupon . Description , Amount = coupon . Amount , Id = coupon . Id } ) ;
58
+
59
+ if ( affected == 0 )
60
+ return false ;
61
+
62
+ return true ;
63
+ }
64
+
65
+ public async Task < bool > DeleteDiscount ( string productName )
66
+ {
67
+ using var connection = new NpgsqlConnection ( _configuration . GetValue < string > ( "DatabaseSettings:ConnectionString" ) ) ;
68
+
69
+ var affected = await connection . ExecuteAsync ( "DELETE FROM Coupon WHERE ProductName = @ProductName" ,
70
+ new { ProductName = productName } ) ;
71
+
72
+ if ( affected == 0 )
73
+ return false ;
74
+
75
+ return true ;
76
+ }
77
+ }
78
+ }
0 commit comments