Skip to content

Instantly share code, notes, and snippets.

@bushev
Created March 4, 2019 02:04
Show Gist options
  • Save bushev/eb7743e03beff8d4fa87e87aa59adb8c to your computer and use it in GitHub Desktop.
Save bushev/eb7743e03beff8d4fa87e87aa59adb8c to your computer and use it in GitHub Desktop.
import { Injectable } from '@angular/core';
import { ElectronService } from 'ngx-electron';
import * as _ from 'lodash';
@Injectable({
providedIn: 'root'
})
export class IPCService {
private callId: number = 0;
private pendingCalls: any[] = [];
constructor(public electronService: ElectronService) {
this.electronService.ipcRenderer.on('call-result', (event, response) => {
this.handleResponse(response);
});
}
public async call(service: string, params: any): Promise<any> {
const callId = this.getNextCallId();
this.electronService.ipcRenderer.send('call', {callId, service, params});
return new Promise<any>((resolve, reject) => {
this.pendingCalls.push({
id: callId,
callback: (err, result) => {
if (err) return reject(err);
resolve(result);
}
});
});
}
private handleResponse(response) {
const pendingCall = _.find(this.pendingCalls, {id: response.id});
if (pendingCall) {
pendingCall.callback(response.err, response.result);
_.remove(pendingCall, {id: response.id});
} else {
console.error(`Couldn't find pending call data by id: ${response.id}`);
}
}
private getNextCallId() {
return ++this.callId;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment