diff --git a/packages/rpc-cache-server/src/index.js b/packages/rpc-cache-server/src/index.js new file mode 100644 index 0000000..41a4ab3 --- /dev/null +++ b/packages/rpc-cache-server/src/index.js @@ -0,0 +1,47 @@ +const { JSONRPCServer } = require("json-rpc-2.0"); +const express = require("express"); +const bodyParser = require("body-parser"); +const redis = require("redis"); +const crypto = require("crypto"); + +const server = new JSONRPCServer(); +const redisClient = redis.createClient(); +const getProgramAccounts = function({ wormholeID }) +{ + return new Promise((resolve, reject) => { + redisClient.get(wormholeID, function(err, reply) { + if (err) { + reject(err); + } else { + if (reply === null) { + let uuid = crypto.randomUUID(); + redisClient.set(wormholeID, uuid, redis.print); + resolve(uuid); + return; + } + resolve(reply); + } + }); + }); +}; +server.addMethod("getProgramAccounts", getProgramAccounts); + +const app = express(); +app.use(bodyParser.json()); + +app.post("/json-rpc", (req, res) => { + const jsonRPCRequest = req.body; + // server.receive takes a JSON-RPC request and returns a Promise of a JSON-RPC response. + console.log("received request"); + console.log(jsonRPCRequest); + server.receive(jsonRPCRequest).then((jsonRPCResponse) => { + if (jsonRPCResponse) { + res.json(jsonRPCResponse); + } else { + console.log("no response"); + res.sendStatus(204); + } + }); +}); + +app.listen(80); diff --git a/packages/rpc-cache-server/src/test-client.js b/packages/rpc-cache-server/src/test-client.js new file mode 100644 index 0000000..61de4ea --- /dev/null +++ b/packages/rpc-cache-server/src/test-client.js @@ -0,0 +1,27 @@ +const { JSONRPCClient } = require("json-rpc-2.0"); +const axios = require("axios"); + +// JSONRPCClient needs to know how to send a JSON-RPC request. +// Tell it by passing a function to its constructor. The function must take a JSON-RPC request and send it. +const client = new JSONRPCClient((jsonRPCRequest) => + axios({ + method: "post", + url: "http://localhost:3000/json-rpc", + headers: { + "content-type": "application/json", + }, + data: jsonRPCRequest, + }).then((response) => { + if (response.status === 200) { + // Use client.receive when you received a JSON-RPC response. + return client.receive(response.data); + } else if (jsonRPCRequest.id !== undefined) { + return Promise.reject(new Error(response.statusText)); + } + }) +); + +client + .request("getProgramAccounts", { wormholeID: "WormT3McKhFJ2RkiGpdw9GKvNCrB2aB54gb2uV9MfQC" }) + .then((result) => console.log(result)); +