Skip to content

Commit

Permalink
Apply GQL and RPC server middlewares ordered on requested paths
Browse files Browse the repository at this point in the history
  • Loading branch information
prathamesh0 committed Oct 11, 2024
1 parent 87ba694 commit 5b3d687
Showing 1 changed file with 38 additions and 10 deletions.
48 changes: 38 additions & 10 deletions packages/util/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,39 +97,67 @@ export const createAndStartServer = async (

await server.start();

server.applyMiddleware({
app,
path: gqlPath
});

const rpcPath = serverConfig.ethRPC?.path ?? DEFAULT_ETH_RPC_PATH;
const rpcEnabled = serverConfig.ethRPC?.enabled;

// Apply GraphQL middleware
const applyGraphQLMiddleware = () => {
console.log('applyGraphQLMiddleware');
server.applyMiddleware({
app,
path: gqlPath
});
};

// Apply RPC middleware
const applyRPCMiddleware = () => {
console.log('applyRPCMiddleware');
if (!rpcEnabled) {
return;
}

if (serverConfig.ethRPC?.enabled) {
// Create a JSON-RPC server to handle ETH RPC calls
const rpcServer = jayson.Server(ethRPCHandlers);

// Mount the JSON-RPC server to ETH_RPC_PATH
// Mount the JSON-RPC server to rpcPath
app.use(
rpcPath,
jsonParser(),
(req: any, res: any, next: () => void) => {
// Convert all GET requests to POST to avoid getting rejected from jayson server middleware
// Convert all GET requests to POST to avoid getting rejected by jayson server middleware
if (jayson.Utils.isMethod(req, 'GET')) {
req.method = 'POST';
}
next();
},
rpcServer.middleware()
);
};

// Apply middlewares based on path specificity
if (isPathMoreSpecific(rpcPath, gqlPath)) {
applyRPCMiddleware();
applyGraphQLMiddleware();
} else {
applyGraphQLMiddleware();
applyRPCMiddleware();
}

httpServer.listen(port, host, () => {
log(`GQL server is listening on http://${host}:${port}${server.graphqlPath}`);
log(`GQL server is listening on http://${host}:${port}${gqlPath}`);

if (serverConfig.ethRPC?.enabled) {
if (rpcEnabled) {
log(`ETH JSON RPC server is listening on http://${host}:${port}${rpcPath}`);
}
});

return server;
};

// Determine which path is more specific (more segments)
function isPathMoreSpecific (path1: string, path2: string) {
const path1Segments = path1.split('/').filter(segment => segment !== '');
const path2Segments = path2.split('/').filter(segment => segment !== '');

return path1Segments.length > path2Segments.length;
}

0 comments on commit 5b3d687

Please sign in to comment.