Skip to content

Commit

Permalink
add rest decorator to explorer
Browse files Browse the repository at this point in the history
rename variables for consistency
  • Loading branch information
Zewasik committed Oct 3, 2024
1 parent fe9c037 commit e5c5827
Show file tree
Hide file tree
Showing 5 changed files with 69 additions and 69 deletions.
44 changes: 43 additions & 1 deletion idea/explorer/src/decorators/method.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,25 @@
import { GenesisNotFound, MethodNotFound, NetworkNotSupported } from '../errors';
import { Router } from 'express';
import { GenesisNotFound, MethodNotFound, NetworkNotSupported, VoucherNotFound } from '../errors';
import { JsonRpcRequest, JsonRpcResponse } from '../types';

type Constructor<T = any> = new (...args: any[]) => T;
type AllowedMethods = 'get' | 'post';

const rpcMethods: Record<string, (...args: any[]) => Promise<void>> = {};
const restHandlers = new Array<{ method: AllowedMethods; path: string; handler: (...args: any[]) => Promise<any> }>();

export function JsonRpcMethod(name: string) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
rpcMethods[name] = descriptor.value;
};
}

export function RestHandler(method: AllowedMethods, path: string) {
return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
restHandlers.push({ method, path, handler: descriptor.value });
};
}

export interface IJsonRpc {
_getMethod(name: string): (...args: any[]) => Promise<void>;
handleRequest({ method, params, id }: JsonRpcRequest): Promise<JsonRpcResponse | JsonRpcResponse[]>;
Expand Down Expand Up @@ -76,5 +85,38 @@ export function JsonRpc<TBase extends Constructor<JsonRpcBase>>(Base: TBase) {
};
}
}

createRestRouter(): Router {
const router = Router();

for (const { method, path, handler } of restHandlers) {
router[method](path, async (req, res) => {
const { genesis } = req.query;
if (!genesis) {
res.status(400).json({ error: 'Genesis not found in the request' });
return;
}

if (!this.__genesises.has(genesis.toString())) {
res.status(400).json({ error: 'Network is not supported' });
return;
}

try {
const result = await handler.apply(this, [{ ...req.body, ...req.params, genesis: genesis.toString() }]);
res.json(result);
} catch (err) {
if (err instanceof VoucherNotFound) {
res.json(null);
return;
}
console.log(err.message);
res.status(500).json({ error: 'Internal server error' });
}
});
}

return router;
}
};
}
54 changes: 6 additions & 48 deletions idea/explorer/src/jsonrpc.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import express, { Express } from 'express';
import { JsonRpc, JsonRpcBase, JsonRpcMethod } from './decorators/method';
import { JsonRpc, JsonRpcBase, JsonRpcMethod, RestHandler } from './decorators/method';
import { AllInOneService } from './services/all-in-one';
import {
ParamGetCode,
Expand Down Expand Up @@ -34,51 +34,7 @@ export class JsonRpcServer extends JsonRpc(JsonRpcBase) {
res.json(result);
});

this._app.get('/api/voucher/:id', async (req, res) => {
const { genesis } = req.query;
if (!genesis) {
res.status(400).json({ error: 'Genesis not found in the request' });
return;
}

const voucherService = this._services.get(genesis.toString())?.voucher;
if (!voucherService) {
res.status(400).json({ error: 'Network is not supported' });
return;
}

try {
const voucher = await voucherService.getVoucher({ id: req.params.id, genesis: genesis.toString() });
res.json(voucher);
} catch (error) {
if (error instanceof VoucherNotFound) {
res.json(null);
return;
}
res.status(500).json({ error: 'Internal server error' });
}
});

this._app.post('/api/vouchers', async (req, res) => {
const { genesis } = req.query;
if (!genesis) {
res.status(400).json({ error: 'Genesis not found in the request' });
return;
}

const voucherService = this._services.get(genesis.toString())?.voucher;
if (!voucherService) {
res.status(400).json({ error: 'Network is not supported' });
return;
}

try {
const vouchers = await voucherService.getVouchers(req.body);
res.json(vouchers);
} catch (error) {
res.status(500).json({ error: 'Internal server error' });
}
});
this._app.use(this.createRestRouter());
}

