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:
parent
b617069784
commit
cc2f5f58e2
@ -19,6 +19,7 @@ describe('jsonrpc', () => {
|
|||||||
httpError(statusCode: number, message: string): Promise<void>
|
httpError(statusCode: number, message: string): Promise<void>
|
||||||
|
|
||||||
addWithContext(a: number, b: number): (ctx: IContext) => number
|
addWithContext(a: number, b: number): (ctx: IContext) => number
|
||||||
|
addWithContext2(a: number, b: number): Promise<number>
|
||||||
}
|
}
|
||||||
|
|
||||||
class Service implements IService {
|
class Service implements IService {
|
||||||
@ -51,6 +52,9 @@ describe('jsonrpc', () => {
|
|||||||
addWithContext = (a: number, b: number) => (ctx: IContext): number => {
|
addWithContext = (a: number, b: number) => (ctx: IContext): number => {
|
||||||
return a + b + ctx.userId
|
return a + b + ctx.userId
|
||||||
}
|
}
|
||||||
|
addWithContext2(a: number, b: number, ctx?: IContext) {
|
||||||
|
return Promise.resolve(a + b + ctx!.userId)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function createApp() {
|
function createApp() {
|
||||||
@ -65,6 +69,7 @@ describe('jsonrpc', () => {
|
|||||||
'asyncError',
|
'asyncError',
|
||||||
'httpError',
|
'httpError',
|
||||||
'addWithContext',
|
'addWithContext',
|
||||||
|
'addWithContext2',
|
||||||
])
|
])
|
||||||
.router(),
|
.router(),
|
||||||
)
|
)
|
||||||
@ -144,6 +149,10 @@ describe('jsonrpc', () => {
|
|||||||
const response = await client.addWithContext(5, 7)
|
const response = await client.addWithContext(5, 7)
|
||||||
expect(response).toEqual(1000 + 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 () => {
|
it('handles synchronous notifications', async () => {
|
||||||
await request(createApp())
|
await request(createApp())
|
||||||
.post('/myService')
|
.post('/myService')
|
||||||
|
|||||||
@ -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') {
|
if (typeof retValue === 'function') {
|
||||||
retValue = retValue(context)
|
retValue = retValue(context)
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user