Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@
const jsf = require("json-schema-faker"); // eslint-disable-line

export interface MethodMapping {
[methodName: string]: (...params: any) => Promise<any>;

Check warning on line 15 in src/router.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type

Check warning on line 15 in src/router.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
}

export interface MockModeSettings {
mockMode: boolean;
}

export type TMethodHandler = (...args: any) => Promise<any>;

Check warning on line 22 in src/router.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type

Check warning on line 22 in src/router.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type

const toArray = (method?: MethodObject, params?: Record<string, unknown>) => {
if (!method) {
Expand All @@ -42,7 +42,7 @@

export class Router {

public static methodNotFoundHandler(methodName: string) {

Check warning on line 45 in src/router.ts

View workflow job for this annotation

GitHub Actions / lint

Missing return type on function
return {
error: {
code: -32601,
Expand All @@ -68,7 +68,7 @@
this.methodCallValidator = new MethodCallValidator(openrpcDocument);
}

public async call(methodName: string, params: any) {
public async call(methodName: string, params: any, context?: any) {
const validationErrors = this.methodCallValidator.validate(methodName, params);

if (validationErrors instanceof MethodNotFoundError) {
Expand All @@ -84,7 +84,8 @@
const paramsAsArray = params instanceof Array ? params : toArray(methodObject, params);

try {
return { result: await this.methods[methodName](...paramsAsArray) };
const result = await this.methods[methodName].apply(context, paramsAsArray);
return { result };
} catch (e) {
if (e instanceof JSONRPCError) {
return { error: { code: e.code, message: e.message, data: e.data } };
Expand Down
32 changes: 32 additions & 0 deletions src/transports/http.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,4 +142,36 @@ describe("http transport", () => {
serverInstance.listen = originalListen;
// Do not call stop, since server never started
});

it("binds req and res as the this context for methods", async () => {
// create an app that attaches customProp to req
const app = connect();
app.use((req: any, res: any, next: any) => { req.customProp = 'hello'; next(); });
// set up transport and router with a method that returns this.req.customProp
const transport = new HTTPTransport({ middleware: [], port: 9710, app });
const minimalDoc = {
openrpc: '1.2.6',
info: { title: 'test', version: '1.0.0' },
methods: [
{ name: 'getCustom', params: [], result: { name: 'custom', schema: { type: 'string' } } }
],
} as any;
const mapping = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getCustom: async function(): Promise<any> { return (this as any).req.customProp; }
};
const router = new Router(minimalDoc, mapping);
transport.addRouter(router);
await transport.start();
try {
const { result } = await fetch('http://localhost:9710', {
body: JSON.stringify({ id: 'foo', jsonrpc: '2.0', method: 'getCustom', params: [] }),
headers: { 'Content-Type': 'application/json' },
method: 'post',
}).then((res) => res.json() as Promise<JSONRPCResponse>);
expect(result).toBe('hello');
} finally {
await transport.stop();
}
});
});
8 changes: 6 additions & 2 deletions src/transports/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,15 @@ export default class HTTPServerTransport extends ServerTransport {
}

private async httpRouterHandler(req: any, res: any): Promise<void> {
// bind req and res as the context for method calls
const context = { req, res };
let result = null;
if (req.body instanceof Array) {
result = await Promise.all(req.body.map((r: JSONRPCRequest) => super.routerHandler(r)));
result = await Promise.all(
req.body.map((r: JSONRPCRequest) => super.routerHandler(r, context)),
);
} else {
result = await super.routerHandler(req.body);
result = await super.routerHandler(req.body, context);
}
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(result));
Expand Down
8 changes: 6 additions & 2 deletions src/transports/https.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,15 @@ export default class HTTPSServerTransport extends ServerTransport {
}

private async httpsRouterHandler(req: any, res: any): Promise<void> {
// bind req and res as the context for method calls
const context = { req, res };
let result = null;
if (req.body instanceof Array) {
result = await Promise.all(req.body.map((r: JSONRPCRequest) => super.routerHandler(r)));
result = await Promise.all(
req.body.map((r: JSONRPCRequest) => super.routerHandler(r, context)),
);
} else {
result = await super.routerHandler(req.body);
result = await super.routerHandler(req.body, context);
}
res.setHeader("Content-Type", "application/json");
res.end(JSON.stringify(result));
Expand Down
8 changes: 6 additions & 2 deletions src/transports/ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,15 @@ export default class IPCServerTransport extends ServerTransport {
}

private async ipcRouterHandler(req: any, respondWith: any) {
// bind req and respondWith as context for method calls
const context = { req, respondWith };
let result = null;
if (req instanceof Array) {
result = await Promise.all(req.map((jsonrpcReq: JSONRPCRequest) => super.routerHandler(jsonrpcReq)));
result = await Promise.all(
req.map((jsonrpcReq: JSONRPCRequest) => super.routerHandler(jsonrpcReq, context)),
);
} else {
result = await super.routerHandler(req);
result = await super.routerHandler(req, context);
}
respondWith(JSON.stringify(result));
}
Expand Down
6 changes: 4 additions & 2 deletions src/transports/server-transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ export abstract class ServerTransport {
throw new Error("Transport missing stop implementation");
}

protected async routerHandler({ id, method, params }: JSONRPCRequest): Promise<JSONRPCResponse> {
protected async routerHandler(request: JSONRPCRequest, context?: any): Promise<JSONRPCResponse> {
const { id, method, params } = request;
if (this.routers.length === 0) {
console.warn("transport method called without a router configured."); // tslint:disable-line
throw new Error("No router configured");
Expand All @@ -61,9 +62,10 @@ export abstract class ServerTransport {
...Router.methodNotFoundHandler(method)
};
} else {
// forward context when invoking the method
res = {
...res,
...await routerForMethod.call(method, params)
...await (routerForMethod as any).call(method, params, context)
};
}

Expand Down
8 changes: 6 additions & 2 deletions src/transports/websocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,15 @@ export default class WebSocketServerTransport extends ServerTransport {
}

private async webSocketRouterHandler(req: any, respondWith: any) {
// bind req and respondWith as context for method calls
const context = { req, respondWith };
let result = null;
if (req instanceof Array) {
result = await Promise.all(req.map((r: JSONRPCRequest) => super.routerHandler(r)));
result = await Promise.all(
req.map((r: JSONRPCRequest) => super.routerHandler(r, context)),
);
} else {
result = await super.routerHandler(req);
result = await super.routerHandler(req, context);
}
respondWith(JSON.stringify(result));
}
Expand Down
Loading