smartlog-receiver/ts/sl.classes.smartlogreceiver.ts

63 lines
2.0 KiB
TypeScript
Raw Normal View History

2018-10-31 16:42:18 +00:00
import * as plugins from './sl.receiver.plugins';
2020-06-07 12:41:25 +00:00
import {
ILogPackage,
ILogPackageAuthenticated,
ILogDestination
} from '@pushrocks/smartlog-interfaces';
2018-11-11 00:38:19 +00:00
2018-11-11 16:45:15 +00:00
export type TValidatorFunction = (logPackage: ILogPackage) => boolean;
2018-11-11 00:38:19 +00:00
export interface ISmartlogReceiverOptions {
smartlogInstance: plugins.smartlog.Smartlog;
passphrase: string;
validatorFunction: TValidatorFunction;
}
2018-10-31 16:42:18 +00:00
/**
* a class that receives smartlog packages
*/
export class SmartlogReceiver {
2019-10-22 13:38:19 +00:00
public passphrase: string;
public validatorFunction: TValidatorFunction;
public smartlogInstance: plugins.smartlog.Smartlog;
2018-11-11 00:38:19 +00:00
constructor(smartlogReceiverOptions: ISmartlogReceiverOptions) {
this.passphrase = smartlogReceiverOptions.passphrase;
this.validatorFunction = smartlogReceiverOptions.validatorFunction;
this.smartlogInstance = smartlogReceiverOptions.smartlogInstance;
}
2018-10-31 16:42:18 +00:00
/**
* handles a authenticated log
*/
2019-10-22 13:38:19 +00:00
public async handleAuthenticatedLog(authenticatedLogPackageArg: ILogPackageAuthenticated) {
2018-11-11 00:38:19 +00:00
const authString = authenticatedLogPackageArg.auth;
const logPackage = authenticatedLogPackageArg.logPackage;
2020-06-07 12:41:25 +00:00
if (authString === plugins.smarthash.sha256FromStringSync(this.passphrase)) {
2018-11-11 00:56:17 +00:00
// this.smartlogInstance.log('ok', 'Message accepted');
2018-11-11 00:56:02 +00:00
this.smartlogInstance.handleLogPackage(logPackage);
2018-11-11 18:06:53 +00:00
return { status: 'ok' };
2018-11-11 00:38:19 +00:00
} else {
this.smartlogInstance.log('error', 'Message rejected because of bad passphrase');
2018-11-11 18:06:53 +00:00
return { status: 'error' };
2018-11-11 00:38:19 +00:00
// console.log(plugins.smarthash.sha256FromStringSync(this.passphrase));
}
}
2019-10-22 13:38:19 +00:00
/**
* handles an array of authenticated logs
* @param authenticatedLogsPackageArrayArg
*/
2020-06-07 12:41:25 +00:00
public async handleManyAuthenticatedLogs(
authenticatedLogsPackageArrayArg: ILogPackageAuthenticated[]
) {
2019-10-22 13:38:19 +00:00
const promiseArray: Array<Promise<any>> = [];
for (const logPackage of authenticatedLogsPackageArrayArg) {
promiseArray.push(this.handleAuthenticatedLog(logPackage));
}
await Promise.all(promiseArray);
}
2018-10-31 16:42:18 +00:00
}