Skip to content

Commit 552af09

Browse files
reduce comments
1 parent b898985 commit 552af09

File tree

7 files changed

+16
-94
lines changed

7 files changed

+16
-94
lines changed

apps/items-service/src/config.ts

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,6 @@ export interface Config {
2626
database: DatabaseConfig;
2727
}
2828

29-
/**
30-
* Load and validate configuration from environment variables
31-
*/
3229
export function loadConfig(): Config {
3330
return {
3431
server: {

apps/items-service/src/controllers.ts

Lines changed: 0 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,6 @@ import { ItemsRepository } from "./database.js";
88
import type { CreateItemDto, HealthResponse, ItemsListResponse } from "./models.js";
99
import { json, badRequest, internalServerError, serviceUnavailable } from "./http-utils.js";
1010

11-
/**
12-
* Health check controller
13-
*/
1411
export class HealthController {
1512
constructor(
1613
private repository: ItemsRepository,
@@ -58,15 +55,9 @@ export class HealthController {
5855
}
5956
}
6057

61-
/**
62-
* Items controller
63-
*/
6458
export class ItemsController {
6559
constructor(private repository: ItemsRepository) {}
6660

67-
/**
68-
* List all items
69-
*/
7061
async list(): Promise<Response> {
7162
const tracer = trace.getTracer("items-service");
7263
return await tracer.startActiveSpan("listItems", async (span) => {
@@ -88,14 +79,10 @@ export class ItemsController {
8879
});
8980
}
9081

91-
/**
92-
* Create a new item
93-
*/
9482
async create(req: Request): Promise<Response> {
9583
const tracer = trace.getTracer("items-service");
9684
return await tracer.startActiveSpan("createItem", async (span) => {
9785
try {
98-
// Parse and validate request body
9986
let body: Partial<CreateItemDto>;
10087
try {
10188
body = (await req.json()) as Partial<CreateItemDto>;
@@ -106,14 +93,12 @@ export class ItemsController {
10693
return badRequest("invalid json");
10794
}
10895

109-
// Validate required fields
11096
if (!body?.name || typeof body.name !== "string") {
11197
span.setStatus({ code: SpanStatusCode.ERROR, message: "Name required" });
11298
span.end();
11399
return badRequest("name required");
114100
}
115101

116-
// Create item
117102
const item = await this.repository.create({ name: body.name });
118103

119104
span.setAttribute("item.id", item.id);

apps/items-service/src/database.ts

Lines changed: 3 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,7 @@ import type { DatabaseConfig } from "./config.js";
44
import type { Item, CreateItemDto } from "./models.js";
55

66
let sql: ReturnType<typeof postgres> | null = null;
7-
/**
8-
* Initialize database connection
9-
*/
7+
108
export function initDatabase(config: DatabaseConfig): ReturnType<typeof postgres> {
119
if (sql) {
1210
return sql;
@@ -26,19 +24,13 @@ export function initDatabase(config: DatabaseConfig): ReturnType<typeof postgres
2624
return sql;
2725
}
2826

29-
/**
30-
* Get the database connection
31-
*/
3227
export function getDatabase(): ReturnType<typeof postgres> {
3328
if (!sql) {
3429
throw new Error("Database not initialized. Call initDatabase first.");
3530
}
3631
return sql;
3732
}
3833

39-
/**
40-
* Initialize database schema
41-
*/
4234
export async function initSchema(): Promise<void> {
4335
const tracer = trace.getTracer("items-service");
4436
return await tracer.startActiveSpan("initDatabase", async (span) => {
@@ -51,10 +43,10 @@ export async function initSchema(): Promise<void> {
5143
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
5244
)
5345
`;
54-
console.log("Database initialized successfully");
46+
console.log("Database initialized successfully");
5547
span.setStatus({ code: SpanStatusCode.OK });
5648
} catch (error) {
57-
console.error("Failed to initialize database:", error);
49+
console.error("Failed to initialize database:", error);
5850
span.recordException(error as Error);
5951
span.setStatus({ code: SpanStatusCode.ERROR, message: String(error) });
6052
throw error;
@@ -64,19 +56,13 @@ export async function initSchema(): Promise<void> {
6456
});
6557
}
6658

67-
/**
68-
* Repository for items data access
69-
*/
7059
export class ItemsRepository {
7160
private readonly db: ReturnType<typeof postgres>;
7261

7362
constructor() {
7463
this.db = getDatabase();
7564
}
7665

77-
/**
78-
* Get all items
79-
*/
8066
async findAll(): Promise<Item[]> {
8167
return await this.db<Item[]>`
8268
SELECT id, name
@@ -85,9 +71,6 @@ export class ItemsRepository {
8571
`;
8672
}
8773

88-
/**
89-
* Create a new item
90-
*/
9174
async create(dto: CreateItemDto): Promise<Item> {
9275
const [item] = await this.db<Item[]>`
9376
INSERT INTO items (name)
@@ -97,9 +80,6 @@ export class ItemsRepository {
9780
return item;
9881
}
9982

100-
/**
101-
* Check database connection health
102-
*/
10383
async healthCheck(): Promise<boolean> {
10484
try {
10585
await this.db`SELECT 1`;

apps/items-service/src/index.ts

Lines changed: 4 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -13,54 +13,38 @@
1313
* - OTEL_SERVICE_NAME - Service name (default: items-service)
1414
* - OTEL_LOG_LEVEL - Log level (default: info)
1515
*/
16-
17-
// Initialize OpenTelemetry first, before any other imports
1816
import { initTelemetry } from "./telemetry.js";
1917
initTelemetry();
2018

21-
// Import application modules
2219
import { loadConfig } from "./config.js";
2320
import { initDatabase, initSchema, ItemsRepository } from "./database.js";
2421
import { HealthController, ItemsController } from "./controllers.js";
2522
import { Router } from "./router.js";
2623

27-
/**
28-
* Bootstrap and start the application
29-
*/
3024
async function main() {
3125
try {
32-
// Load configuration
3326
const config = loadConfig();
3427

35-
// Initialize database connection
3628
initDatabase(config.database);
3729
await initSchema();
3830

39-
// Initialize repositories
4031
const itemsRepository = new ItemsRepository();
41-
42-
// Initialize controllers
4332
const healthController = new HealthController(itemsRepository, config.server.commitSha);
4433
const itemsController = new ItemsController(itemsRepository);
45-
46-
// Initialize router
4734
const router = new Router(config.server, healthController, itemsController);
4835

49-
// Start HTTP server
5036
const server = Bun.serve({
5137
port: config.server.port,
5238
fetch: (req) => router.handle(req),
5339
});
5440

55-
// Log startup information
56-
console.log(`✅ Items service listening on http://localhost:${server.port}`);
57-
console.log(`📚 Swagger UI: http://localhost:${server.port}/docs`);
58-
console.log(`🗄️ Database: ${config.database.host}:${config.database.port}/${config.database.database}`);
41+
console.log(`Items service listening on http://localhost:${server.port}`);
42+
console.log(`Swagger UI: http://localhost:${server.port}/docs`);
43+
console.log(`Database: ${config.database.host}:${config.database.port}/${config.database.database}`);
5944
} catch (error) {
60-
console.error("Failed to start server:", error);
45+
console.error("Failed to start server:", error);
6146
process.exit(1);
6247
}
6348
}
6449

65-
// Start the application
6650
await main();

apps/items-service/src/openapi.ts

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
// openapi.ts - OpenAPI specification for the items service
2-
31
export const openapi = {
42
openapi: "3.0.3",
53
info: { title: "items API", version: "1.0.1", description: "Simple items service built with Bun" },

apps/items-service/src/router.ts

Lines changed: 0 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -10,23 +10,14 @@ import { openapi } from "./openapi.js";
1010
import { json, notFound, html } from "./http-utils.js";
1111
import type { ServerConfig } from "./config.js";
1212

13-
/**
14-
* Route handler type
15-
*/
1613
type RouteHandler = (req: Request) => Promise<Response> | Response;
1714

18-
/**
19-
* Route definition
20-
*/
2115
interface Route {
2216
method: string;
2317
path: string;
2418
handler: RouteHandler;
2519
}
2620

27-
/**
28-
* Router class for handling HTTP requests
29-
*/
3021
export class Router {
3122
private routes: Route[] = [];
3223

@@ -38,9 +29,6 @@ export class Router {
3829
this.registerRoutes();
3930
}
4031

41-
/**
42-
* Register all application routes
43-
*/
4432
private registerRoutes(): void {
4533
// Root page
4634
this.routes.push({
@@ -85,22 +73,15 @@ export class Router {
8573
});
8674
}
8775

88-
/**
89-
* Find a matching route for the request
90-
*/
9176
private findRoute(method: string, path: string): Route | undefined {
9277
return this.routes.find((route) => route.method === method && route.path === path);
9378
}
9479

95-
/**
96-
* Handle incoming HTTP request
97-
*/
9880
async handle(req: Request): Promise<Response> {
9981
const tracer = trace.getTracer("items-service");
10082
const url = new URL(req.url);
10183
const path = url.pathname;
10284

103-
// Create a span for the HTTP request
10485
return await tracer.startActiveSpan(`${req.method} ${path}`, async (span) => {
10586
try {
10687
span.setAttributes({

apps/items-service/src/telemetry.ts

Lines changed: 9 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
// telemetry.ts - OpenTelemetry configuration
1+
// OpenTelemetry configuration
22
import { NodeSDK } from "@opentelemetry/sdk-node";
33
import { getNodeAutoInstrumentations } from "@opentelemetry/auto-instrumentations-node";
44
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http";
@@ -7,13 +7,12 @@ import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from "@opentelemetry/semantic
77
import { diag, DiagConsoleLogger, DiagLogLevel } from "@opentelemetry/api";
88

99
// Configuration from environment variables
10-
const OTEL_ENABLED = true; //process.env.OTEL_ENABLED !== "false"; // Default to true
10+
const OTEL_ENABLED = process.env.OTEL_ENABLED !== "false"; // Default to true
1111
const OTEL_EXPORTER_OTLP_ENDPOINT = process.env.OTEL_EXPORTER_OTLP_ENDPOINT || "http://localhost:4318";
1212
const OTEL_SERVICE_NAME = process.env.OTEL_SERVICE_NAME || "items-service";
1313
const OTEL_SERVICE_VERSION = process.env.OTEL_SERVICE_VERSION || "1.0.0";
1414
const OTEL_LOG_LEVEL = process.env.OTEL_LOG_LEVEL || "info";
1515

16-
// Enable OpenTelemetry diagnostic logging for debugging
1716
if (OTEL_LOG_LEVEL === "debug") {
1817
diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.DEBUG);
1918
} else if (OTEL_LOG_LEVEL === "verbose") {
@@ -24,7 +23,7 @@ let sdk: NodeSDK | null = null;
2423

2524
export function initTelemetry() {
2625
if (!OTEL_ENABLED) {
27-
console.log("📊 OpenTelemetry is disabled");
26+
console.log("OpenTelemetry is disabled");
2827
return;
2928
}
3029

@@ -41,7 +40,6 @@ export function initTelemetry() {
4140
[ATTR_SERVICE_VERSION]: OTEL_SERVICE_VERSION,
4241
});
4342

44-
// Initialize the SDK
4543
sdk = new NodeSDK({
4644
resource,
4745
traceExporter,
@@ -63,12 +61,11 @@ export function initTelemetry() {
6361
],
6462
});
6563

66-
// Start the SDK
6764
sdk.start();
6865

69-
console.log(`📊 OpenTelemetry initialized`);
70-
console.log(` Service: ${OTEL_SERVICE_NAME} v${OTEL_SERVICE_VERSION}`);
71-
console.log(` Endpoint: ${OTEL_EXPORTER_OTLP_ENDPOINT}`);
66+
console.log(`OpenTelemetry initialized`);
67+
console.log(`Service: ${OTEL_SERVICE_NAME} v${OTEL_SERVICE_VERSION}`);
68+
console.log(`Endpoint: ${OTEL_EXPORTER_OTLP_ENDPOINT}`);
7269

7370
// Handle graceful shutdown
7471
process.on("SIGTERM", async () => {
@@ -81,17 +78,17 @@ export function initTelemetry() {
8178
process.exit(0);
8279
});
8380
} catch (error) {
84-
console.error("Failed to initialize OpenTelemetry:", error);
81+
console.error("Failed to initialize OpenTelemetry:", error);
8582
}
8683
}
8784

8885
export async function shutdownTelemetry() {
8986
if (sdk) {
9087
try {
9188
await sdk.shutdown();
92-
console.log("📊 OpenTelemetry shut down successfully");
89+
console.log("OpenTelemetry shut down successfully");
9390
} catch (error) {
94-
console.error("Error shutting down OpenTelemetry:", error);
91+
console.error("Error shutting down OpenTelemetry:", error);
9592
}
9693
}
9794
}

0 commit comments

Comments
 (0)