Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

change files, routes & add welcome route #306

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@
"name": "express-typescript-boilerplate",
"version": "1.0.14",
"description": "An Express boilerplate backend",
"author": "Edwin Hernandez",
"repository": "edwinhern/express-typescript-2024",
"author": "Alejandro Ruiz",
"repository": "alex-ruiz/express-typescript-2024",
"license": "MIT",
"main": "index.ts",
"main": "src/index.ts",
"private": true,
"scripts": {
"dev": "tsx watch --clear-screen=false src/index.ts | pino-pretty",
Expand Down
6 changes: 3 additions & 3 deletions src/api-docs/__tests__/openAPIRouter.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { StatusCodes } from "http-status-codes";
import request from "supertest";

import { app } from "@/server";
import { app } from "@/bin/server";

import { generateOpenAPIDocument } from "../openAPIDocumentGenerator";

Expand All @@ -12,7 +12,7 @@ describe("OpenAPI Router", () => {
const expectedResponse = generateOpenAPIDocument();

// Act
const response = await request(app).get("/swagger.json");
const response = await request(app).get("/swagger/swagger.json");

// Assert
expect(response.status).toBe(StatusCodes.OK);
Expand All @@ -22,7 +22,7 @@ describe("OpenAPI Router", () => {

it("should serve the Swagger UI", async () => {
// Act
const response = await request(app).get("/");
const response = await request(app).get("/swagger/");

// Assert
expect(response.status).toBe(StatusCodes.OK);
Expand Down
2 changes: 1 addition & 1 deletion src/api-docs/openAPIDocumentGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export function generateOpenAPIDocument() {
},
externalDocs: {
description: "View the raw OpenAPI Specification in JSON format",
url: "/swagger.json",
url: "/swagger/swagger.json",
},
});
}
2 changes: 1 addition & 1 deletion src/api/healthCheck/__tests__/healthCheckRouter.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { StatusCodes } from "http-status-codes";
import request from "supertest";

import { app } from "@/bin/server";
import type { ServiceResponse } from "@/common/models/serviceResponse";
import { app } from "@/server";

describe("Health Check API endpoints", () => {
it("GET / - success", async () => {
Expand Down
2 changes: 1 addition & 1 deletion src/api/user/__tests__/userRouter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import request from "supertest";

import type { User } from "@/api/user/userModel";
import { users } from "@/api/user/userRepository";
import { app } from "@/bin/server";
import type { ServiceResponse } from "@/common/models/serviceResponse";
import { app } from "@/server";

describe("User API Endpoints", () => {
describe("GET /users", () => {
Expand Down
2 changes: 1 addition & 1 deletion src/api/user/userService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { StatusCodes } from "http-status-codes";

import type { User } from "@/api/user/userModel";
import { UserRepository } from "@/api/user/userRepository";
import { logger } from "@/bin/server";
import { ServiceResponse } from "@/common/models/serviceResponse";
import { logger } from "@/server";

export class UserService {
private userRepository: UserRepository;
Expand Down
14 changes: 14 additions & 0 deletions src/api/welcome/__tests__/welcomeRouter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { StatusCodes } from "http-status-codes";
import request from "supertest";

import { app } from "@/bin/server";

describe("Welcome API endpoints", () => {
it("GET / - success", async () => {
const response = await request(app).get("/");
const result: string = response.text;

expect(response.statusCode).toEqual(StatusCodes.OK);
expect(result).toEqual("<h1>Welcome to Express Typescript Api</h1>");
});
});
22 changes: 22 additions & 0 deletions src/api/welcome/welcomeRouter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { OpenAPIRegistry } from "@asteasolutions/zod-to-openapi";
import express, { type Request, type Response, type Router } from "express";
import { z } from "zod";

import { createApiResponse } from "@/api-docs/openAPIResponseBuilders";
import { HtmlServiceResponse } from "@/common/models/htmlServiceResponse";
import { handleHtmlServiceResponse } from "@/common/utils/httpHandlers";

export const welcomeRegistry = new OpenAPIRegistry();
export const welcomeRouter: Router = express.Router();

welcomeRegistry.registerPath({
method: "get",
path: "/",
tags: ["Welcome"],
responses: createApiResponse(z.null(), "Success"),
});

welcomeRouter.get("/", (_req: Request, res: Response) => {
const htmlServiceResponse = HtmlServiceResponse.success("<h1>Welcome to Express Typescript Api</h1>");
return handleHtmlServiceResponse(htmlServiceResponse, res);
});
3 changes: 3 additions & 0 deletions src/bin/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { pino } from "pino";

export const logger = pino({ name: "Server Start" });
16 changes: 16 additions & 0 deletions src/bin/routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { openAPIRouter } from "@/api-docs/openAPIRouter";
import { healthCheckRouter } from "@/api/healthCheck/healthCheckRouter";
import { userRouter } from "@/api/user/userRouter";
import { welcomeRouter } from "@/api/welcome/welcomeRouter";
import express, { type Router } from "express";

export const router: Router = express.Router();

// Home
router.use("/", welcomeRouter);

router.use("/health-check", healthCheckRouter);
router.use("/users", userRouter);

// Swagger UI
router.use("/swagger", openAPIRouter);
13 changes: 3 additions & 10 deletions src/server.ts → src/bin/server.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,14 @@
import cors from "cors";
import express, { type Express } from "express";
import helmet from "helmet";
import { pino } from "pino";

import { openAPIRouter } from "@/api-docs/openAPIRouter";
import { healthCheckRouter } from "@/api/healthCheck/healthCheckRouter";
import { userRouter } from "@/api/user/userRouter";
import { logger } from "@/bin/logger";
import { router as globalRouter } from "@/bin/routes";
import errorHandler from "@/common/middleware/errorHandler";
import rateLimiter from "@/common/middleware/rateLimiter";
import requestLogger from "@/common/middleware/requestLogger";
import { env } from "@/common/utils/envConfig";

const logger = pino({ name: "server start" });
const app: Express = express();

// Set the application to trust the reverse proxy
Expand All @@ -28,11 +25,7 @@ app.use(rateLimiter);
app.use(requestLogger);

// Routes
app.use("/health-check", healthCheckRouter);
app.use("/users", userRouter);

// Swagger UI
app.use(openAPIRouter);
app.use(globalRouter);

// Error handlers
app.use(errorHandler());
Expand Down
26 changes: 26 additions & 0 deletions src/common/models/htmlServiceResponse.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { StatusCodes } from "http-status-codes";
import { z } from "zod";

export class HtmlServiceResponse {
readonly html: string;
readonly statusCode: number;

private constructor(html: string, statusCode: number) {
this.html = html;
this.statusCode = statusCode;
}

static success(html: string, statusCode: number = StatusCodes.OK) {
return new HtmlServiceResponse(html, statusCode);
}

static failure(html: string, statusCode: number = StatusCodes.BAD_REQUEST) {
return new HtmlServiceResponse(html, statusCode);
}
}

export const HtmlServiceResponseSchema = () =>
z.object({
html: z.string(),
statusCode: z.number(),
});
5 changes: 5 additions & 0 deletions src/common/utils/httpHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,17 @@ import type { NextFunction, Request, Response } from "express";
import { StatusCodes } from "http-status-codes";
import type { ZodError, ZodSchema } from "zod";

import type { HtmlServiceResponse } from "@/common/models/htmlServiceResponse";
import { ServiceResponse } from "@/common/models/serviceResponse";

export const handleServiceResponse = (serviceResponse: ServiceResponse<any>, response: Response) => {
return response.status(serviceResponse.statusCode).send(serviceResponse);
};

export const handleHtmlServiceResponse = (serviceResponse: HtmlServiceResponse, response: Response) => {
return response.status(serviceResponse.statusCode).send(serviceResponse.html);
};

export const validateRequest = (schema: ZodSchema) => (req: Request, res: Response, next: NextFunction) => {
try {
schema.parse({ body: req.body, query: req.query, params: req.params });
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { app, logger } from "@/bin/server";
import { env } from "@/common/utils/envConfig";
import { app, logger } from "@/server";

const server = app.listen(env.PORT, () => {
const { NODE_ENV, HOST, PORT } = env;
Expand Down