ExpressJS
Express.js, commonly known as Express, is a fast and minimalist web application framework for Node.js. It provides a simple and flexible set of features for building web applications and APIs. Express.js is designed to be unopinionated, allowing developers to structure and organize their applications according to their specific needs.
Structure
Directoryprisma/
- …
Directorysrc
Directorymodel
Directorycontroller
Directoryrouter
- main.router.ts
Directorydb/
- …
Directorymiddleware
- main.middleware.ts
Directorytest
- test.ts
- .env
Directorysrc
Directorymodel
Directorycontroller
Directoryrouter
- main.router.ts
Directorydb/
- …
Directorymiddleware
- main.middleware.ts
Directorytest
- test.ts
- .env
router
in router file you can get function from controller file and use it to make clean router
import {IRouter , Router} from 'express';const Main_router : IRouter = Router();import { create , get} from '../Controller/main.controller';
Main_router.get("/", get)Main_router.post('/example',create)
export default Main_router ;
controller
//This file to make Controller process you can do anything and export it in function to use in routerimport Model from "../model/main.model";import {Request ,Response} from "express";
export async function get(req:Request,res:Response){ res.send('welcome to expressTS')}
export async function create(req:Request,res:Response){ const {name , age} = req.body; const result = await Model.create({ name:name, age:age }) res.send(result)};
model
//make schema model in mongoose exampleimport mongoose from "mongoose";import { user } from "../types/type";
const model = new mongoose.Schema( { name:{ type: String, required: true }, age:{ type: Number, required: true } }, { collection: 'model', })
const Model: mongoose.Model<user> = mongoose.model("model", model)export default Model
// in schema for pgsql you can set it in prisma.schema filemodel User { id Int @id @default(autoincrement()) email String @unique name String?}
middleware
in middleware floder you can set header use logger check token and many things in this floder and import to use it in index.js
file
db
if you use PostgreSQL you will see prisma floder and you can use it to set database
.env
you can change your port and setup your database in .env file
PORT = 8080DATABASE_URI = '< DATABASE_URL >'DATABASE_NAME = '< DB_NAME >'
PORT= 7777DATABASE_URL="< DATABASE_URL >"
test
test using supertest and vitest together learn more about vitest and supertest
import request from 'supertest'import { describe, expect, test } from 'vitest'import app from '../src/index';
describe("Test the root path",async () => { const response = await request(app).get("/");
test("It should response the GET method", () => { expect(response.text).toBe("welcome to expressTS"); }); test("status should be 200" , async ()=>{ expect(response.status).toBe(200); })});
logger
🔐Security
security is the topic we concerned about so that we use sample protection there
DDOS protection
this cannot protect all of DDos attack please learn more about security
const limiter = rateLimit({ windowMs: 15 * 60 * 1000, // 15 minutes limit: 100, // Limit each IP to 100 requests per `window` (here, per 15 minutes). standardHeaders: 'draft-7', // draft-6: `RateLimit-*` headers; draft-7: combined `RateLimit` header legacyHeaders: false, // Disable the `X-RateLimit-*` headers. // store: ... , // Use an external store for consistency across multiple server instances.})
SQL injection protection
- prisma can help you from SQL injection cuz it dont want to write real SQL script from your code learn more about ORM
cors protection
// in this part from middle ware you can replace your website in * to protect your site from another userapp.use(cors({ "origin":'*', "methods": ['GET','POST','PUT','DELETE']}));
LICENCE BY DOSE FROM ANOTHER PLANET