2.0.0 • Published 4 years ago

@melb2991/electron-railbridge v2.0.0

Weekly downloads
-
License
MIT
Repository
-
Last release
4 years ago

Readme

A thin wrapper around ipcMain and ipcRenderer that's a little more ergonomic and type safe.

Usage

install:

yarn install @melb2991/electron-railbridge

preload.ts

import "@melb2991/electron-railbridge/preload";

api.ts

export const api = {
  hello: (name: string) => `Hello ${name}`,
  goodbye: async (name: string) => `Goodbye ${name}`,
};

export type Api = typeof api;

main.ts

import { app, BrowserWindow } from "electron";
import * as path from "path";
import { api } from "./api";
import { BridgeServer } from "@melb2991/electron-railbridge/server";

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
    },
    width: 800,
  });

  // and load the index.html of the app.
  mainWindow.loadFile(path.join(__dirname, "../index.html"));

  // Open the DevTools.
  mainWindow.webContents.openDevTools();
}

app.on("ready", () => {
  BridgeServer({
    api,
  });

  createWindow();

  app.on("activate", function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

// ... other stuff

renderer/index.ts

import { BridgeClient } from "@melb2991/electron-railbridge/client";
import { Api } from "../api";

type BridgeType = {
  api: Api;
};

const bridgeClient = BridgeClient<BridgeType>();

async function callClient() {
  console.log(await bridgeClient.api.hello("Jim")); // Hello Jim
  console.log(await bridgeClient.api.goodbye("Bob")); // Goodbye Bob
}

callClient();