Skip to content

Commit

Permalink
feat: lazy load import framework
Browse files Browse the repository at this point in the history
  • Loading branch information
ramonornela committed Jun 29, 2020
1 parent 5090731 commit 3a10a33
Showing 1 changed file with 41 additions and 10 deletions.
51 changes: 41 additions & 10 deletions src/vpn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,21 @@ import { Config, ConnectOptions } from './interfaces';

const path = require('path'); // eslint-disable-line

export const $ = require('@ammora/nodobjc'); // eslint-disable-line

export class Bridge {
private vpnManager: any;

private readonly config?: Config = {};

constructor(options: ConnectOptions, config?: Config) {
private $: any;

private fwImported = false;

private readonly options: any;

constructor(options?: ConnectOptions, config?: Config) {
this.config = config;

this.importFramework();
this.create(options);
this.options = options;
}

private get log(): any {
Expand All @@ -30,7 +33,26 @@ export class Bridge {
return log;
}

get objC(): any {
if (this.$ !== undefined) {
return this.$;
}

try {
this.$ = require('@ammora/nodobjc'); // eslint-disable-line
} catch (e) {
this.log.info('Error import Objc: ', e.message);
throw e;
}

return this.$;
}

private importFramework(): void {
if (this.fwImported) {
return;
}

let frameworkPath = this.config?.frameworkPath;

if (frameworkPath === null || frameworkPath === undefined) {
Expand All @@ -40,28 +62,37 @@ export class Bridge {
const fwPath: string = path.join(frameworkPath, 'VPNManager.framework');
this.log.info('VPNManager Framework path: ' + fwPath);

$.import(fwPath);
this.objC.import(fwPath);

this.log.info('VPNManager Framework import');
this.fwImported = true;
}

get manager(): any {
return this.vpnManager;
}

create(options: ConnectOptions): this {
this.importFramework();
const json = JSON.stringify(options);
this.vpnManager = $.VPNManager('alloc')('initWithJson', $(json));
this.vpnManager = this.objC.VPNManager('alloc')('initWithJson', this.objC(json));

this.log.info('VPNManager created');

return this;
}

connect(username: string, password: string): void {
// @todo async/await
if (this.vpnManager === undefined && this.options !== undefined) {
this.create(this.options);
}

if (this.vpnManager === undefined) {
throw new Error('VPNManager no created!');
}

const self = this; // eslint-disable-line
const block = $(function(_self: any, isSuccess: any) {
const block = this.objC(function(_self: any, isSuccess: any) {
// @todo get NSError
self.log.info('VPNManager connecting');
if (isSuccess === true) {
Expand All @@ -72,7 +103,7 @@ export class Bridge {
self.log.info(`VPNManager error`);
}, ['v',['?','B']]);

this.vpnManager('connect', $(username), 'password', $(password), 'complete', block);
this.vpnManager('connect', this.objC(username), 'password', this.objC(password), 'complete', block);
}
}

Expand Down

0 comments on commit 3a10a33

Please # to comment.