-
Notifications
You must be signed in to change notification settings - Fork 12
/
index.ts
183 lines (161 loc) · 4.74 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import { RPCRequest, RPCResponse } from '@erebos/rpc-base'
import {
ERROR_CODE,
RPCError,
createInvalidParams,
createParseError,
getErrorMessage,
} from '@erebos/rpc-error'
import Validator from 'fastest-validator'
export type ErrorHandler = <C = any, P = any>(
ctx: C,
req: RPCRequest<P>,
error: Error,
) => void
export type MethodHandler = <C = any, P = any, R = any>(
ctx: C,
params: P,
) => R | Promise<R>
export type NotificationHandler = <C = any, P = any>(
ctx: C,
req: RPCRequest<P>,
) => void
// Definitions from the fastest-validator are not complete
type ValidationSchema = Record<string, any>
export interface MethodWithParams {
params?: ValidationSchema | undefined
handler: MethodHandler
}
export type Methods = Record<string, MethodHandler | MethodWithParams>
type NormalizedMethods = Record<string, MethodHandler>
export interface HandlerParams {
methods: Methods
onHandlerError?: ErrorHandler | undefined
onInvalidMessage?: NotificationHandler | undefined
onNotification?: NotificationHandler | undefined
validatorOptions?: any | undefined
}
export type HandlerFunc = <C = any, P = any, R = any, E = any>(
ctx: C,
req: RPCRequest<P>,
) => Promise<RPCResponse<R, E>>
export function parseJSON<T = any>(input: string): T {
try {
return JSON.parse(input)
} catch (err) {
throw createParseError()
}
}
export function createErrorResponse<R, E>(
id: number | string,
code: number,
): RPCResponse<R, E> {
return {
jsonrpc: '2.0',
id,
error: { code, message: getErrorMessage(code) },
}
}
export function normalizeMethods(
methods: Methods,
validatorOptions?: any | undefined,
): NormalizedMethods {
const v = new Validator(validatorOptions)
return Object.keys(methods).reduce((acc, name) => {
const method = methods[name]
if (typeof method === 'function') {
acc[name] = method
} else if (typeof method.handler === 'function') {
if (method.params == null) {
acc[name] = method.handler
} else {
const check = v.compile(method.params)
acc[name] = function validatedMethod<C = any, P = Record<string, any>>(
ctx: C,
params: P,
) {
// eslint-disable-next-line @typescript-eslint/ban-types
const checked = check(params as Object)
if (checked === true) {
return method.handler(ctx, params)
} else {
throw createInvalidParams(checked)
}
}
}
} else {
throw new Error(
`Unexpected definition for method "${name}": method should be a function or an object with "params" Object and "handler" function.`,
)
}
return acc
}, {} as NormalizedMethods)
}
function defaultOnHandlerError<C = any, P = any>(
ctx: C,
msg: RPCRequest<P>,
error: Error,
): void {
// eslint-disable-next-line no-console
console.warn('Unhandled handler error', msg, error)
}
function defaultOnInvalidMessage<C = any, P = any>(
ctx: C,
msg: RPCRequest<P>,
): void {
// eslint-disable-next-line no-console
console.warn('Unhandled invalid message', msg)
}
function defaultOnNotification<C = any, P = any>(
ctx: C,
msg: RPCRequest<P>,
): void {
// eslint-disable-next-line no-console
console.warn('Unhandled notification', msg)
}
export function createHandler(
params: HandlerParams,
): <C = any, P = any, R = any, E = any>(
ctx: C,
msg: RPCRequest<P>,
) => Promise<RPCResponse<R, E> | null> {
const methods = normalizeMethods(params.methods, params.validatorOptions)
const onHandlerError = params.onHandlerError || defaultOnHandlerError
const onInvalidMessage = params.onInvalidMessage || defaultOnInvalidMessage
const onNotification = params.onNotification || defaultOnNotification
return async function handleMessage<C = any, P = any, R = any, E = any>(
ctx: C,
msg: RPCRequest<P>,
): Promise<RPCResponse<R, E> | null> {
const id = msg.id
if (msg.jsonrpc !== '2.0' || msg.method == null) {
if (id == null) {
onInvalidMessage(ctx, msg)
return null
}
return createErrorResponse(id, ERROR_CODE.INVALID_REQUEST)
}
if (id == null) {
onNotification(ctx, msg)
return null
}
const handler = methods[msg.method]
if (handler == null) {
return createErrorResponse(id, ERROR_CODE.METHOD_NOT_FOUND)
}
try {
const result = await handler(ctx, msg.params || {})
return { jsonrpc: '2.0', id, result }
} catch (err) {
onHandlerError(ctx, msg, err)
let error
if (err instanceof RPCError) {
error = err.toObject()
} else {
const code = err.code || -32000 // Server error
error = { code, message: err.message || getErrorMessage(code) }
}
return { jsonrpc: '2.0', id, error }
}
}
}