Boilerplate / starter template kutubxonasi
Senior dasturchi har safar noldan boshlamaydi — tayyor poydevorlar to'plamiga ega. Bu — tez-tez kerak bo'ladigan starter kod va konfiguratsiyalar. Nusxalab, moslab ishlat.
Bu — skeletlar (to'liq ilova emas). G'oyani ko'rsatadi; o'z loyihangga moslab to'ldir.
1. Express + TypeScript server skeleti
ts
// src/server.ts
import express from "express";
import cors from "cors";
import helmet from "helmet";
const app = express();
app.use(helmet()); // xavfsizlik sarlavhalari (14.7)
app.use(cors()); // CORS
app.use(express.json()); // JSON body parse
// Health check
app.get("/health", (_, res) => res.json({ status: "ok" }));
// Routerlar
// app.use("/api/users", usersRouter);
// 404
app.use((_, res) => res.status(404).json({ error: "Not found" }));
// Markaziy xato boshqaruvi
app.use((err, _req, res, _next) => {
console.error(err);
res.status(err.status || 500).json({ error: err.message || "Server error" });
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`Server: http://localhost:${PORT}`));2. REST router skeleti (CRUD)
ts
// src/routes/users.ts
import { Router } from "express";
const router = Router();
router.get("/", async (req, res, next) => {
try { /* ro'yxat */ res.json({ data: [] }); }
catch (e) { next(e); }
});
router.get("/:id", async (req, res, next) => { /* bitta */ });
router.post("/", async (req, res, next) => { /* yaratish 201 */ });
router.put("/:id", async (req, res, next) => { /* yangilash */ });
router.delete("/:id", async (req, res, next) => { /* o'chirish 204 */ });
export default router;3. .env va konfiguratsiya
bash
# .env (HECH QACHON git'ga qo'yma — .gitignore'ga)
NODE_ENV=development
PORT=3000
DATABASE_URL=postgresql://user:pass@localhost:5432/mydb
JWT_SECRET=change-me-in-production
REDIS_URL=redis://localhost:6379bash
# .env.example (git'ga qo'yiladi — namuna)
NODE_ENV=
PORT=
DATABASE_URL=
JWT_SECRET=ts
// src/config.ts — markazlashgan, validatsiyalangan config
export const config = {
port: Number(process.env.PORT) || 3000,
dbUrl: process.env.DATABASE_URL!,
jwtSecret: process.env.JWT_SECRET!,
};
if (!config.dbUrl) throw new Error("DATABASE_URL kerak");4. .gitignore
text
node_modules/
.env
.env.local
dist/
build/
*.log
.DS_Store
coverage/
.next/5. JWT auth middleware
ts
// src/middleware/auth.ts
import jwt from "jsonwebtoken";
import { config } from "../config";
export function auth(req, res, next) {
const header = req.headers.authorization; // "Bearer <token>"
const token = header?.split(" ")[1];
if (!token) return res.status(401).json({ error: "Token kerak" });
try {
req.user = jwt.verify(token, config.jwtSecret); // payloadni req'ga
next();
} catch {
res.status(401).json({ error: "Yaroqsiz token" });
}
}
// Ishlatish: router.get("/me", auth, handler)6. Dockerfile (Node, multi-stage)
dockerfile
# 1-bosqich: build
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build
# 2-bosqich: ishga tushirish (kichik image)
FROM node:20-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY --from=builder /app/dist ./dist
EXPOSE 3000
CMD ["node", "dist/server.js"]7. docker-compose (app + DB + Redis)
yaml
services:
app:
build: .
ports: ["3000:3000"]
env_file: .env
depends_on: [db, redis]
db:
image: postgres:16-alpine
environment:
POSTGRES_PASSWORD: pass
POSTGRES_DB: mydb
ports: ["5432:5432"]
volumes: [pgdata:/var/lib/postgresql/data]
redis:
image: redis:7-alpine
ports: ["6379:6379"]
volumes:
pgdata:8. GitHub Actions CI
yaml
# .github/workflows/ci.yml
name: CI
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 20, cache: npm }
- run: npm ci
- run: npm run lint
- run: npm test
- run: npm run build9. ESLint + Prettier + Husky (15.3)
jsonc
// package.json (qism)
{
"scripts": {
"lint": "eslint .",
"format": "prettier --write .",
"prepare": "husky"
}
}bash
# .husky/pre-commit
npx lint-stagedjsonc
// lint-staged (package.json)
"lint-staged": { "*.{ts,js}": ["eslint --fix", "prettier --write"] }10. Prisma sxema skeleti
prisma
// prisma/schema.prisma
generator client { provider = "prisma-client-js" }
datasource db { provider = "postgresql"; url = env("DATABASE_URL") }
model User {
id Int @id @default(autoincrement())
email String @unique
name String
posts Post[]
createdAt DateTime @default(now())
}
model Post {
id Int @id @default(autoincrement())
title String
authorId Int
author User @relation(fields: [authorId], references: [id])
createdAt DateTime @default(now())
}11. Next.js boshlang'ich struktura
text
app/
layout.tsx # ildiz layout
page.tsx # bosh sahifa
(auth)/login/page.tsx
dashboard/page.tsx
api/users/route.ts # Route Handler
lib/
db.ts # Prisma client (singleton)
auth.ts # auth config
components/
ui/ # qayta ishlatiladigan komponentlarts
// lib/db.ts — Prisma singleton (dev'da ko'p ulanishni oldini oladi)
import { PrismaClient } from "@prisma/client";
const g = globalThis as any;
export const db = g.prisma || new PrismaClient();
if (process.env.NODE_ENV !== "production") g.prisma = db;12. README shabloni (har loyiha uchun)
markdown
# Loyiha nomi
Qisqa tavsif. [Jonli demo](havola)
## Texnologiyalar
Next.js, NestJS, PostgreSQL, ...
## Ishga tushirish
\`\`\`bash
npm install
cp .env.example .env # to'ldir
npm run dev
\`\`\`
## Xususiyatlar
- ...
## Skrinshot
Bu skeletlarni o'z
templates/papkangda saqla — har yangi loyihada qayta yozma. Bu — senior odat (15.1: qayta ishlatish).
Bog'liq: 10-QISM DevOps, 15.3 · Bosh sahifa: README.
Izohlar (0)
Izoh yozish uchun kiring.
- Hozircha izoh yo'q. Birinchi bo'ling!