- C.R.U.D, Filter, Paginate, Sort and Search API
I - Setup
-
npm i express.
- A web framework for node -
npm i mongoose
- A Object Document Mapper - ODM for MongoDB -
npm i cors
- CORS is a node.js package for providing a Connect/Express middleware -
npm i dotenv
- Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env -
npm i morgan
- HTTP request logger middleware for node.js -
npm i -D typescript
- TypeScript is JavaScript with syntax for types -
npm i -D ts-node-dev
- It restarts target node process when any of required files changes -
Create a "tsconfig.json" file and copy:
{
"compilerOptions": {
"module": "commonjs",
"esModuleInterop": true,
"target": "es6",
"moduleResolution": "node",
"sourceMap": true,
"outDir": "dist",
"rootDir": "src"
},
"lib": ["es2015"]
}
- Updating the package.json File
II - How to use?
- Routes
> GET /api/products
> GET /api/products/:id
> POST /api/products
> PUT /api/products/:id
> DELETE /api/products/:id
- Filter
gt = greater than, gte = greater than or equal.
lt = lesser than, lte = lesser than or equal.
> GET /api/products?price=15
> GET /api/products?price[gt]=15.99
> GET /api/products?price[gte]=15.99
> GET /api/products?price[lt]=15.99
> GET /api/products?price[lte]=15.99
> GET /api/products?title[regex]=men&price[lte]=15.99
- Paginate
Default page=1 and limit=5
> GET /api/products?page=2
> GET /api/products?page=2&limit=7
- Sort
Default sort='-createdAt'
> GET /api/products?sort=price
> GET /api/products?sort=createdAt
- Full-text search
> GET /api/products?search=men