Skip to content

Instantly share code, notes, and snippets.

@alexstrat
Last active November 23, 2018 17:50
Show Gist options
  • Save alexstrat/5b3e0ff7bdeb68fe3d6e02d00f15a07c to your computer and use it in GitHub Desktop.
Save alexstrat/5b3e0ff7bdeb68fe3d6e02d00f15a07c to your computer and use it in GitHub Desktop.
Mojom example

Overview

  • math.mojom is the definition of the service
  • math.ts is auto-generated code based on Mojo definition: it gives a stub and a type definition of an implementation
  • mathImpl.ts is an actual implementation of Math service.
  • mathRPC.ts is the necessary code to call a remote implementation of Math service via JSON-RPC (using a RPCPeer). It can be auto-generated as well.

In the best world, dev just have to define math.mojom and implement mathImpl.ts, the logic of the service. The rest is code-generated.

Local usage

import { Math } from './math.ts'
import { MathImpl } from './MathImpl'

const math = new Math(new MathImpl());

const { sum } = await math.add({a: 1, b: 2});
// sum is 3

Remote usage

In process A (server):

import { Math } from './math.ts'
import { MathImpl } from './mathRPC.ts'

const rpcPeer = getRPCPeer();

const math = new Math(new MathImpl(rpcPeer));

const { sum } = await math.add({a: 1, b: 2});
// sum is 3

In process B (usage):

import { MathImpl } from './MathImpl'
import { bindImpl } from './mathRPC.ts'
const rpcPeer = getRPCPeer();

bindImpl(rpcPeer, new MathImpl());
module bx.util;
interface Math {
Add(int32 a, int32 b) => (uint32 sum);
}
export type IMathAddRequest {
a: int;
b: int;
}
export type IMathAddResponse {
sum: int;
}
export interface IMath {
add: (r: IMathAddRequest) => Promise<IMathAddResponse>;
}
// stub
export class Math implements IMath {
constructor(impl) {
this.impl = impl;
}
async add(r:IMathAddRequest ): Promise<IMathAddResponse> {
return await this.impl.add(r);
}
}
import { IMath } from './math.ts';
export class MathImpl implements IMath {
async add(r) {
return r.a + r.b;
}
}
import { IMath } from './math.ts';
export class MathRPCImpl implements IMath {
static module = 'bx.util';
static interfaceName = 'Math';
constructor(rpcPeer: RPCPeer) {
this.peer = rpcPeer;
}
async add(r) {
return this.peer.request('bx.util.Math.Add', r);
}
}
export class bindImpl = (rpcPeer: RPCPeer, impl: IMath) => {
rpcPeer.addHander('bx.util.Math.Add', async (r) => {
return await impl.add(r);
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment