refactor: add destroy method (for testing) for backend transport

Additionally fix minor issues and refactor the class
This commit is contained in:
Jovan Krunić
2020-10-23 10:19:42 +02:00
committed by Rainer Killinger
parent dd6ea1c6f3
commit f3b86f0f0d

View File

@@ -13,6 +13,7 @@
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import {Logger} from '@openstapps/logger';
import {SMTP} from '@openstapps/logger/lib/smtp';
import {Transport, VerifiableTransport} from '@openstapps/logger/lib/transport';
@@ -39,7 +40,7 @@ export class BackendTransport {
/**
* Stores information if transport is in state of waiting for the verification
*/
private readonly waitingForVerification: boolean;
private waitingForVerification = false;
/**
* A (SMTP) transport which includes settings for sending mails
@@ -47,16 +48,30 @@ export class BackendTransport {
protected transport: SMTP | undefined;
/**
* Provides an instance of a transport
* Destroys the singleton instance of the class (for unit test purposes)
*/
public static getTransportInstance(): SMTP | undefined {
public static destroy() {
delete BackendTransport._instance;
}
/**
* Provides instance of a backend transport
*/
public static getInstance(): BackendTransport {
if (typeof BackendTransport._instance !== 'undefined') {
return BackendTransport._instance.transport;
return BackendTransport._instance;
}
BackendTransport._instance = new BackendTransport();
return BackendTransport._instance.transport;
return BackendTransport._instance;
}
/**
* Provides an instance of a transport
*/
public static getTransportInstance(): SMTP | undefined {
return BackendTransport.getInstance().transport;
}
private constructor() {
@@ -67,27 +82,30 @@ export class BackendTransport {
this.transport = SMTP.getInstance();
} catch (error) {
if (process.env.ALLOW_NO_TRANSPORT === 'true') {
/* tslint:disable-next-line:no-console */
console.warn('SMTP error was ignored.');
Logger.warn('SMTP error was ignored.');
} else {
throw error;
}
}
if (typeof this.transport !== 'undefined' && isTransportWithVerification(this.transport)) {
this.waitingForVerification = true;
void this.verifyTransport(this.transport);
}
}
this.transport.verify()
.then((message) => {
if (typeof message === 'string') {
// tslint:disable-next-line:no-console
console.log(message);
}
})
.catch((err) => {
throw err;
});
} else {
/**
* Verifies the transport using its verification method
*/
private async verifyTransport(transport: VerifiableTransport): Promise<void> {
this.waitingForVerification = true;
try {
const successful = await transport.verify();
if (successful) {
Logger.log('SMTP verification successful.');
}
} catch (err) {
throw err;
} finally {
this.waitingForVerification = false;
}
}