aboutsummaryrefslogtreecommitdiff
path: root/Emails.Transactional.Client/ClientExtensions.cs
blob: 3246b9f9830aa003c1418735f65cfe2daada633e (plain)
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
using System;

using System.Net;
using System.Threading;
using System.Threading.Tasks;

using Emails.Transactional.Client.Exceptions;

using RestSharp;

namespace Emails.Transactional.Client
{
    /// <summary>
    /// Contains extension methods to send emails on remote transational email servers
    /// </summary>
    public static class ClientExtensions
    {
        private const Method DEFAULT_SEND_METHOD = Method.Post;
      
        /// <summary>
        /// Asynchronously begins an email transaction against the mail server with the specified
        /// transaction request.
        /// </summary>
        /// <param name="client"></param>
        /// <param name="transaction">The <see cref="EmailTransactionRequest"/> to submit</param>
        /// <param name="token">A cancelaion token to cancel the operation</param>
        /// <returns>A task that represents the async send operation</returns>
        /// <exception cref="ValidationFailedException"></exception>
        /// <exception cref="InvalidAuthorizationException"></exception>
        /// <exception cref="InvalidTransactionRequestException"></exception>
        /// <exception cref="InvalidTransactionResponseException"></exception>
        public static async Task<TransactionResult> SendEmailAsync(this RestClient client, EmailTransactionRequest transaction, CancellationToken token = default)
        {
            //Init the new request
            RestRequest request = new(transaction.Endpoint, DEFAULT_SEND_METHOD)
            {
                //Json request
                RequestFormat = DataFormat.Json
            };
            //add/serialze the transacion request
            request.AddJsonBody(transaction);
            //Exec the tranasction on the client
            RestResponse<TransactionResult> response = await client.ExecuteAsync<TransactionResult>(request, token);
            //parse the response body
            return response.StatusCode switch
            {
                HttpStatusCode.Unauthorized or HttpStatusCode.Forbidden => throw new InvalidAuthorizationException("The server did not accept the current authorization", response),
                HttpStatusCode.BadRequest => throw new InvalidTransactionRequestException(response),
                HttpStatusCode.UnprocessableEntity => throw new ValidationFailedException(response.Data),
                HttpStatusCode.OK => response.Data,
                _ => throw new InvalidTransactionResponseException("Unhandled status code", response),
            };
        }
    }
}