Add ability to specify jsonrpc context as extra argument

In this case the interface does not define context, but the implementing
service may use it as an optional argument:

  interface IService {
    add(a: number, b: number): number
  }

  class Service implements IService {
    add(a: number, b: number, ctx?: IContext): number {
      return a + b + ctx!.userId
    }
  }
This commit is contained in:
Jerko Steiner 2019-08-06 20:10:33 +07:00
parent b617069784
commit cc2f5f58e2
2 changed files with 10 additions and 1 deletions

View File

@ -19,6 +19,7 @@ describe('jsonrpc', () => {
httpError(statusCode: number, message: string): Promise<void>
addWithContext(a: number, b: number): (ctx: IContext) => number
addWithContext2(a: number, b: number): Promise<number>
}
class Service implements IService {
@ -51,6 +52,9 @@ describe('jsonrpc', () => {
addWithContext = (a: number, b: number) => (ctx: IContext): number => {
return a + b + ctx.userId
}
addWithContext2(a: number, b: number, ctx?: IContext) {
return Promise.resolve(a + b + ctx!.userId)
}
}
function createApp() {
@ -65,6 +69,7 @@ describe('jsonrpc', () => {
'asyncError',
'httpError',
'addWithContext',
'addWithContext2',
])
.router(),
)
@ -144,6 +149,10 @@ describe('jsonrpc', () => {
const response = await client.addWithContext(5, 7)
expect(response).toEqual(1000 + 5 + 7)
})
it('can use context as extra argument', async () => {
const response = await client.addWithContext2(5, 7)
expect(response).toEqual(1000 + 5 + 7)
})
it('handles synchronous notifications', async () => {
await request(createApp())
.post('/myService')

View File

@ -107,7 +107,7 @@ export const createRpcService = <T, M extends FunctionPropertyNames<T>>(
})
}
let retValue = (rpcService[method] as any)(...params)
let retValue = (rpcService[method] as any)(...params, context)
if (typeof retValue === 'function') {
retValue = retValue(context)