public async run() {
Expand Down Expand Up @@ -161,13 +117,15 @@ export class JsonRpcServer extends JsonRpc(JsonRpcBase) {
}

@JsonRpcMethod('voucher.all')
@Cache(15)
@RestHandler('post', '/api/vouchers')
@Cache(60)
async voucherAll(params: ParamGetVouchers) {
return this._services.get(params.genesis).voucher.getVouchers(params);
}

@JsonRpcMethod('voucher.data')
@Cache(15)
@RestHandler('get', '/api/voucher/:id')
@Cache(300)
async voucherData(params: ParamGetVoucher) {
return this._services.get(params.genesis).voucher.getVoucher(params);
}
Expand Down
8 changes: 4 additions & 4 deletions idea/squid/src/event.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ export async function handleUserMessageRead({ ctx, event, tempState }: IHandleEv

const VOUCHERS_FROM_SPEC_VERSION = 1100;

export function handleIsVoucherIssued({ event, block, tempState, common }: IHandleEventProps<EVoucherIssued>) {
export function handleVoucherIssued({ event, block, tempState, common }: IHandleEventProps<EVoucherIssued>) {
if (block.header.specVersion < VOUCHERS_FROM_SPEC_VERSION) return;

const { call } = event;
Expand Down Expand Up @@ -231,7 +231,7 @@ export function handleIsVoucherIssued({ event, block, tempState, common }: IHand
tempState.addVoucher(voucher);
}

export async function handleIsVoucherUpdated({
export async function handleVoucherUpdated({
ctx,
event,
block,
Expand Down Expand Up @@ -277,13 +277,13 @@ export async function handleIsVoucherUpdated({
}
}

export async function handleIsVoucherDeclined({ event, block, tempState }: IHandleEventProps<EVoucherDeclined>) {
export async function handleVoucherDeclined({ event, block, tempState }: IHandleEventProps<EVoucherDeclined>) {
if (block.header.specVersion < VOUCHERS_FROM_SPEC_VERSION) return;

tempState.setVoucherDeclined(event.args.voucherId);
}

export function handleIsVoucherRevoked({ event, block, tempState }: IHandleEventProps<EVoucherRevoked>) {
export function handleVoucherRevoked({ event, block, tempState }: IHandleEventProps<EVoucherRevoked>) {
if (block.header.specVersion < VOUCHERS_FROM_SPEC_VERSION) return;

tempState.setVoucherRevoked(event.args.voucherId);
Expand Down
16 changes: 8 additions & 8 deletions idea/squid/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,10 @@ import {
import {
handleCodeChanged,
handleBalanceTransfer,
handleIsVoucherDeclined,
handleIsVoucherIssued,
handleIsVoucherRevoked,
handleIsVoucherUpdated,
handleVoucherDeclined,
handleVoucherIssued,
handleVoucherRevoked,
handleVoucherUpdated,
handleMessageQueued,
handleMessagesDispatched,
handleProgramChanged,
Expand All @@ -38,10 +38,10 @@ const callHandlers = [
{ pattern: isCodeChanged, handler: handleCodeChanged },
{ pattern: isMessagesDispatched, handler: handleMessagesDispatched },
{ pattern: isUserMessageRead, handler: handleUserMessageRead },
{ pattern: isVoucherIssued, handler: handleIsVoucherIssued },
{ pattern: isVoucherUpdated, handler: handleIsVoucherUpdated },
{ pattern: isVoucherDeclined, handler: handleIsVoucherDeclined },
{ pattern: isVoucherRevoked, handler: handleIsVoucherRevoked },
{ pattern: isVoucherIssued, handler: handleVoucherIssued },
{ pattern: isVoucherUpdated, handler: handleVoucherUpdated },
{ pattern: isVoucherDeclined, handler: handleVoucherDeclined },
{ pattern: isVoucherRevoked, handler: handleVoucherRevoked },
{ pattern: isBalanceTransfer, handler: handleBalanceTransfer },
];

Expand Down
16 changes: 8 additions & 8 deletions idea/squid/src/temp-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ export class TempState {
private messagesToProgram: Map<string, MessageToProgram>;
private events: Map<string, Event>;
private vouchers: Map<string, Voucher>;
private revoked: Set<string>;
private revokedVouchers: Set<string>;
private transfers: Map<string, bigint>;
private _ctx: ProcessorContext<Store>;
private _metadata: Metadata;
Expand All @@ -68,7 +68,7 @@ export class TempState {
this.events = new Map();
this.newPrograms = new Set();
this.vouchers = new Map();
this.revoked = new Set();
this.revokedVouchers = new Set();
this.transfers = new Map();
}

Expand All @@ -81,7 +81,7 @@ export class TempState {
this.events.clear();
this.newPrograms.clear();
this.vouchers.clear();
this.revoked.clear();
this.revokedVouchers.clear();
this.transfers.clear();
}

Expand Down Expand Up @@ -260,7 +260,7 @@ export class TempState {
}

setVoucherRevoked(id: string) {
this.revoked.add(id);
this.revokedVouchers.add(id);
}

setTransfer(id: string, amount: bigint) {
Expand Down Expand Up @@ -315,9 +315,9 @@ export class TempState {
this.vouchers.get(id)!.balance += this.transfers.get(id)!;
this.transfers.delete(id);
}
if (this.revoked.has(id)) {
if (this.revokedVouchers.has(id)) {
this.vouchers.delete(id);
this.revoked.delete(id);
this.revokedVouchers.delete(id);
}
}

Expand All @@ -327,8 +327,8 @@ export class TempState {
await this._ctx.store.save(vouchers);
}

if (this.revoked.size > 0) {
const revoked = Array.from(this.revoked);
if (this.revokedVouchers.size > 0) {
const revoked = Array.from(this.revokedVouchers);
await this._ctx.store.remove(Voucher, revoked);
}

Expand Down

0 comments on commit e5c5827

Please sign in to comment.