Skip to content

Commit

Permalink
feat(demo): expresss proxy
Browse files Browse the repository at this point in the history
  • Loading branch information
sogunshola committed Aug 9, 2022
1 parent 668ec2e commit d542326
Show file tree
Hide file tree
Showing 8 changed files with 91 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/fuzzy-wombats-sniff.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@moralisweb3/api-utils': minor
---

body params was added to the `getDescriptors()` method
2 changes: 2 additions & 0 deletions demos/parse-server/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@ <h1>Demo Auth parse-server</h1>
<main>
<div id="error"></div>
<button class="btn" id="auth-metamask">Authenticate via Metamask</button>
<button class="btn" id="evm-version">web3api version</button>
<button class="btn" id="evm-native-balance">get native balance</button>
<div id="user"></div>
</main>

Expand Down
35 changes: 35 additions & 0 deletions demos/parse-server/public/script.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
const AUTH_API_URL = 'http://localhost:1337/api/auth';
const EVM_PROXY_URL = 'http://localhost:1337/api/evm-proxy';

const elError = document.getElementById('error');
const elUser = document.getElementById('user');
const elBtnMetamask = document.getElementById('auth-metamask');
const elBtnEvmVersion = document.getElementById('evm-version');
const elBtnNativeBalance = document.getElementById('evm-native-balance');

const handleApiPost = async (endpoint, params) => {
const result = await axios.post(`${AUTH_API_URL}/${endpoint}`, params, {
Expand All @@ -14,6 +17,18 @@ const handleApiPost = async (endpoint, params) => {
return result.data;
};

const handleEvmProxyCall = async (endpoint, params) => {
const result = await axios.post(`${EVM_PROXY_URL}/${endpoint}`, params, {
headers: {
'content-type': 'application/json',
},
});

console.log(result);

return result.data;
};

const requestMessage = (account, chain) =>
handleApiPost('request-message', {
address: account,
Expand All @@ -28,6 +43,18 @@ const verifyMessage = (message, signature) =>
network: 'evm',
});

// proxy calls
const web3apiVersion = () => {
handleEvmProxyCall('web3ApiVersion');
};

const getNativeBalance = () => {
handleEvmProxyCall('getNativeBalance', {
address: '0x992eCcC191D6F74E8Be187ed6B6AC196b08314f7',
chain: '0x4',
});
};

const connectToMetamask = async () => {
const provider = new ethers.providers.Web3Provider(window.ethereum, 'any');

Expand Down Expand Up @@ -72,6 +99,14 @@ function init() {
elBtnMetamask.addEventListener('click', async () => {
handleAuth().catch((error) => renderError(error));
});

elBtnEvmVersion.addEventListener('click', async () => {
web3apiVersion().catch((error) => renderError(error));
});

elBtnNativeBalance.addEventListener('click', async () => {
getNativeBalance().catch((error) => renderError(error));
});
}

window.addEventListener('load', () => {
Expand Down
43 changes: 43 additions & 0 deletions demos/parse-server/src/api/evmProxy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import Moralis from 'moralis';
import express from 'express';
import axios from 'axios';
import config from '../config';

const evmProxyRouter = express.Router();

const descriptors = Moralis.EvmApi.endpoints.getDescriptors();

for (const descriptor of descriptors) {
evmProxyRouter.route(`/${descriptor.name}`).post(async (req, res) => {
let url = descriptor.urlPattern;
for (const param in req.body) {
if (Object.prototype.hasOwnProperty.call(req.body, param)) {
url = url.replace(`{${param}}`, req.body[param]);
}
}
const body = descriptor.bodyParams || {};
const params = Object.keys(req.body).reduce((result, key) => {
if (!req.body[key] || key in body || descriptor.urlPatternParamNames.includes(key)) {
return result;
}
return { ...result, [key]: req.body[key] };
}, {});
await axios
.request({
method: descriptor.method,
params,
url: `${Moralis.EvmApi.baseUrl}${url}`,
data: body,
headers: {
'Content-Type': 'application/json',
'x-api-key': config.MORALIS_API_KEY,
},
})
.then((response) => res.send(response.data))
.catch((error) => {
res.status(500).send(error);
});
});
}

export default evmProxyRouter;
2 changes: 2 additions & 0 deletions demos/parse-server/src/apiRouter.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import express from 'express';
import evmProxyRouter from './api/evmProxy';
import { authRouter } from './auth/authRouter';

export const apiRouter = express.Router();

apiRouter.use('/auth', authRouter);
apiRouter.use('/evm-proxy', evmProxyRouter);
2 changes: 2 additions & 0 deletions packages/apiUtils/src/resolvers/Endpoints.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ export interface EndpointDescriptor {
urlPatternParamNames: string[];
urlPattern: string;
method: EndpointMethod;
bodyParams?: readonly (string | number | symbol)[];
}

export class Endpoints {
Expand Down Expand Up @@ -59,6 +60,7 @@ export class Endpoints {
urlPatternParamNames,
urlPattern,
method: endpoint.method || 'get',
bodyParams: endpoint.bodyParams,
};
});
}
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/Modules/ApiModule.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { MoralisCore } from '../MoralisCore';
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export abstract class ApiModule<Events extends EventMap = any> extends Module<Events> {
public constructor(name: string, core: MoralisCore, protected readonly baseUrl: string) {
public constructor(name: string, core: MoralisCore, public readonly baseUrl: string) {
super(name, core, ModuleType.API);
}
}
2 changes: 1 addition & 1 deletion packages/core/src/version.ts
Original file line number Diff line number Diff line change
@@ -1 +1 @@
export const LIB_VERSION = "2.0.0-beta.7";
export const LIB_VERSION = "2.0.0-beta.8";

0 comments on commit d542326

Please sign in to comment.