├── src ├── database │ ├── schema │ │ ├── index.ts │ │ └── users.sql.ts │ └── drizzle.ts ├── lib │ ├── utils │ │ ├── common.ts │ │ ├── logger.ts │ │ ├── create-app.ts │ │ └── openapi │ │ │ ├── configure-openapi-spec.ts │ │ │ └── helpers.ts │ ├── middlewares │ │ ├── not-found.ts │ │ └── error-handler.ts │ ├── @types │ │ └── app.ts │ └── constants │ │ └── http-status-codes.ts ├── routes │ ├── users │ │ ├── index.ts │ │ ├── user.test.ts │ │ ├── user.handler.ts │ │ └── user.route.ts │ └── root-router.ts ├── index.ts ├── app.ts ├── utils │ └── logger.ts └── env.ts ├── .vscode ├── extensions.json └── settings.json ├── .prettierrc ├── .env.example ├── vitest.config.ts ├── .gitignore ├── tsconfig.json ├── eslint.config.mjs ├── package.json └── README.md /src/database/schema/index.ts: -------------------------------------------------------------------------------- 1 | export { users } from "./users.sql"; 2 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | "recommendations": [ 3 | "dbaeumer.vscode-eslint", 4 | "yoavbls.pretty-ts-errors" 5 | ] 6 | } -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": true, 3 | "trailingComma": "all", 4 | "singleQuote": false, 5 | "bracketSameLine": true, 6 | "printWidth": 80 7 | } -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | NODE_ENV=dev 2 | 3 | LOG_LEVEL=debug 4 | 5 | SERVER_PORT=3000 6 | 7 | DB_HOST=localhost 8 | DB_PORT=3306 9 | DB_USER= 10 | DB_PASS= 11 | DB_NAME= -------------------------------------------------------------------------------- /vitest.config.ts: -------------------------------------------------------------------------------- 1 | import path from "node:path"; 2 | import { defineConfig } from "vitest/config"; 3 | 4 | export default defineConfig({ 5 | resolve: { 6 | alias: { 7 | "@": path.resolve(__dirname, "./src"), 8 | }, 9 | }, 10 | }); 11 | -------------------------------------------------------------------------------- /src/lib/utils/common.ts: -------------------------------------------------------------------------------- 1 | import path from "node:path"; 2 | import { fileURLToPath } from "node:url"; 3 | 4 | // Resolve __dirname for ES modules 5 | export const __filename = fileURLToPath(import.meta.url); 6 | export const __dirname = path.dirname(__filename); 7 | -------------------------------------------------------------------------------- /src/lib/middlewares/not-found.ts: -------------------------------------------------------------------------------- 1 | import type { NotFoundHandler } from "hono"; 2 | 3 | import { NOT_FOUND } from "../constants/http-status-codes"; 4 | 5 | export const notFound: NotFoundHandler = (c) => { 6 | return c.json( 7 | { 8 | message: "Not Found", 9 | route: c.req.path, 10 | }, 11 | NOT_FOUND, 12 | ); 13 | }; 14 | -------------------------------------------------------------------------------- /src/lib/@types/app.ts: -------------------------------------------------------------------------------- 1 | import type { PinoLogger } from "hono-pino"; 2 | 3 | import type { OpenAPIHono, RouteConfig, RouteHandler } from "@hono/zod-openapi"; 4 | 5 | export interface AppBindings { 6 | Variables: { 7 | logger: PinoLogger; 8 | }; 9 | } 10 | 11 | export type AppOpenAPI = OpenAPIHono; 12 | export type AppRouteHandler = RouteHandler< 13 | R, 14 | AppBindings 15 | >; 16 | -------------------------------------------------------------------------------- /src/routes/users/index.ts: -------------------------------------------------------------------------------- 1 | import { createRouter } from "@/lib/utils/create-app"; 2 | 3 | import * as handlers from "./user.handler"; 4 | import * as routes from "./user.route"; 5 | 6 | const UserRouter = createRouter() 7 | .openapi(routes.CreateUser, handlers.CreateUserHandler) 8 | .openapi(routes.GetUserByID, handlers.GetUserByIDHandler) 9 | .openapi(routes.GetAllUsers, handlers.GetAllUsersHandler); 10 | 11 | export default UserRouter; 12 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import ENV from "@/env"; 2 | import { logger } from "@/utils/logger"; 3 | import { serve } from "@hono/node-server"; 4 | 5 | import { app } from "./app"; 6 | 7 | const port = ENV.SERVER_PORT; 8 | 9 | logger.info(` 10 | Server is up and running... 11 | 12 | Server: http://localhost:${port} 13 | Documentation: http://localhost:${port}/reference 14 | `); 15 | 16 | serve({ 17 | fetch: app.fetch, 18 | port, 19 | }); 20 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # dev 2 | .yarn/ 3 | !.yarn/releases 4 | 5 | .vscode/* 6 | !.vscode/launch.json 7 | !.vscode/settings.json 8 | !.vscode/extensions.json 9 | !.vscode/*.code-snippets 10 | 11 | .idea/* 12 | 13 | # deps 14 | node_modules/ 15 | 16 | # env 17 | .env 18 | .env.production 19 | .env.test 20 | 21 | # logs 22 | logs/ 23 | *.log 24 | npm-debug.log* 25 | yarn-debug.log* 26 | yarn-error.log* 27 | pnpm-debug.log* 28 | lerna-debug.log* 29 | 30 | # misc 31 | .DS_Store 32 | 33 | # dist / build 34 | dist/ 35 | build/ -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ESNext", 4 | "jsx": "react-jsx", 5 | "jsxImportSource": "hono/jsx", 6 | "baseUrl": "./", 7 | "module": "ESNext", 8 | "moduleResolution": "Bundler", 9 | "paths": { 10 | "@/*": ["./src/*"] 11 | }, 12 | "typeRoots": ["./node_modules/@types"], 13 | "types": [ 14 | "node" 15 | ], 16 | "strict": true, 17 | "outDir": "./dist", 18 | "skipLibCheck": true 19 | }, 20 | "tsc-alias": { 21 | "resolveFullPaths": true 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/routes/users/user.test.ts: -------------------------------------------------------------------------------- 1 | import { testClient } from "hono/testing"; 2 | import { describe, expect, it } from "vitest"; 3 | 4 | import createApp from "@/lib/utils/create-app"; 5 | 6 | import UserRouter from "./index"; 7 | 8 | describe("[user]", () => { 9 | it("should respond with an array", async () => { 10 | const client = testClient(createApp().route("/", UserRouter)); 11 | 12 | const result = await client.users.$get(); 13 | const json = await result.json(); 14 | 15 | expect(json.success).toBe(true); 16 | expect(json.data.length).toBeGreaterThanOrEqual(0); 17 | }); 18 | }); 19 | -------------------------------------------------------------------------------- /src/database/drizzle.ts: -------------------------------------------------------------------------------- 1 | import type { Logger as DrizzleLogger } from "drizzle-orm"; 2 | 3 | import { drizzle } from "drizzle-orm/mysql2"; 4 | 5 | import ENV from "@/env"; 6 | import { logger } from "@/utils/logger"; 7 | 8 | import * as schema from "./schema"; 9 | 10 | class QueryLogger implements DrizzleLogger { 11 | logQuery(query: string, params: unknown[]): void { 12 | logger.debug(JSON.stringify({ query, params })); 13 | } 14 | } 15 | 16 | export const database = drizzle({ 17 | connection: { 18 | host: ENV.DB_HOST, 19 | port: ENV.DB_PORT, 20 | user: ENV.DB_USER, 21 | password: ENV.DB_PASS, 22 | database: ENV.DB_NAME, 23 | }, 24 | logger: new QueryLogger(), 25 | mode: "default", 26 | schema, 27 | }); 28 | -------------------------------------------------------------------------------- /src/lib/utils/logger.ts: -------------------------------------------------------------------------------- 1 | import { logger } from "hono-pino"; 2 | import { randomUUID } from "node:crypto"; 3 | import pino from "pino"; 4 | 5 | export type StreamArray = (pino.DestinationStream | pino.StreamEntry)[] | pino.DestinationStream | pino.StreamEntry; 6 | 7 | export function PinoLogger(level: pino.Level, streams: StreamArray) { 8 | return logger({ 9 | pino: pino( 10 | { 11 | level, 12 | name: "request-logs", 13 | }, 14 | pino.multistream(streams), 15 | ), 16 | http: { 17 | reqId: () => randomUUID(), 18 | }, 19 | }); 20 | } 21 | 22 | export function Logger(level: pino.Level, streams: StreamArray) { 23 | return pino( 24 | { name: "app-logs", level }, 25 | pino.multistream(streams), 26 | ); 27 | } 28 | -------------------------------------------------------------------------------- /src/lib/middlewares/error-handler.ts: -------------------------------------------------------------------------------- 1 | import type { ErrorHandler } from "hono"; 2 | import type { StatusCode } from "hono/utils/http-status"; 3 | 4 | import { env } from "node:process"; 5 | 6 | import { INTERNAL_SERVER_ERROR, OK } from "../constants/http-status-codes"; 7 | 8 | export const onError: ErrorHandler = (err, c) => { 9 | const currentStatus = 10 | "status" in err ? err.status : c.newResponse(null).status; 11 | 12 | const statusCode = 13 | currentStatus !== OK 14 | ? (currentStatus as StatusCode) 15 | : INTERNAL_SERVER_ERROR; 16 | 17 | const environment = c.env?.NODE_ENV || env.NODE_ENV; 18 | return c.json( 19 | { 20 | message: err.message, 21 | stack: environment === "prod" ? undefined : err.stack, 22 | }, 23 | statusCode, 24 | ); 25 | }; 26 | -------------------------------------------------------------------------------- /src/routes/root-router.ts: -------------------------------------------------------------------------------- 1 | import * as HTTPStatusCodes from "@/lib/constants/http-status-codes"; 2 | import { createRouter } from "@/lib/utils/create-app"; 3 | import { createSuccessSchema, jsonContent } from "@/lib/utils/openapi/helpers"; 4 | import { createRoute, z } from "@hono/zod-openapi"; 5 | 6 | const RootRouter = createRouter().openapi( 7 | createRoute({ 8 | method: "get", 9 | path: "/", 10 | tags: ["Root"], 11 | responses: { 12 | [HTTPStatusCodes.OK]: jsonContent( 13 | createSuccessSchema( 14 | z.object({ 15 | message: z.string(), 16 | }), 17 | ), 18 | "Root Path", 19 | ), 20 | }, 21 | }), 22 | (c) => { 23 | return c.json({ 24 | success: true, 25 | data: { 26 | message: "Hello World", 27 | }, 28 | }); 29 | }, 30 | ); 31 | 32 | export default RootRouter; 33 | -------------------------------------------------------------------------------- /src/lib/utils/create-app.ts: -------------------------------------------------------------------------------- 1 | import { OpenAPIHono } from "@hono/zod-openapi"; 2 | 3 | import type { AppBindings, AppOpenAPI } from "../@types/app"; 4 | 5 | import { onError } from "../middlewares/error-handler"; 6 | import { notFound } from "../middlewares/not-found"; 7 | import { ValidationHook } from "./openapi/configure-openapi-spec"; 8 | 9 | export function createRouter() { 10 | const app = new OpenAPIHono({ 11 | strict: false, 12 | defaultHook: ValidationHook, 13 | }); 14 | 15 | return app; 16 | } 17 | 18 | function createApp() { 19 | const app = createRouter(); 20 | 21 | app.notFound(notFound); 22 | app.onError(onError); 23 | 24 | return app; 25 | } 26 | 27 | export function createTestRouter(router: AppOpenAPI) { 28 | const testApp = createApp(); 29 | testApp.route("/", router); 30 | return testApp; 31 | } 32 | 33 | export default createApp; 34 | -------------------------------------------------------------------------------- /src/app.ts: -------------------------------------------------------------------------------- 1 | import { prettyJSON } from "hono/pretty-json"; 2 | import { secureHeaders } from "hono/secure-headers"; 3 | 4 | import ENV from "@/env"; 5 | import createApp from "@/lib/utils/create-app"; 6 | import configureOpenApiSpec from "@/lib/utils/openapi/configure-openapi-spec"; 7 | import RootRouter from "@/routes/root-router"; 8 | import UserRouter from "@/routes/users"; 9 | import { pinoHttpLogger } from "@/utils/logger"; 10 | 11 | import packageJSON from "../package.json" with { type: "json" }; 12 | 13 | const app = createApp(); 14 | 15 | app.use(secureHeaders()); 16 | app.use(pinoHttpLogger()); 17 | app.use(prettyJSON()); 18 | 19 | if (ENV.NODE_ENV !== "prod") { 20 | configureOpenApiSpec(app, { 21 | title: packageJSON.name, 22 | version: packageJSON.version, 23 | }); 24 | } 25 | 26 | const _app = app.route("/", RootRouter).route("/", UserRouter); 27 | 28 | export { app }; 29 | export type App = typeof _app; 30 | -------------------------------------------------------------------------------- /src/utils/logger.ts: -------------------------------------------------------------------------------- 1 | import { join } from "node:path"; 2 | import { cwd } from "node:process"; 3 | import pretty from "pino-pretty"; 4 | import { createStream } from "rotating-file-stream"; 5 | 6 | import type { StreamArray } from "@/lib/utils/logger"; 7 | 8 | import ENV from "@/env"; 9 | import { Logger, PinoLogger } from "@/lib/utils/logger"; 10 | 11 | const logFileStream = createStream("combined.log", { 12 | interval: "1d", 13 | compress: "gzip", 14 | path: join(cwd(), "logs"), 15 | }); 16 | 17 | const errorFileStream = createStream("error.log", { 18 | interval: "1d", 19 | compress: "gzip", 20 | path: join(cwd(), "logs"), 21 | }); 22 | 23 | const streams: StreamArray = [ 24 | { stream: pretty(), level: "debug" }, 25 | { stream: logFileStream }, 26 | { stream: errorFileStream, level: "error" }, 27 | ]; 28 | 29 | export const logger = Logger(ENV.LOG_LEVEL, streams); 30 | export const pinoHttpLogger = () => PinoLogger(ENV.LOG_LEVEL, streams); 31 | -------------------------------------------------------------------------------- /src/lib/utils/openapi/configure-openapi-spec.ts: -------------------------------------------------------------------------------- 1 | import type { Hook } from "@hono/zod-openapi"; 2 | 3 | import { apiReference } from "@scalar/hono-api-reference"; 4 | 5 | import type { AppOpenAPI } from "../../@types/app"; 6 | 7 | import { UNPROCESSABLE_ENTITY } from "../../constants/http-status-codes"; 8 | 9 | function configureOpenApiSpec(app: AppOpenAPI, info: { 10 | title: string; 11 | version: string; 12 | }) { 13 | app.doc("/openapi", { 14 | openapi: "3.0.0", 15 | info: { 16 | title: info.title, 17 | version: info.version, 18 | }, 19 | }); 20 | 21 | app.get( 22 | "/reference", 23 | apiReference({ 24 | theme: "saturn", 25 | layout: "classic", 26 | defaultHttpClient: { 27 | clientKey: "fetch", 28 | targetKey: "javascript", 29 | }, 30 | spec: { 31 | url: "/openapi", 32 | }, 33 | }), 34 | ); 35 | } 36 | 37 | export const ValidationHook: Hook = (result, c) => { 38 | if (!result.success) { 39 | return c.json( 40 | { 41 | success: result.success, 42 | error: result.error, 43 | }, 44 | UNPROCESSABLE_ENTITY, 45 | ); 46 | } 47 | }; 48 | 49 | export default configureOpenApiSpec; 50 | -------------------------------------------------------------------------------- /src/env.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-magic-numbers */ 2 | 3 | import { config } from "dotenv"; 4 | import { expand } from "dotenv-expand"; 5 | import path from "node:path"; 6 | import { cwd, env } from "node:process"; 7 | import { z } from "zod"; 8 | 9 | expand(config({ 10 | path: path.resolve(cwd(), env.NODE_ENV === "test" ? ".env.test" : ".env"), 11 | })); 12 | 13 | const EnvSchema = z.object({ 14 | NODE_ENV: z.enum(["dev", "stage", "uat", "preprod", "prod", "test"]).default("dev"), 15 | 16 | SERVER_PORT: z.coerce.number().default(3000), 17 | 18 | LOG_LEVEL: z 19 | .enum(["fatal", "error", "warn", "info", "debug", "trace"]) 20 | .default("debug"), 21 | 22 | DB_HOST: z.string().default("localhost"), 23 | DB_PORT: z.coerce.number().default(3306), 24 | DB_USER: z.string(), 25 | DB_PASS: z.string(), 26 | DB_NAME: z.string(), 27 | }); 28 | 29 | export type ENV = z.infer; 30 | 31 | // eslint-disable-next-line import/no-mutable-exports, ts/no-redeclare 32 | let ENV: ENV; 33 | 34 | try { 35 | ENV = EnvSchema.parse(env); 36 | } catch (error) { 37 | if (error instanceof z.ZodError) { 38 | console.error("❌ Invalid .env file"); 39 | console.error(error.flatten()?.fieldErrors); 40 | 41 | process.exit(1); 42 | } 43 | } 44 | 45 | // eslint-disable-next-line ts/ban-ts-comment 46 | // @ts-expect-error 47 | export default ENV; 48 | -------------------------------------------------------------------------------- /eslint.config.mjs: -------------------------------------------------------------------------------- 1 | import drizzle from "eslint-plugin-drizzle"; 2 | 3 | import antfu from "@antfu/eslint-config"; 4 | 5 | export default antfu( 6 | { 7 | type: "app", 8 | typescript: true, 9 | formatters: true, 10 | stylistic: { 11 | indent: 2, 12 | semi: true, 13 | quotes: "double", 14 | }, 15 | ignores: ["**/migrations/*"], 16 | }, 17 | { 18 | rules: { 19 | "no-console": ["warn"], 20 | "antfu/no-top-level-await": ["off"], 21 | "node/prefer-global/process": ["off"], 22 | "node/no-process-env": ["error"], 23 | "style/brace-style": ["error", "1tbs"], 24 | "style/operator-linebreak": ["off"], 25 | "no-magic-numbers": [ 26 | "error", 27 | { 28 | ignore: [0, 1], 29 | ignoreArrayIndexes: true, 30 | }, 31 | ], 32 | "perfectionist/sort-imports": [ 33 | "error", 34 | { 35 | internalPattern: ["@\/*"], 36 | }, 37 | ], 38 | "unicorn/filename-case": [ 39 | "error", 40 | { 41 | case: "kebabCase", 42 | ignore: ["README.md"], 43 | }, 44 | ], 45 | }, 46 | }, 47 | { 48 | plugins: { 49 | drizzle, 50 | }, 51 | rules: { 52 | "drizzle/enforce-delete-with-where": ["error"], 53 | "drizzle/enforce-update-with-where": ["error"], 54 | }, 55 | }, 56 | ); 57 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "template", 3 | "type": "module", 4 | "version": "1.0.1", 5 | "engines": { 6 | "pnpm": ">=10.2.0" 7 | }, 8 | "scripts": { 9 | "dev": "tsx watch src/index.ts", 10 | "type-check": "tsc --noEmit", 11 | "build": "tsc && tsc-alias", 12 | "start": "node ./dist/src/index.js", 13 | "lint": "eslint ./src", 14 | "lint:fix": "eslint ./src --fix", 15 | "fmt": "prettier --write ./src", 16 | "test": "vitest" 17 | }, 18 | "dependencies": { 19 | "@asteasolutions/zod-to-openapi": "^7.2.0", 20 | "@hono/node-server": "^1.13.7", 21 | "@hono/zod-openapi": "^0.17.1", 22 | "@scalar/hono-api-reference": "^0.5.159", 23 | "dotenv": "^16.4.5", 24 | "dotenv-expand": "^12.0.0", 25 | "drizzle-orm": "^0.36.3", 26 | "drizzle-zod": "^0.5.1", 27 | "hono": "^4.6.10", 28 | "hono-pino": "^0.6.0", 29 | "mysql2": "^3.11.4", 30 | "neverthrow": "^8.1.1", 31 | "pino": "^9.5.0", 32 | "pino-pretty": "^13.0.0", 33 | "rotating-file-stream": "^3.2.5", 34 | "zod": "^3.23.8" 35 | }, 36 | "devDependencies": { 37 | "@antfu/eslint-config": "^4.2.0", 38 | "@types/node": "^22.9.0", 39 | "cross-env": "^7.0.3", 40 | "eslint": "^9.15.0", 41 | "eslint-plugin-drizzle": "^0.2.3", 42 | "eslint-plugin-format": "^0.1.2", 43 | "tsc-alias": "^1.8.10", 44 | "tsx": "^4.7.1", 45 | "vitest": ">=2.1.9" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | // Disable the default formatter, use eslint instead 3 | "prettier.enable": false, 4 | "editor.formatOnSave": false, 5 | 6 | // Auto fix 7 | "editor.codeActionsOnSave": { 8 | "source.fixAll.eslint": "explicit", 9 | "source.organizeImports": "never" 10 | }, 11 | 12 | // Silent the stylistic rules in you IDE, but still auto fix them 13 | "eslint.rules.customizations": [ 14 | { "rule": "style/*", "severity": "off", "fixable": true }, 15 | { "rule": "format/*", "severity": "off", "fixable": true }, 16 | { "rule": "*-indent", "severity": "off", "fixable": true }, 17 | { "rule": "*-spacing", "severity": "off", "fixable": true }, 18 | { "rule": "*-spaces", "severity": "off", "fixable": true }, 19 | { "rule": "*-order", "severity": "off", "fixable": true }, 20 | { "rule": "*-dangle", "severity": "off", "fixable": true }, 21 | { "rule": "*-newline", "severity": "off", "fixable": true }, 22 | { "rule": "*quotes", "severity": "off", "fixable": true }, 23 | { "rule": "*semi", "severity": "off", "fixable": true } 24 | ], 25 | 26 | // Enable eslint for all supported languages 27 | "eslint.validate": [ 28 | "javascript", 29 | "javascriptreact", 30 | "typescript", 31 | "typescriptreact", 32 | "vue", 33 | "html", 34 | "markdown", 35 | "json", 36 | "json5", 37 | "jsonc", 38 | "yaml", 39 | "toml", 40 | "xml", 41 | "gql", 42 | "graphql", 43 | "astro", 44 | "svelte", 45 | "css", 46 | "less", 47 | "scss", 48 | "pcss", 49 | "postcss" 50 | ] 51 | } 52 | -------------------------------------------------------------------------------- /src/database/schema/users.sql.ts: -------------------------------------------------------------------------------- 1 | import { 2 | datetime, 3 | int, 4 | mysqlTable, 5 | text, 6 | varchar, 7 | } from "drizzle-orm/mysql-core"; 8 | import { createInsertSchema, createSelectSchema } from "drizzle-zod"; 9 | 10 | import type { z } from "@hono/zod-openapi"; 11 | 12 | const MAX_PASSWORD_LENGTH = 70; 13 | 14 | export const users = mysqlTable("users", { 15 | id: int("id", { unsigned: true }).primaryKey().autoincrement(), 16 | name: varchar("name", { length: 255 }), 17 | email: varchar("email", { length: 255 }).unique().notNull(), 18 | password: text("password").notNull(), 19 | createdAt: datetime("created_at", { mode: "string" }).default( 20 | "CURRENT_TIMESTAMP", 21 | ), 22 | }); 23 | 24 | export const selectUsersSchema = createSelectSchema(users); 25 | export const selectUsersSchemaOpenAPI = selectUsersSchema.openapi({ 26 | example: { 27 | id: 1, 28 | name: "John Doe", 29 | email: "john.doe@example.com", 30 | password: "super-secret-password", 31 | createdAt: new Date().toISOString(), 32 | }, 33 | }); 34 | export type SelectUsersSchema = z.infer; 35 | 36 | export const insertUsersSchema = createInsertSchema(users, { 37 | name: s => s.name.min(1), 38 | email: s => s.email.email(), 39 | password: s => s.password.min(1).max(MAX_PASSWORD_LENGTH), 40 | }) 41 | .required({ name: true }) 42 | .omit({ id: true, createdAt: true }) 43 | .openapi({ 44 | example: { 45 | name: "John Doe", 46 | email: "john.doe@example.com", 47 | password: "super-secret-password", 48 | }, 49 | }); 50 | export type InsertUsersSchema = z.infer; 51 | -------------------------------------------------------------------------------- /src/routes/users/user.handler.ts: -------------------------------------------------------------------------------- 1 | import { eq } from "drizzle-orm"; 2 | 3 | import type { AppRouteHandler } from "@/lib/@types/app"; 4 | 5 | import { database } from "@/database/drizzle"; 6 | import { users } from "@/database/schema/users.sql"; 7 | import * as HTTPStatusCodes from "@/lib/constants/http-status-codes"; 8 | 9 | import type { CreateUserRoute, GetAllUsersRoute, GetUserByIDRoute } from "./user.route"; 10 | 11 | export const CreateUserHandler: AppRouteHandler = async ( 12 | ctx, 13 | ) => { 14 | const json = ctx.req.valid("json"); 15 | 16 | const [result] = await database 17 | .insert(users) 18 | .values({ 19 | name: json.name, 20 | email: json.email, 21 | password: json.password, 22 | }) 23 | .$returningId(); 24 | 25 | return ctx.json( 26 | { 27 | success: true, 28 | data: { ...result, ...json }, 29 | }, 30 | HTTPStatusCodes.OK, 31 | ); 32 | }; 33 | 34 | export const GetUserByIDHandler: AppRouteHandler = async ( 35 | ctx, 36 | ) => { 37 | const { id } = ctx.req.valid("param"); 38 | 39 | const [result] = await database 40 | .select() 41 | .from(users) 42 | .where(eq(users.id, id)) 43 | .limit(1); 44 | 45 | if (!result) { 46 | return ctx.json( 47 | { 48 | success: false, 49 | error: { 50 | issues: [{ message: "User not found!" }], 51 | }, 52 | }, 53 | HTTPStatusCodes.NOT_FOUND, 54 | ); 55 | } 56 | 57 | return ctx.json({ success: true, data: result }, HTTPStatusCodes.OK); 58 | }; 59 | 60 | export const GetAllUsersHandler: AppRouteHandler = async ( 61 | ctx, 62 | ) => { 63 | // const result = await database.select().from(users); 64 | const result = await database.query.users.findMany(); 65 | 66 | return ctx.json( 67 | { 68 | success: true, 69 | data: result, 70 | }, 71 | HTTPStatusCodes.OK, 72 | ); 73 | }; 74 | -------------------------------------------------------------------------------- /src/routes/users/user.route.ts: -------------------------------------------------------------------------------- 1 | import { 2 | insertUsersSchema, 3 | selectUsersSchemaOpenAPI, 4 | } from "@/database/schema/users.sql"; 5 | import { 6 | NOT_FOUND, 7 | OK, 8 | UNPROCESSABLE_ENTITY, 9 | } from "@/lib/constants/http-status-codes"; 10 | import { 11 | createErrorSchema, 12 | createSuccessSchema, 13 | createValidationErrorSchema, 14 | jsonContent, 15 | } from "@/lib/utils/openapi/helpers"; 16 | import { createRoute, z } from "@hono/zod-openapi"; 17 | 18 | export const tags = ["Users"]; 19 | 20 | export const CreateUser = createRoute({ 21 | path: "/users", 22 | method: "post", 23 | tags, 24 | request: { 25 | body: jsonContent(insertUsersSchema, "Request Body"), 26 | }, 27 | responses: { 28 | [OK]: jsonContent( 29 | createSuccessSchema(selectUsersSchemaOpenAPI), 30 | "Create User", 31 | ), 32 | [UNPROCESSABLE_ENTITY]: jsonContent( 33 | createValidationErrorSchema(insertUsersSchema), 34 | "Validation Error(s)", 35 | ), 36 | }, 37 | }); 38 | export type CreateUserRoute = typeof CreateUser; 39 | 40 | export const GetUserByID = createRoute({ 41 | path: "/users/{id}", 42 | method: "get", 43 | tags, 44 | request: { 45 | params: z.object({ id: z.coerce.number() }).openapi({ example: { id: 1 } }), 46 | }, 47 | responses: { 48 | [OK]: jsonContent(createSuccessSchema(selectUsersSchemaOpenAPI), "User"), 49 | [NOT_FOUND]: jsonContent(createErrorSchema("User not found!"), "Not Found"), 50 | [UNPROCESSABLE_ENTITY]: jsonContent( 51 | createValidationErrorSchema( 52 | z.object({ id: z.coerce.number() }).openapi({ example: { id: 1 } }), 53 | ), 54 | "Validation Error(s)", 55 | ), 56 | }, 57 | }); 58 | export type GetUserByIDRoute = typeof GetUserByID; 59 | 60 | export const GetAllUsers = createRoute({ 61 | path: "/users", 62 | method: "get", 63 | tags, 64 | responses: { 65 | [OK]: jsonContent( 66 | createSuccessSchema(z.array(selectUsersSchemaOpenAPI)), 67 | "All Users", 68 | ), 69 | }, 70 | }); 71 | export type GetAllUsersRoute = typeof GetAllUsers; 72 | -------------------------------------------------------------------------------- /src/lib/utils/openapi/helpers.ts: -------------------------------------------------------------------------------- 1 | import { 2 | OpenApiGeneratorV3, 3 | OpenAPIRegistry, 4 | } from "@asteasolutions/zod-to-openapi"; 5 | import { z } from "@hono/zod-openapi"; 6 | 7 | type ZodSchema = 8 | | z.ZodUnion<[z.AnyZodObject, ...z.AnyZodObject[]]> 9 | | z.AnyZodObject 10 | | z.ZodArray; 11 | 12 | function oneOf(schemas: T[]) { 13 | const registry = new OpenAPIRegistry(); 14 | 15 | schemas.forEach((schema, index) => { 16 | registry.register(index.toString(), schema); 17 | }); 18 | 19 | const generator = new OpenApiGeneratorV3(registry.definitions); 20 | const components = generator.generateComponents(); 21 | 22 | return components.components?.schemas 23 | ? Object.values(components.components!.schemas!) 24 | : []; 25 | } 26 | 27 | export function jsonContent( 28 | schema: T, 29 | description: string, 30 | ) { 31 | return { 32 | content: { 33 | "application/json": { 34 | schema, 35 | }, 36 | }, 37 | description, 38 | }; 39 | } 40 | 41 | export function jsonContentRequired( 42 | schema: T, 43 | description: string, 44 | ) { 45 | return { 46 | ...jsonContent(schema, description), 47 | required: true, 48 | }; 49 | } 50 | 51 | export function jsonContentOneOf( 52 | schemas: T[], 53 | description: string, 54 | ) { 55 | return { 56 | content: { 57 | "application/json": { 58 | schema: { 59 | oneOf: oneOf(schemas), 60 | }, 61 | }, 62 | }, 63 | description, 64 | }; 65 | } 66 | 67 | export function createValidationErrorSchema(schema: T) { 68 | const { error } = schema.safeParse( 69 | schema._def.typeName === z.ZodFirstPartyTypeKind.ZodArray ? [] : {}, 70 | ); 71 | 72 | return z.object({ 73 | success: z.boolean().openapi({ example: false }), 74 | error: z 75 | .object({ 76 | issues: z.array( 77 | z.object({ 78 | code: z.string(), 79 | path: z.array(z.union([z.string(), z.number()])), 80 | message: z.string().optional(), 81 | }), 82 | ), 83 | name: z.string(), 84 | }) 85 | .openapi({ 86 | example: error, 87 | }), 88 | }); 89 | } 90 | 91 | export function createErrorSchema(example?: T) { 92 | return z.object({ 93 | success: z.boolean().openapi({ example: false }), 94 | error: z 95 | .object({ 96 | issues: z.array( 97 | z.object({ 98 | message: z.string(), 99 | }), 100 | ), 101 | }) 102 | .openapi({ 103 | example: { 104 | issues: [{ message: example ?? "" }], 105 | }, 106 | }), 107 | }); 108 | } 109 | 110 | export function createSuccessSchema(schema: T) { 111 | const example = schema?._def?.openapi?.metadata?.example; 112 | 113 | return z.object({ 114 | success: z.boolean().openapi({ example: true }), 115 | data: schema?.openapi({ 116 | example, 117 | }), 118 | }); 119 | } 120 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## NodeJS Typescript Starter 2 | 3 | ## Documentation 4 | 5 | - [Libraries](https://github.com/dhruvsaxena1998/node-typescript-starter#libraries) 6 | - [Features](https://github.com/dhruvsaxena1998/node-typescript-starter#features) 7 | - [Pre requisite](https://github.com/dhruvsaxena1998/node-typescript-starter#pre-reqs) 8 | - [Getting Started](https://github.com/dhruvsaxena1998/node-typescript-starter#getting-started) 9 | 10 | ## Libraries 11 | 12 | | Categories | Libraries | 13 | | ------------- | ------------------------------------------ | 14 | | Server | [`Hono.js`](https://hono.dev/) | 15 | | Database | [`Drizzle ORM`](https://orm.drizzle.team/) | 16 | | Validations | [`ZOD`](https://zod.dev/) | 17 | | Logging | [`Pino`](https://github.com/pinojs/pino) | 18 | | OPEN Api Spec | [`Scalar`](https://scalar.com/) | 19 | 20 | ## Features 21 | 22 | - Full Typesafety with [Typescript](https://www.typescriptlang.org/) 23 | - Opinionated Structure 24 | - Clear and organized directory structure. 25 | - Seperations of routes and handlers 26 | - Validations 27 | - Database Integration 28 | - OPENAPI Spec Client Integrated 29 | - Error Handling 30 | - File stream Logging 31 | - Testing 32 | - Developer Experience 33 | - Hot Reloading 34 | - Linting and Code Formatting 35 | 36 | All pre-configured or minimum configuration required\* 37 | 38 | ## Pre-reqs 39 | 40 | - Environment - Node.JS 41 | - Editor - VSCode (Recommended) 42 | - Database - MySQL (pre-configured) via Drizzle ORM (configure as per needs) 43 | 44 | ## Getting Started 45 | 46 | ### Clone the Template 47 | 48 | 1. Click the "Use this template" button: On the top-right of the repository's page, you'll see a "Use this template" button. Click it. 49 | 50 | 2. Fill in repository details: You'll be prompted to give your new repository a name and set it as public or private. After that, click "Create repository from template." 51 | 52 | 3. Clone the new repository: Once the repository is created, clone it locally 53 | 54 | ```bash 55 | git clone https://github.com/your-username/your-new-repo.git 56 | ``` 57 | 58 | 4. Install Dependencies 59 | 60 | ```bash 61 | # recommended (pnpm) 62 | # npm i -g pnpm 63 | 64 | pnpm install 65 | ``` 66 | 67 | ### Configure Environment 68 | 69 | Create .env file by replicating .env.example and fill as per needs. To properly run this project, you will need to setup following variables to your .env file. 70 | 71 | > Server 72 | 73 | | key | default value | available values | 74 | | ----------- | ------------- | ------------------------------------------- | 75 | | NODE_ENV | `dev` | `dev` `stage` `uat` `preprod` `prod` `test` | 76 | | SERVER_PORT | `3000` | `number` | 77 | 78 | > Logging 79 | 80 | | key | default value | available values | 81 | | --------- | ------------- | --------------------------------------------- | 82 | | LOG_LEVEL | `debug` | `fatal` `error` `warn` `info` `debug` `trace` | 83 | 84 | > Database 85 | 86 | | key | default value | 87 | | ------- | ------------- | 88 | | DB_HOST | `localhost` | 89 | | DB_PORT | `3306` | 90 | | DB_USER | | 91 | | DB_PASS | | 92 | | DB_NAME | | 93 | 94 | ### Starting Application 95 | 96 | ```bash 97 | pnpm dev 98 | ``` 99 | 100 | ### Building 101 | 102 | ```bash 103 | pnpm build 104 | ``` 105 | 106 | ### Other Commands 107 | 108 | ```bash 109 | pnpm 110 | ``` 111 | 112 | | command | description | 113 | | ---------- | ---------------------------------------- | 114 | | dev | start hot-reload server | 115 | | build | build javascript source | 116 | | start | start application from javascript source | 117 | | lint | linting via eslint | 118 | | lint:fix | auto-fix linting issues | 119 | | fmt | auto-format via prettier | 120 | | test | test application | 121 | | type-check | typecheck application without building | 122 | 123 | ## Authors 124 | 125 | - [@dhruvsaxena1998](https://github.com/dhruvsaxena1998) 126 | -------------------------------------------------------------------------------- /src/lib/constants/http-status-codes.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-magic-numbers */ 2 | 3 | /** 4 | * @fileoverview Generated file. Do not edit 5 | * @generated 6 | */ 7 | 8 | // Codes retrieved on Thu, 03 Oct 2024 12:05:14 GMT from https://raw.githubusercontent.com/prettymuchbryce/http-status-codes/refs/heads/master/codes.json 9 | /** 10 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.3 11 | * 12 | * The request has been received but not yet acted upon. It is non-committal, meaning that there is no way in HTTP to later send an asynchronous response indicating the outcome of processing the request. It is intended for cases where another process or server handles the request, or for batch processing. 13 | */ 14 | export const ACCEPTED = 202 as const; 15 | /** 16 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.3 17 | * 18 | * This error response means that the server, while working as a gateway to get a response needed to handle the request, got an invalid response. 19 | */ 20 | export const BAD_GATEWAY = 502 as const; 21 | /** 22 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.1 23 | * 24 | * This response means that server could not understand the request due to invalid syntax. 25 | */ 26 | export const BAD_REQUEST = 400 as const; 27 | /** 28 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.8 29 | * 30 | * This response is sent when a request conflicts with the current state of the server. 31 | */ 32 | export const CONFLICT = 409 as const; 33 | /** 34 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.1 35 | * 36 | * This interim response indicates that everything so far is OK and that the client should continue with the request or ignore it if it is already finished. 37 | */ 38 | export const CONTINUE = 100 as const; 39 | /** 40 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.2 41 | * 42 | * The request has succeeded and a new resource has been created as a result of it. This is typically the response sent after a PUT request. 43 | */ 44 | export const CREATED = 201 as const; 45 | /** 46 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.14 47 | * 48 | * This response code means the expectation indicated by the Expect request header field can't be met by the server. 49 | */ 50 | export const EXPECTATION_FAILED = 417 as const; 51 | /** 52 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.5 53 | * 54 | * The request failed due to failure of a previous request. 55 | */ 56 | export const FAILED_DEPENDENCY = 424 as const; 57 | /** 58 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.3 59 | * 60 | * The client does not have access rights to the content, i.e. they are unauthorized, so server is rejecting to give proper response. Unlike 401, the client's identity is known to the server. 61 | */ 62 | export const FORBIDDEN = 403 as const; 63 | /** 64 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.5 65 | * 66 | * This error response is given when the server is acting as a gateway and cannot get a response in time. 67 | */ 68 | export const GATEWAY_TIMEOUT = 504 as const; 69 | /** 70 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.9 71 | * 72 | * This response would be sent when the requested content has been permenantly deleted from server, with no forwarding address. Clients are expected to remove their caches and links to the resource. The HTTP specification intends this status code to be used for "limited-time, promotional services". APIs should not feel compelled to indicate resources that have been deleted with this status code. 73 | */ 74 | export const GONE = 410 as const; 75 | /** 76 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.6 77 | * 78 | * The HTTP version used in the request is not supported by the server. 79 | */ 80 | export const HTTP_VERSION_NOT_SUPPORTED = 505 as const; 81 | /** 82 | * Official Documentation @ https://tools.ietf.org/html/rfc2324#section-2.3.2 83 | * 84 | * Any attempt to brew coffee with a teapot should result in the error code "418 I'm a teapot". The resulting entity body MAY be short and stout. 85 | */ 86 | export const IM_A_TEAPOT = 418 as const; 87 | /** 88 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6 89 | * 90 | * The 507 (Insufficient Storage) status code means the method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request. This condition is considered to be temporary. If the request which received this status code was the result of a user action, the request MUST NOT be repeated until it is requested by a separate user action. 91 | */ 92 | export const INSUFFICIENT_SPACE_ON_RESOURCE = 419 as const; 93 | /** 94 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6 95 | * 96 | * The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process. 97 | */ 98 | export const INSUFFICIENT_STORAGE = 507 as const; 99 | /** 100 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.1 101 | * 102 | * The server encountered an unexpected condition that prevented it from fulfilling the request. 103 | */ 104 | export const INTERNAL_SERVER_ERROR = 500 as const; 105 | /** 106 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.10 107 | * 108 | * The server rejected the request because the Content-Length header field is not defined and the server requires it. 109 | */ 110 | export const LENGTH_REQUIRED = 411 as const; 111 | /** 112 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.4 113 | * 114 | * The resource that is being accessed is locked. 115 | */ 116 | export const LOCKED = 423 as const; 117 | /** 118 | * @deprecated 119 | * Official Documentation @ https://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt 120 | * 121 | * A deprecated response used by the Spring Framework when a method has failed. 122 | */ 123 | export const METHOD_FAILURE = 420 as const; 124 | /** 125 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.5 126 | * 127 | * The request method is known by the server but has been disabled and cannot be used. For example, an API may forbid DELETE-ing a resource. The two mandatory methods, GET and HEAD, must never be disabled and should not return this error code. 128 | */ 129 | export const METHOD_NOT_ALLOWED = 405 as const; 130 | /** 131 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.2 132 | * 133 | * This response code means that URI of requested resource has been changed. Probably, new URI would be given in the response. 134 | */ 135 | export const MOVED_PERMANENTLY = 301 as const; 136 | /** 137 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.3 138 | * 139 | * This response code means that URI of requested resource has been changed temporarily. New changes in the URI might be made in the future. Therefore, this same URI should be used by the client in future requests. 140 | */ 141 | export const MOVED_TEMPORARILY = 302 as const; 142 | /** 143 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.2 144 | * 145 | * A Multi-Status response conveys information about multiple resources in situations where multiple status codes might be appropriate. 146 | */ 147 | export const MULTI_STATUS = 207 as const; 148 | /** 149 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.1 150 | * 151 | * The request has more than one possible responses. User-agent or user should choose one of them. There is no standardized way to choose one of the responses. 152 | */ 153 | export const MULTIPLE_CHOICES = 300 as const; 154 | /** 155 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-6 156 | * 157 | * The 511 status code indicates that the client needs to authenticate to gain network access. 158 | */ 159 | export const NETWORK_AUTHENTICATION_REQUIRED = 511 as const; 160 | /** 161 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.5 162 | * 163 | * There is no content to send for this request, but the headers may be useful. The user-agent may update its cached headers for this resource with the new ones. 164 | */ 165 | export const NO_CONTENT = 204 as const; 166 | /** 167 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.4 168 | * 169 | * This response code means returned meta-information set is not exact set as available from the origin server, but collected from a local or a third party copy. Except this condition, 200 OK response should be preferred instead of this response. 170 | */ 171 | export const NON_AUTHORITATIVE_INFORMATION = 203 as const; 172 | /** 173 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.6 174 | * 175 | * This response is sent when the web server, after performing server-driven content negotiation, doesn't find any content following the criteria given by the user agent. 176 | */ 177 | export const NOT_ACCEPTABLE = 406 as const; 178 | /** 179 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.4 180 | * 181 | * The server can not find requested resource. In the browser, this means the URL is not recognized. In an API, this can also mean that the endpoint is valid but the resource itself does not exist. Servers may also send this response instead of 403 to hide the existence of a resource from an unauthorized client. This response code is probably the most famous one due to its frequent occurence on the web. 182 | */ 183 | export const NOT_FOUND = 404 as const; 184 | /** 185 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.2 186 | * 187 | * The request method is not supported by the server and cannot be handled. The only methods that servers are required to support (and therefore that must not return this code) are GET and HEAD. 188 | */ 189 | export const NOT_IMPLEMENTED = 501 as const; 190 | /** 191 | * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.1 192 | * 193 | * This is used for caching purposes. It is telling to client that response has not been modified. So, client can continue to use same cached version of response. 194 | */ 195 | export const NOT_MODIFIED = 304 as const; 196 | /** 197 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.1 198 | * 199 | * The request has succeeded. The meaning of a success varies depending on the HTTP method: 200 | * GET: The resource has been fetched and is transmitted in the message body. 201 | * HEAD: The entity headers are in the message body. 202 | * POST: The resource describing the result of the action is transmitted in the message body. 203 | * TRACE: The message body contains the request message as received by the server 204 | */ 205 | export const OK = 200 as const; 206 | /** 207 | * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.1 208 | * 209 | * This response code is used because of range header sent by the client to separate download into multiple streams. 210 | */ 211 | export const PARTIAL_CONTENT = 206 as const; 212 | /** 213 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.2 214 | * 215 | * This response code is reserved for future use. Initial aim for creating this code was using it for digital payment systems however this is not used currently. 216 | */ 217 | export const PAYMENT_REQUIRED = 402 as const; 218 | /** 219 | * Official Documentation @ https://tools.ietf.org/html/rfc7538#section-3 220 | * 221 | * This means that the resource is now permanently located at another URI, specified by the Location: HTTP Response header. This has the same semantics as the 301 Moved Permanently HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request. 222 | */ 223 | export const PERMANENT_REDIRECT = 308 as const; 224 | /** 225 | * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.2 226 | * 227 | * The client has indicated preconditions in its headers which the server does not meet. 228 | */ 229 | export const PRECONDITION_FAILED = 412 as const; 230 | /** 231 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-3 232 | * 233 | * The origin server requires the request to be conditional. Intended to prevent the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict. 234 | */ 235 | export const PRECONDITION_REQUIRED = 428 as const; 236 | /** 237 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.1 238 | * 239 | * This code indicates that the server has received and is processing the request, but no response is available yet. 240 | */ 241 | export const PROCESSING = 102 as const; 242 | /** 243 | * Official Documentation @ https://www.rfc-editor.org/rfc/rfc8297#page-3 244 | * 245 | * This code indicates to the client that the server is likely to send a final response with the header fields included in the informational response. 246 | */ 247 | export const EARLY_HINTS = 103 as const; 248 | /** 249 | * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7231#section-6.5.15 250 | * 251 | * The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol. 252 | */ 253 | export const UPGRADE_REQUIRED = 426 as const; 254 | /** 255 | * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.2 256 | * 257 | * This is similar to 401 but authentication is needed to be done by a proxy. 258 | */ 259 | export const PROXY_AUTHENTICATION_REQUIRED = 407 as const; 260 | /** 261 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-5 262 | * 263 | * The server is unwilling to process the request because its header fields are too large. The request MAY be resubmitted after reducing the size of the request header fields. 264 | */ 265 | export const REQUEST_HEADER_FIELDS_TOO_LARGE = 431 as const; 266 | /** 267 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.7 268 | * 269 | * This response is sent on an idle connection by some servers, even without any previous request by the client. It means that the server would like to shut down this unused connection. This response is used much more since some browsers, like Chrome, Firefox 27+, or IE9, use HTTP pre-connection mechanisms to speed up surfing. Also note that some servers merely shut down the connection without sending this message. 270 | */ 271 | export const REQUEST_TIMEOUT = 408 as const; 272 | /** 273 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.11 274 | * 275 | * Request entity is larger than limits defined by server; the server might close the connection or return an Retry-After header field. 276 | */ 277 | export const REQUEST_TOO_LONG = 413 as const; 278 | /** 279 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.12 280 | * 281 | * The URI requested by the client is longer than the server is willing to interpret. 282 | */ 283 | export const REQUEST_URI_TOO_LONG = 414 as const; 284 | /** 285 | * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.4 286 | * 287 | * The range specified by the Range header field in the request can't be fulfilled; it's possible that the range is outside the size of the target URI's data. 288 | */ 289 | export const REQUESTED_RANGE_NOT_SATISFIABLE = 416 as const; 290 | /** 291 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.6 292 | * 293 | * This response code is sent after accomplishing request to tell user agent reset document view which sent this request. 294 | */ 295 | export const RESET_CONTENT = 205 as const; 296 | /** 297 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.4 298 | * 299 | * Server sent this response to directing client to get requested resource to another URI with an GET request. 300 | */ 301 | export const SEE_OTHER = 303 as const; 302 | /** 303 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.4 304 | * 305 | * The server is not ready to handle the request. Common causes are a server that is down for maintenance or that is overloaded. Note that together with this response, a user-friendly page explaining the problem should be sent. This responses should be used for temporary conditions and the Retry-After: HTTP header should, if possible, contain the estimated time before the recovery of the service. The webmaster must also take care about the caching-related headers that are sent along with this response, as these temporary condition responses should usually not be cached. 306 | */ 307 | export const SERVICE_UNAVAILABLE = 503 as const; 308 | /** 309 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.2 310 | * 311 | * This code is sent in response to an Upgrade request header by the client, and indicates the protocol the server is switching too. 312 | */ 313 | export const SWITCHING_PROTOCOLS = 101 as const; 314 | /** 315 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.7 316 | * 317 | * Server sent this response to directing client to get requested resource to another URI with same method that used prior request. This has the same semantic than the 302 Found HTTP response code, with the exception that the user agent must not change the HTTP method used: if a POST was used in the first request, a POST must be used in the second request. 318 | */ 319 | export const TEMPORARY_REDIRECT = 307 as const; 320 | /** 321 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-4 322 | * 323 | * The user has sent too many requests in a given amount of time ("rate limiting"). 324 | */ 325 | export const TOO_MANY_REQUESTS = 429 as const; 326 | /** 327 | * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.1 328 | * 329 | * Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response. 330 | */ 331 | export const UNAUTHORIZED = 401 as const; 332 | /** 333 | * Official Documentation @ https://tools.ietf.org/html/rfc7725 334 | * 335 | * The user-agent requested a resource that cannot legally be provided, such as a web page censored by a government. 336 | */ 337 | export const UNAVAILABLE_FOR_LEGAL_REASONS = 451 as const; 338 | /** 339 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.3 340 | * 341 | * The request was well-formed but was unable to be followed due to semantic errors. 342 | */ 343 | export const UNPROCESSABLE_ENTITY = 422 as const; 344 | /** 345 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.13 346 | * 347 | * The media format of the requested data is not supported by the server, so the server is rejecting the request. 348 | */ 349 | export const UNSUPPORTED_MEDIA_TYPE = 415 as const; 350 | /** 351 | * @deprecated 352 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.6 353 | * 354 | * Was defined in a previous version of the HTTP specification to indicate that a requested response must be accessed by a proxy. It has been deprecated due to security concerns regarding in-band configuration of a proxy. 355 | */ 356 | export const USE_PROXY = 305 as const; 357 | /** 358 | * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7540#section-9.1.2 359 | * 360 | * Defined in the specification of HTTP/2 to indicate that a server is not able to produce a response for the combination of scheme and authority that are included in the request URI. 361 | */ 362 | export const MISDIRECTED_REQUEST = 421 as const; 363 | --------------------------------------------------------------------------------