Skip to content

Commit

Permalink
logger and formating
Browse files Browse the repository at this point in the history
  • Loading branch information
Mathieu Lefebvre committed Oct 23, 2023
1 parent 6381514 commit 84ab7fa
Show file tree
Hide file tree
Showing 8 changed files with 177 additions and 179 deletions.
Binary file modified bun.lockb
Binary file not shown.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"dotenv": "^16.3.1",
"ethers": "^6.8.0",
"hono": "^3.7.2",
"tslog": "^4.9.2",
"zod": "^3.22.4"
},
"devDependencies": {
Expand Down
5 changes: 3 additions & 2 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ export const DEFAULT_DB_NAME = "clickhouse_sink";
export const DEFAULT_DB_USERNAME = "default";
export const DEFAULT_DB_PASSWORD = "";
export const DEFAULT_MAX_ELEMENTS_QUERIES = 10;
export const DEFAULT_VERBOSE = false;
export const DEFAULT_VERBOSE = true;

const CommanderSchema = z.object({
NODE_ENV: z.string().optional(),
Expand All @@ -23,7 +23,8 @@ const CommanderSchema = z.object({
password: z.string().default(DEFAULT_DB_PASSWORD),
maxElementsQueried: z.coerce.number().default(DEFAULT_MAX_ELEMENTS_QUERIES).describe(
'Maximum number of query elements when using arrays as parameters'
)
),
verbose: z.boolean().default(DEFAULT_VERBOSE),
});

export function decode(data: unknown) {
Expand Down
77 changes: 35 additions & 42 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,33 @@
import { OpenAPIHono } from '@hono/zod-openapi';
import { TypedResponse } from 'hono';
import { serveStatic } from 'hono/bun'
import { logger } from 'hono/logger';
import { OpenAPIHono } from "@hono/zod-openapi";
import { TypedResponse } from "hono";
import { serveStatic } from "hono/bun";
import { logger } from "./logger";
import pkg from "../package.json";
import * as routes from './routes';
import * as routes from "./routes";
import {
type SupplyResponseSchema,
type SupplySchema, type ContractSchema, type ContractResponseSchema, type BalanceSchema, type BalanceResponseSchema
} from './schemas';
import { getTotalSupply, getContract, getBalance } from './queries';
import config from './config'
import { HTTPException } from 'hono/http-exception';
type SupplySchema,
type ContractSchema,
type ContractResponseSchema,
type BalanceSchema,
type BalanceResponseSchema,
} from "./schemas";
import { getTotalSupply, getContract, getBalance } from "./queries";
import config from "./config";
import { HTTPException } from "hono/http-exception";

import { banner } from "./banner";

export function generateApp() {

const app = new OpenAPIHono();

if (config.NODE_ENV !== "production")
app.use('*', logger());

app.use('/swagger/*', serveStatic({ root: './' }))
app.use("/swagger/*", serveStatic({ root: "./" }));

app.doc('/openapi', {
openapi: '3.0.0',
app.doc("/openapi", {
openapi: "3.0.0",
info: {
version: pkg.version,
title: 'ERC20 API',
title: "ERC20 API",
},
});

Expand All @@ -40,65 +40,58 @@ export function generateApp() {
error_code = err.status;
}

logger.error(error_message);
return c.json({ error_message }, error_code);
});


app.openapi(routes.indexRoute, (c) => {
return {
response: c.text(banner())
response: c.text(banner()),
} as TypedResponse<string>;
});


app.openapi(routes.TotalSupplyQueryRoute, async (c) => {
// @ts-expect-error: Suppress type of parameter expected to be never (see https://github.com/honojs/middleware/issues/200)
const { address, block, contract } = c.req.valid('query') as SupplySchema;
const { address, block, contract } = c.req.valid("query") as SupplySchema;
if (contract) {
let supply = await getTotalSupply(address, block);
let contract_info = await getContract(address);
let result = Object.assign({}, supply, contract_info)
let result = Object.assign({}, supply, contract_info);
return {
response: c.json(result)
response: c.json(result),
} as TypedResponse<SupplyResponseSchema>;
}
else {
} else {
return {
response: c.json(await getTotalSupply(address, block))
response: c.json(await getTotalSupply(address, block)),
} as TypedResponse<SupplyResponseSchema>;
}

});





app.openapi(routes.ContractQueryRoute, async (c) => {
const { address } = c.req.valid('query') as ContractSchema;
const { address } = c.req.valid("query") as ContractSchema;
return {
response: c.json(await getContract(address))
response: c.json(await getContract(address)),
} as TypedResponse<ContractResponseSchema>;
});


app.openapi(routes.BalanceQueryRoute, async (c) => {
// @ts-expect-error: Suppress type of parameter expected to be never (see https://github.com/honojs/middleware/issues/200)
const { wallet, address, block } = c.req.valid('query') as BalanceSchema;
const { wallet, address, block } = c.req.valid("query") as BalanceSchema;
return {
response: c.json(await getBalance(wallet, address, block))
response: c.json(await getBalance(wallet, address, block)),
} as TypedResponse<BalanceResponseSchema>;
});


return app;
}
if (config.verbose) logger.enable();
logger.info(
`Server listening on http://${config.hostname}${config.port}/`
);

Bun.serve({
port: config.port,
hostname: config.hostname,
fetch: generateApp().fetch
}
)
fetch: generateApp().fetch,
});

