| 220 | } |
| 221 | |
| 222 | export class ApiConnectionHandler extends ConnectionHandler { |
| 223 | dispose: () => Promise<void> | void; |
| 224 | isRpc: boolean; |
| 225 | |
| 226 | @param('op', Types.String) |
| 227 | async prepare({ }, op: string) { |
| 228 | if (op === 'rpc') { |
| 229 | this.isRpc = true; |
| 230 | return; |
| 231 | } |
| 232 | if (!APIS[op]) throw new BadRequestError(`Invalid API operation: ${op}`); |
| 233 | if (APIS[op].type !== 'Subscription') { |
| 234 | throw new BadRequestError('Only subscription operations are supported'); |
| 235 | } |
| 236 | handleArguments(this.args); |
| 237 | // @ts-ignore |
| 238 | await this.ctx.parallel('handler/api/before', this); |
| 239 | // @ts-ignore |
| 240 | await this.ctx.parallel(`handler/api/before/${op}`, this); |
| 241 | this.dispose = await this.ctx.api.execute( |
| 242 | this, op, { domainId: this.args.domainId, ...this.args, ...(this.args.args || {}) }, |
| 243 | (m, args) => (this.ctx.parallel as any)(m, args), this.args.projection, (p) => this.send(p), |
| 244 | ); |
| 245 | } |
| 246 | |
| 247 | async message(message) { |
| 248 | if (!this.isRpc) throw new BadRequestError('Only RPC operations are supported'); |
| 249 | if (typeof message === 'string') { |
| 250 | try { |
| 251 | message = JSON.parse(message); |
| 252 | } catch (e) { |
| 253 | throw new BadRequestError('Invalid message'); |
| 254 | } |
| 255 | } |
| 256 | if (!APIS[message.op]) throw new BadRequestError(`Invalid API operation: ${message.op}`); |
| 257 | if (APIS[message.op].type !== 'Subscription') { |
| 258 | throw new BadRequestError('Only subscription operations are supported'); |
| 259 | } |
| 260 | handleArguments(message); |
| 261 | const result = await this.ctx.api.execute( |
| 262 | this, message.op, message.args, (m, args) => (this.ctx.parallel as any)(m, args), message.projection, |
| 263 | ); |
| 264 | this.send(result); |
| 265 | } |
| 266 | |
| 267 | async cleanup() { |
| 268 | await this.dispose?.(); |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | export async function applyApiHandler(ctx: Context, name: string, path: string) { |
| 273 | ctx.plugin(ApiService); |