44 lines
1.1 KiB
TypeScript
44 lines
1.1 KiB
TypeScript
|
|
import * as plugins from '../plugins.js';
|
||
|
|
|
||
|
|
/**
|
||
|
|
* TypedRequest handler for type-safe RPC endpoint
|
||
|
|
*/
|
||
|
|
export class TypedRequestHandler {
|
||
|
|
private typedRouter: plugins.typedrequest.TypedRouter;
|
||
|
|
|
||
|
|
constructor(typedRouter: plugins.typedrequest.TypedRouter) {
|
||
|
|
this.typedRouter = typedRouter;
|
||
|
|
}
|
||
|
|
|
||
|
|
/**
|
||
|
|
* Handle a request - returns Response if handled, null otherwise
|
||
|
|
*/
|
||
|
|
public async handle(request: Request): Promise<Response | null> {
|
||
|
|
const url = new URL(request.url);
|
||
|
|
const path = url.pathname;
|
||
|
|
|
||
|
|
if (path === '/typedrequest' && request.method === 'POST') {
|
||
|
|
try {
|
||
|
|
const body = await request.json();
|
||
|
|
const response = await this.typedRouter.routeAndAddResponse(body);
|
||
|
|
|
||
|
|
return new Response(plugins.smartjson.stringify(response), {
|
||
|
|
status: 200,
|
||
|
|
headers: {
|
||
|
|
'Content-Type': 'application/json',
|
||
|
|
},
|
||
|
|
});
|
||
|
|
} catch (error) {
|
||
|
|
return new Response(JSON.stringify({ error: 'Invalid request' }), {
|
||
|
|
status: 400,
|
||
|
|
headers: {
|
||
|
|
'Content-Type': 'application/json',
|
||
|
|
},
|
||
|
|
});
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
return null;
|
||
|
|
}
|
||
|
|
}
|