Skip to content

Create an endpoint

Wojtek Cichoń edited this page Jan 25, 2021 · 2 revisions

Front-end and back-end/phone communication happens through IPC exposed by Electron. Some utilities make the creation simpler and more unified in the app.

If you want to introduce a new channel, please follow the following steps:

1. Name your request

Add a request name and a label in src/common/requests/ipc-request.enum.ts.

export enum IpcRequest {
  // ...
  MyNewRequest = "get-some-data"
}

2. Create a back-end handler

Create a new definition in src/backend/requests/my-new-request.request.ts. This definition will look similar to:

// The handler responsible for receiving and sending the data.
const handleMyRequest = (
  { app }: Adapters,
  // This is a value passed by the front-end when making a call.
  valuePassedByCaller: string
): DeviceInfo => {
  // Whatever you return will be sent to the front-end.
  return app.getName() + valuePassedByCaller
}

const registerMyRequest = createEndpoint({
  name: IpcRequest.MyNewRequest,
  handler: handleMyRequest,
})

export default registerMyRequest

3. Register it

Register the new endpoint in the src/backend/bootstrap.ts.

const bootstrap = () => {
  // ...
  ;[/* ... other endpoints */, registerMyRequest].forEach(register =>
    // ...
  )
}

4. Handle front-end

Add the front-end part that will be used by the app. Create the src/renderer/requests/my-request.request.ts file.

const getMyData = (value: string): Promise<DeviceInfo> => {
  return ipcRenderer.callMain(IpcRequest.MyNewRequest, value) as Promise<
    string
  >
}

export default getMyData

Now you can just call this function in your components.

const MyCmp = () => {
  const onClick = () => await getMyData()
  // ...
}
Clone this wiki locally