1+ import { errorWithCode , logger } from '@bcgov/nodejs-common-utils' ;
2+ import axios from "axios" ;
3+
4+ export class Mailer {
5+
6+ constructor ( authenticaitonURL = process . env . CHES_AUTHENTICATION_URL , emailServiceURL = process . env . CHES_EMAIL_SERVICE_URL , clientId = process . env . CHES_CLIENT_ID , clientSecret = process . env . CHES_CLIENT_SECRET , enabled = process . env . CHES_ENABLED ) {
7+ this . authenticationURL = authenticaitonURL ;
8+ this . emailServiceURL = emailServiceURL ;
9+ this . clientId = clientId ;
10+ this . clientSecret = clientSecret ;
11+ this . enabled = enabled ;
12+ }
13+
14+ async getBearerToken ( ) {
15+ const tokenEndpoint = `${ this . authenticationURL } /auth/realms/comsvcauth/protocol/openid-connect/token`
16+ const credentials = Buffer . from ( `${ this . clientId } :${ this . clientSecret } ` ) . toString ( 'base64' )
17+ try {
18+ const response = await axios . post ( tokenEndpoint , 'grant_type=client_credentials' , {
19+ headers : {
20+ 'Authorization' : `Basic ${ credentials } ` ,
21+ 'Content-Type' : 'application/x-www-form-urlencoded' ,
22+ }
23+ } ) ;
24+ console . debug ( "Bearer token retrieved" )
25+ return response . data . access_token
26+ }
27+ catch ( error ) {
28+ logger . error ( `Failed to retrieve bearer token: ${ JSON . stringify ( error ) } ` )
29+ throw errorWithCode ( 'Failed to retrieve bearer token' , 500 )
30+ }
31+ }
32+
33+ async sendEmail ( to , from , subject , body , bodyType ) {
34+ if ( ! eval ( this . enabled ) )
35+ return ;
36+ const emailEndpoint = `${ this . emailServiceURL } /api/v1/email`
37+ try {
38+ const token = await this . getBearerToken ( )
39+ const emailPayload = { to, from, subject, body, bodyType, }
40+ logger . debug ( "email payload: " + JSON . stringify ( emailPayload ) )
41+ await axios . post ( emailEndpoint , JSON . stringify ( emailPayload ) , {
42+ headers : {
43+ 'Content-Type' : 'application/json' ,
44+ Authorization : `Bearer ${ token } ` ,
45+ } ,
46+ } ) . then ( response => {
47+ if ( response . status > 199 && response . status < 300 )
48+ logger . info ( 'Email sent successfully' )
49+ else
50+ logger . error ( `Could not send Email: ${ response . statusText } ` )
51+ } ) . catch ( error => {
52+ logger . error ( `Error sending email: ${ JSON . stringify ( error ) } ` )
53+ throw errorWithCode ( 'Error sending email' , 500 )
54+ } ) ;
55+ } catch ( error ) {
56+ logger . error ( `Failed sending email: ${ JSON . stringify ( error ) } ` )
57+ throw errorWithCode ( 'Failed sending email' , 500 )
58+ }
59+ }
60+ }
0 commit comments