Skip to content

Commit

Permalink
refactor: remove unnecessary code
Browse files Browse the repository at this point in the history
  • Loading branch information
icfor committed Nov 30, 2023
1 parent 625f356 commit c8c9222
Show file tree
Hide file tree
Showing 11 changed files with 180 additions and 214 deletions.
127 changes: 72 additions & 55 deletions package-lock.json

Large diffs are not rendered by default.

5 changes: 1 addition & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@
"body-parser": "^1.20.1",
"cors": "^2.8.5",
"dotenv": "^16.0.3",
"express": "^4.17.1",
"graphql": "^16.6.0"
"express": "^4.17.1"
},
"devDependencies": {
"@trivago/prettier-plugin-sort-imports": "^4.3.0",
Expand All @@ -32,10 +31,8 @@
"@typescript-eslint/eslint-plugin": "^6.11.0",
"@typescript-eslint/parser": "^6.11.0",
"eslint": "^8.3.0",
"eslint-config-airbnb-base": "^15.0.0",
"eslint-config-prettier": "^9.0.0",
"eslint-import-resolver-typescript": "^3.6.1",
"eslint-plugin-import": "^2.25.3",
"eslint-plugin-prettier": "^5.0.1",
"nodemon": "^3.0.1",
"prettier": "^3.1.0",
Expand Down
7 changes: 0 additions & 7 deletions src/graphql/routes/cosmos-api.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
import { RESTDataSource } from "@apollo/datasource-rest";
import type { KeyValueCache } from "@apollo/utils.keyvaluecache";

require("dotenv").config();

export class CosmosAPI extends RESTDataSource {
override baseURL = `${process.env.PROM_QUERY_URL}/prometheus/api/v1/`;

constructor(options: { cache: KeyValueCache }) {
super(options); // this sends our server's `cache` through
}

async getAllCosmosUsers() {
return this.get(
`query?query=sum(max_over_time(tendermint_validator_delegators_total[${process.env.MAX_OVER_TIME_DURATION}]))`,
Expand Down
7 changes: 0 additions & 7 deletions src/graphql/routes/elrond-api.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
import { RESTDataSource } from "@apollo/datasource-rest";
import type { KeyValueCache } from "@apollo/utils.keyvaluecache";

require("dotenv").config();

export class ElrondAPI extends RESTDataSource {
override baseURL = `${process.env.PROM_QUERY_URL}/prometheus/api/v1/`;

constructor(options: { cache: KeyValueCache }) {
super(options); // this sends our server's `cache` through
}

async getElrondAPY() {
return this.get(
`query?query=max_over_time(elrond_provider_apr[${process.env.MAX_OVER_TIME_DURATION}])`,
Expand Down
7 changes: 0 additions & 7 deletions src/graphql/routes/oasis-api.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
import { RESTDataSource } from "@apollo/datasource-rest";
import type { KeyValueCache } from "@apollo/utils.keyvaluecache";

require("dotenv").config();

export class OasisAPI extends RESTDataSource {
override baseURL = `${process.env.PROM_QUERY_URL}/prometheus/api/v1/`;

constructor(options: { cache: KeyValueCache }) {
super(options); // this sends our server's `cache` through
}

async getOasisUsers() {
return this.get(
`query?query=max_over_time(oasis_validator_delegators_total[${process.env.MAX_OVER_TIME_DURATION}])`,
Expand Down
5 changes: 0 additions & 5 deletions src/graphql/routes/radix-api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { RESTDataSource } from "@apollo/datasource-rest";
import type { KeyValueCache } from "@apollo/utils.keyvaluecache";

const { RADIX_URL } = process.env;

Expand All @@ -18,10 +17,6 @@ type RadixResponse = {
export class RadixAPI extends RESTDataSource {
override baseURL = `${(RADIX_URL as string).replace(/\/$/, "")}/`;

constructor(options: { cache: KeyValueCache }) {
super(options); // this sends our server's `cache` through
}

async getTotalRadixSupply(): Promise<RadixResponse> {
return this.post("token/native", {
headers: {
Expand Down
7 changes: 0 additions & 7 deletions src/graphql/routes/radix-prom-api.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,8 @@
import { RESTDataSource } from "@apollo/datasource-rest";
import type { KeyValueCache } from "@apollo/utils.keyvaluecache";

require("dotenv").config();

export class RadixPromAPI extends RESTDataSource {
override baseURL = `${process.env.PROM_QUERY_URL}/prometheus/api/v1/`;

constructor(options: { cache: KeyValueCache }) {
super(options);
}

async getRadixTVL() {
return this.get(
`query?query=max_over_time(radix_validator_staked{}[${process.env.MAX_OVER_TIME_DURATION}]) * on (denom) group_left token_price`,
Expand Down
9 changes: 0 additions & 9 deletions src/graphql/routes/solana-api.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,8 @@
import { RESTDataSource } from "@apollo/datasource-rest";
// KeyValueCache is the type of Apollo server's default cache
import type { KeyValueCache } from "@apollo/utils.keyvaluecache";

// eslint-disable-next-line @typescript-eslint/no-var-requires
require("dotenv").config();

export class SolanaAPI extends RESTDataSource {
override baseURL = `${process.env.PROM_QUERY_URL}/prometheus/api/v1/`;

constructor(options: { cache: KeyValueCache }) {
super(options); // this sends our server's `cache` through
}

async getSolanaUsers() {
return this.get(
`query?query=max_over_time(solana_validator_delegators_count[${process.env.MAX_OVER_TIME_DURATION}])`,
Expand Down
9 changes: 0 additions & 9 deletions src/graphql/routes/sui-api.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,4 @@
import { RESTDataSource } from "@apollo/datasource-rest";
// KeyValueCache is the type of Apollo server's default cache
import type { KeyValueCache } from "@apollo/utils.keyvaluecache";

// eslint-disable-next-line @typescript-eslint/no-var-requires
require("dotenv").config();

if (!process.env.DEVTOOLS_API_KEY) {
throw new Error("DEVTOOLS_API_KEY is not set");
Expand All @@ -17,10 +12,6 @@ const validatorAddress =
export class SuiAPI extends RESTDataSource {
override baseURL = `https://rpc-mainnet-sui.forbole.com`;

constructor(options: { cache: KeyValueCache }) {
super(options); // this sends our server's `cache` through
}

private getRequestContent(body: unknown) {
return {
headers: {
Expand Down
106 changes: 2 additions & 104 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,107 +1,5 @@
import { ApolloServer } from "@apollo/server";
import responseCachePlugin from "@apollo/server-plugin-response-cache";
import { expressMiddleware } from "@apollo/server/express4";
import { ApolloServerPluginDrainHttpServer } from "@apollo/server/plugin/drainHttpServer";
import bodyParser from "body-parser";
import cors from "cors";
import type { NextFunction, Request, Response } from "express";
import express from "express";
import http from "node:http";

import { resolvers } from "./graphql/resolvers";
import {
CosmosAPI,
ElrondAPI,
OasisAPI,
RadixAPI,
RadixPromAPI,
SolanaAPI,
SuiAPI,
} from "./graphql/routes";
import { typeDefs } from "./graphql/typedefs";
import type { ContextValue } from "./graphql/types";

require("dotenv").config();

(async () => {
const app = express();
const httpServer = http.createServer(app);
const port = process.env.PORT || 4000;

const server = new ApolloServer({
typeDefs,
resolvers,
plugins: [
ApolloServerPluginDrainHttpServer({ httpServer }),
responseCachePlugin(),
],
});
await server.start();

app.use(express.json());

app.use(cors());

app.use(
"/graphql",
cors<cors.CorsRequest>(),
bodyParser.json(),
expressMiddleware(server, {
context: async () => {
const { cache } = server;

const context: ContextValue = {
dataSources: {
cosmosAPI: new CosmosAPI({ cache }),
elrondAPI: new ElrondAPI({ cache }),
oasisAPI: new OasisAPI({ cache }),
radixAPI: new RadixAPI({ cache }),
radixPromAPI: new RadixPromAPI({ cache }),
solanaAPI: new SolanaAPI({ cache }),
suiAPI: new SuiAPI({ cache }),
},
};

return context;
},
}),
);

// health check api
app.get("/ping", (_req: Request, res: Response, next: NextFunction) => {
try {
return res.status(200).send("pong");
} catch (err) {
next(err);
}
});

// 404 middleware
app.use((_req, _res, next) => {
const error = new Error("Not found") as ResponseError;
error.status = 404;
next(error);
});

// error handler middleware
app.use(
(
error: ResponseError,
_req: Request,
res: Response,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_next: NextFunction,
) => {
res.status(error.status || 500).send({
error: {
status: error.status || 500,
message: error.message || "Internal Server Error",
},
});
},
);

await new Promise<void>((resolve) => httpServer.listen({ port }, resolve));
const { setupServer } = require("./server");

console.log(`🚀 Server ready at http://localhost:${port}/graphql`);
})();
setupServer();
105 changes: 105 additions & 0 deletions src/server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { ApolloServer } from "@apollo/server";
import responseCachePlugin from "@apollo/server-plugin-response-cache";
import { expressMiddleware } from "@apollo/server/express4";
import { ApolloServerPluginDrainHttpServer } from "@apollo/server/plugin/drainHttpServer";
import bodyParser from "body-parser";
import cors from "cors";
import type { NextFunction, Request, Response } from "express";
import express from "express";
import http from "node:http";

import { resolvers } from "./graphql/resolvers";
import {
CosmosAPI,
ElrondAPI,
OasisAPI,
RadixAPI,
RadixPromAPI,
SolanaAPI,
SuiAPI,
} from "./graphql/routes";
import { typeDefs } from "./graphql/typedefs";
import type { ContextValue } from "./graphql/types";

export const setupServer = async () => {
const app = express();
const httpServer = http.createServer(app);
const port = process.env.PORT || 4000;

const server = new ApolloServer({
typeDefs,
resolvers,
plugins: [
ApolloServerPluginDrainHttpServer({ httpServer }),
responseCachePlugin(),
],
});
await server.start();

app.use(express.json());

app.use(cors());

app.use(
"/graphql",
cors<cors.CorsRequest>(),
bodyParser.json(),
expressMiddleware(server, {
context: async () => {
const { cache } = server;

const context: ContextValue = {
dataSources: {
cosmosAPI: new CosmosAPI({ cache }),
elrondAPI: new ElrondAPI({ cache }),
oasisAPI: new OasisAPI({ cache }),
radixAPI: new RadixAPI({ cache }),
radixPromAPI: new RadixPromAPI({ cache }),
solanaAPI: new SolanaAPI({ cache }),
suiAPI: new SuiAPI({ cache }),
},
};

return context;
},
}),
);

// health check api
app.get("/ping", (_req: Request, res: Response, next: NextFunction) => {
try {
return res.status(200).send("pong");
} catch (err) {
next(err);
}
});

// 404 middleware
app.use((_req, _res, next) => {
const error = new Error("Not found") as ResponseError;
error.status = 404;
next(error);
});

// error handler middleware
app.use(
(
error: ResponseError,
_req: Request,
res: Response,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
_next: NextFunction,
) => {
res.status(error.status || 500).send({
error: {
status: error.status || 500,
message: error.message || "Internal Server Error",
},
});
},
);

await new Promise<void>((resolve) => httpServer.listen({ port }, resolve));

console.log(`🚀 Server ready at http://localhost:${port}/graphql`);
};

0 comments on commit c8c9222

Please sign in to comment.