console.log("Server listening on http://" + config.hostname + ":" + config.port + "/")
21 changes: 21 additions & 0 deletions src/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { Logger, type ILogObj } from "tslog";
import { name } from "../package.json" assert { type: "json" };

class TsLogger extends Logger<ILogObj> {
constructor() {
super();
this.settings.minLevel = 5;
this.settings.name = name;
}

public enable(type: "pretty" | "json" = "pretty") {
this.settings.type = type;
this.settings.minLevel = 0;
}

public disable() {
this.settings.type = "hidden";
}
}

export const logger = new TsLogger();
5 changes: 1 addition & 4 deletions src/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ const client = createClient({
});

function formatAddress(address: string) {
if (address.startsWith('0x')) {
if (address.startsWith("0x")) {
// Remove the "0x" prefix and return the address
return address.slice(2);
}
Expand Down Expand Up @@ -48,7 +48,6 @@ export async function getTotalSupply(
return { error: "Invalid Address" };
}
}

}

export async function getContract(address: string | undefined) {
Expand All @@ -68,7 +67,6 @@ export async function getContract(address: string | undefined) {
return { error: "Invalid Address" };
}
}

}

export async function getBalance(
Expand Down Expand Up @@ -156,5 +154,4 @@ export async function getBalance(
return { error: "Invalid Wallet" };
}
}

}
41 changes: 18 additions & 23 deletions src/routes.ts
Original file line number Diff line number Diff line change
@@ -1,71 +1,66 @@
import { createRoute } from '@hono/zod-openapi';
import * as schemas from './schemas';


import { createRoute } from "@hono/zod-openapi";
import * as schemas from "./schemas";

export const indexRoute = createRoute({
method: 'get',
path: '/',
method: "get",
path: "/",
responses: {
200: {
description: 'Index page banner.',
description: "Index page banner.",
},
},
});


export const TotalSupplyQueryRoute = createRoute({
method: 'get',
path: '/supply',
method: "get",
path: "/supply",
request: {
query: schemas.SupplySchema,
},
responses: {
200: {
content: {
'application/json': {
"application/json": {
schema: schemas.SupplyResponseSchema,
},
},
description: 'Get the total supply of an ERC20 contract',
description: "Get the total supply of an ERC20 contract",
},
},
});


export const ContractQueryRoute = createRoute({
method: 'get',
path: '/contract',
method: "get",
path: "/contract",
request: {
query: schemas.ContractSchema,
},
responses: {
200: {
content: {
'application/json': {
"application/json": {
schema: schemas.ContractResponseSchema,
},
},
description: 'Get the ERC20 contract information',
description: "Get the ERC20 contract information",
},
},
});


export const BalanceQueryRoute = createRoute({
method: 'get',
path: '/balance',
method: "get",
path: "/balance",
request: {
query: schemas.BalanceSchema,
},
responses: {
200: {
content: {
'application/json': {
"application/json": {
schema: schemas.BalanceResponseSchema,
},
},
description: 'Get the ERC20 contract information',
description: "Get the ERC20 contract information",
},
},
});
});
Loading

0 comments on commit 84ab7fa

Please sign in to comment.