├── .env ├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── README.md ├── client ├── .gitignore ├── README.md ├── package-lock.json ├── package.json ├── public │ ├── favicon.ico │ ├── index.html │ ├── logo192.png │ ├── logo512.png │ ├── manifest.json │ └── robots.txt └── src │ ├── App.js │ ├── components │ ├── DrawerExample.js │ ├── InputsGroup.js │ └── Row.js │ ├── context │ └── GlobalWrapper.js │ ├── index.css │ └── index.js ├── nest-cli.json ├── package-lock.json ├── package.json ├── src ├── app.module.ts ├── dto │ └── users.dto.ts ├── main.ts ├── models │ └── users.models.ts ├── users │ ├── users.controller.ts │ ├── users.module.ts │ └── users.service.ts └── util │ └── filter.validation.ts ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json └── tsconfig.json /.env: -------------------------------------------------------------------------------- 1 | PORT=5000 2 | MONGO_URI= 3 | -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | project: 'tsconfig.json', 5 | tsconfigRootDir : __dirname, 6 | sourceType: 'module', 7 | }, 8 | plugins: ['@typescript-eslint/eslint-plugin'], 9 | extends: [ 10 | 'plugin:@typescript-eslint/recommended', 11 | 'plugin:prettier/recommended', 12 | ], 13 | root: true, 14 | env: { 15 | node: true, 16 | jest: true, 17 | }, 18 | ignorePatterns: ['.eslintrc.js'], 19 | rules: { 20 | '@typescript-eslint/interface-name-prefix': 'off', 21 | '@typescript-eslint/explicit-function-return-type': 'off', 22 | '@typescript-eslint/explicit-module-boundary-types': 'off', 23 | '@typescript-eslint/no-explicit-any': 'off', 24 | }, 25 | }; 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /dist 3 | /node_modules 4 | 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | pnpm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # OS 15 | .DS_Store 16 | 17 | # Tests 18 | /coverage 19 | /.nyc_output 20 | 21 | # IDEs and editors 22 | /.idea 23 | .project 24 | .classpath 25 | .c9/ 26 | *.launch 27 | .settings/ 28 | *.sublime-workspace 29 | 30 | # IDE - VSCode 31 | .vscode/* 32 | !.vscode/settings.json 33 | !.vscode/tasks.json 34 | !.vscode/launch.json 35 | !.vscode/extensions.json -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # complete-crud-nest-react 2 | 3 | # 1- Backend (5000 port) 4 | 5 | You can change the MONGO_URI into .env with your URI 6 | 7 | run npm install and npm run start:dev 8 | 9 | # 2- Frontend (3000 port) 10 | 11 | run npm install and npm start 12 | 13 | # 3- together 14 | 15 | run npm run start:together 16 | -------------------------------------------------------------------------------- /client/.gitignore: -------------------------------------------------------------------------------- 1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files. 2 | 3 | # dependencies 4 | /node_modules 5 | /.pnp 6 | .pnp.js 7 | 8 | # testing 9 | /coverage 10 | 11 | # production 12 | /build 13 | 14 | # misc 15 | .DS_Store 16 | .env.local 17 | .env.development.local 18 | .env.test.local 19 | .env.production.local 20 | 21 | npm-debug.log* 22 | yarn-debug.log* 23 | yarn-error.log* 24 | -------------------------------------------------------------------------------- /client/README.md: -------------------------------------------------------------------------------- 1 | # Getting Started with Create React App 2 | 3 | This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app). 4 | 5 | ## Available Scripts 6 | 7 | In the project directory, you can run: 8 | 9 | ### `npm start` 10 | 11 | Runs the app in the development mode.\ 12 | Open [http://localhost:3000](http://localhost:3000) to view it in your browser. 13 | 14 | The page will reload when you make changes.\ 15 | You may also see any lint errors in the console. 16 | 17 | ### `npm test` 18 | 19 | Launches the test runner in the interactive watch mode.\ 20 | See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information. 21 | 22 | ### `npm run build` 23 | 24 | Builds the app for production to the `build` folder.\ 25 | It correctly bundles React in production mode and optimizes the build for the best performance. 26 | 27 | The build is minified and the filenames include the hashes.\ 28 | Your app is ready to be deployed! 29 | 30 | See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information. 31 | 32 | ### `npm run eject` 33 | 34 | **Note: this is a one-way operation. Once you `eject`, you can't go back!** 35 | 36 | If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project. 37 | 38 | Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own. 39 | 40 | You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it. 41 | 42 | ## Learn More 43 | 44 | You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started). 45 | 46 | To learn React, check out the [React documentation](https://reactjs.org/). 47 | 48 | ### Code Splitting 49 | 50 | This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting) 51 | 52 | ### Analyzing the Bundle Size 53 | 54 | This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size) 55 | 56 | ### Making a Progressive Web App 57 | 58 | This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app) 59 | 60 | ### Advanced Configuration 61 | 62 | This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration) 63 | 64 | ### Deployment 65 | 66 | This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment) 67 | 68 | ### `npm run build` fails to minify 69 | 70 | This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify) 71 | -------------------------------------------------------------------------------- /client/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "client", 3 | "version": "0.1.0", 4 | "private": true, 5 | "proxy": "http://localhost:5000/", 6 | "dependencies": { 7 | "@chakra-ui/react": "^2.3.2", 8 | "@emotion/react": "^11.10.4", 9 | "@emotion/styled": "^11.10.4", 10 | "@testing-library/jest-dom": "^5.16.5", 11 | "@testing-library/react": "^13.4.0", 12 | "@testing-library/user-event": "^13.5.0", 13 | "axios": "^0.27.2", 14 | "framer-motion": "^7.3.2", 15 | "react": "^18.2.0", 16 | "react-dom": "^18.2.0", 17 | "react-icons": "^4.4.0", 18 | "react-scripts": "5.0.1", 19 | "web-vitals": "^2.1.4" 20 | }, 21 | "scripts": { 22 | "start": "react-scripts start", 23 | "build": "react-scripts build", 24 | "test": "react-scripts test", 25 | "eject": "react-scripts eject" 26 | }, 27 | "eslintConfig": { 28 | "extends": [ 29 | "react-app", 30 | "react-app/jest" 31 | ] 32 | }, 33 | "browserslist": { 34 | "production": [ 35 | ">0.2%", 36 | "not dead", 37 | "not op_mini all" 38 | ], 39 | "development": [ 40 | "last 1 chrome version", 41 | "last 1 firefox version", 42 | "last 1 safari version" 43 | ] 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /client/public/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/youssef-of-web/complete-crud-nest-react/371ffe2fbac87c15e01085a99cdb5b63ba6efb7d/client/public/favicon.ico -------------------------------------------------------------------------------- /client/public/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 12 | 13 | 17 | 18 | 27 | React App 28 | 29 | 30 | 31 |
32 | 42 | 43 | 44 | -------------------------------------------------------------------------------- /client/public/logo192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/youssef-of-web/complete-crud-nest-react/371ffe2fbac87c15e01085a99cdb5b63ba6efb7d/client/public/logo192.png -------------------------------------------------------------------------------- /client/public/logo512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/youssef-of-web/complete-crud-nest-react/371ffe2fbac87c15e01085a99cdb5b63ba6efb7d/client/public/logo512.png -------------------------------------------------------------------------------- /client/public/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "short_name": "React App", 3 | "name": "Create React App Sample", 4 | "icons": [ 5 | { 6 | "src": "favicon.ico", 7 | "sizes": "64x64 32x32 24x24 16x16", 8 | "type": "image/x-icon" 9 | }, 10 | { 11 | "src": "logo192.png", 12 | "type": "image/png", 13 | "sizes": "192x192" 14 | }, 15 | { 16 | "src": "logo512.png", 17 | "type": "image/png", 18 | "sizes": "512x512" 19 | } 20 | ], 21 | "start_url": ".", 22 | "display": "standalone", 23 | "theme_color": "#000000", 24 | "background_color": "#ffffff" 25 | } 26 | -------------------------------------------------------------------------------- /client/public/robots.txt: -------------------------------------------------------------------------------- 1 | # https://www.robotstxt.org/robotstxt.html 2 | User-agent: * 3 | Disallow: 4 | -------------------------------------------------------------------------------- /client/src/App.js: -------------------------------------------------------------------------------- 1 | import { 2 | Box, 3 | Button, 4 | Container, 5 | Input, 6 | Table, 7 | TableContainer, 8 | Tbody, 9 | Td, 10 | Text, 11 | Th, 12 | Thead, 13 | Tr, 14 | } from '@chakra-ui/react'; 15 | import { FormControl } from '@chakra-ui/react'; 16 | import { useContext, useEffect, useState } from 'react'; 17 | import { GlobalContext } from './context/GlobalWrapper'; 18 | import { AiOutlinePlus, AiOutlineSearch } from 'react-icons/ai'; 19 | import Row from './components/Row'; 20 | import DrawerExample from './components/DrawerExample'; 21 | 22 | function App() { 23 | const { FetchUsers, Search, users, onOpen, isOpen, onClose } = 24 | useContext(GlobalContext); 25 | const [query, setQuery] = useState(''); 26 | useEffect(() => { 27 | FetchUsers(); 28 | }, []); 29 | const SearchHandler = () => { 30 | Search(query); 31 | }; 32 | const onchangeHandler = (e) => { 33 | setQuery(e.target.value); 34 | }; 35 | return ( 36 |
37 | 38 | 39 | 40 | 41 | 42 | 43 | 53 | 54 | 55 | 56 | 57 | 58 | List Users 59 | 60 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | {users?.map(({ _id, fullname, email, age, country }) => { 85 | return ( 86 | 93 | ); 94 | })} 95 | 96 |
AvatarFullnameEmailAgeCountryActions
97 |
98 |
99 | 100 |
101 |
102 | ); 103 | } 104 | 105 | export default App; 106 | -------------------------------------------------------------------------------- /client/src/components/DrawerExample.js: -------------------------------------------------------------------------------- 1 | import { 2 | Button, 3 | Drawer, 4 | DrawerBody, 5 | DrawerCloseButton, 6 | DrawerContent, 7 | DrawerFooter, 8 | DrawerHeader, 9 | DrawerOverlay, 10 | Input, 11 | Stack, 12 | } from '@chakra-ui/react'; 13 | import { useContext, useEffect, useState } from 'react'; 14 | import { GlobalContext } from '../context/GlobalWrapper'; 15 | import InputsGroup from './InputsGroup'; 16 | 17 | export default function DrawerExample() { 18 | const { onOpen, isOpen, onClose, Add, errors, setErrors, user, Update } = 19 | useContext(GlobalContext); 20 | const [form, setForm] = useState({}); 21 | const onChangeHandler = (e) => { 22 | setForm({ 23 | ...form, 24 | [e.target.name]: e.target.value, 25 | }); 26 | }; 27 | 28 | const onAdd = () => { 29 | Add(form, setForm); 30 | }; 31 | 32 | const onUpdate = () => { 33 | Update(form, setForm, form._id); 34 | }; 35 | 36 | useEffect(() => { 37 | setForm(user); 38 | }, [user]); 39 | return ( 40 | <> 41 | 42 | 43 | 44 | { 46 | onClose(); 47 | setErrors({}); 48 | setForm({}); 49 | }} 50 | /> 51 | Create / Update user 52 | 53 | 54 | 55 | 61 | 67 | 73 | 79 | 80 | 81 | 82 | 83 | 94 | 100 | 101 | 102 | 103 | 104 | ); 105 | } 106 | -------------------------------------------------------------------------------- /client/src/components/InputsGroup.js: -------------------------------------------------------------------------------- 1 | import { 2 | FormControl, 3 | FormErrorMessage, 4 | FormLabel, 5 | Input, 6 | } from '@chakra-ui/react'; 7 | import React from 'react'; 8 | 9 | const InputsGroup = ({ name, onChangeHandler, value, errors }) => { 10 | return ( 11 | 12 | {name} 13 | 14 | {errors && 15 | errors?.map((err) => { 16 | return {err}; 17 | })} 18 | 19 | ); 20 | }; 21 | 22 | export default InputsGroup; 23 | -------------------------------------------------------------------------------- /client/src/components/Row.js: -------------------------------------------------------------------------------- 1 | import { Avatar, Box, Button, Td, Tr } from '@chakra-ui/react'; 2 | import React, { useContext } from 'react'; 3 | import { AiFillDelete, AiFillEdit } from 'react-icons/ai'; 4 | import { GlobalContext } from '../context/GlobalWrapper'; 5 | 6 | const Row = ({ id, fullname, email, age, country }) => { 7 | const { Delete, onOpen, FindOne } = useContext(GlobalContext); 8 | return ( 9 | 10 | 11 | 12 | 13 | {fullname} 14 | {email} 15 | {age} 16 | {country} 17 | 18 | 19 | 27 | 30 | 31 | 32 | 33 | ); 34 | }; 35 | 36 | export default Row; 37 | -------------------------------------------------------------------------------- /client/src/context/GlobalWrapper.js: -------------------------------------------------------------------------------- 1 | import { createContext, useState } from 'react'; 2 | import axios from 'axios'; 3 | import { useDisclosure, useToast } from '@chakra-ui/react'; 4 | export const GlobalContext = createContext(); 5 | 6 | export default function Wrapper({ children }) { 7 | const [users, setUsers] = useState([]); 8 | const [user, setUser] = useState({}); 9 | const [errors, setErrors] = useState({}); 10 | const { isOpen, onOpen, onClose } = useDisclosure(); 11 | const toast = useToast(); 12 | const FetchUsers = () => { 13 | axios 14 | .get('/api/users') 15 | .then((res) => { 16 | setUsers(res.data); 17 | }) 18 | .catch((err) => { 19 | console.log(err.reponse.data); 20 | }); 21 | }; 22 | 23 | const Search = (query) => { 24 | axios 25 | .post(`/api/users/search?key=${query}`) 26 | .then((res) => { 27 | setUsers(res.data); 28 | }) 29 | .catch((err) => { 30 | console.log(err.reponse.data); 31 | }); 32 | }; 33 | 34 | const Delete = (id) => { 35 | axios 36 | .delete(`/api/users/${id}`) 37 | .then((res) => { 38 | setUsers(users.filter((u) => u._id != id)); 39 | toast({ 40 | title: 'User Deleted', 41 | status: 'success', 42 | duration: 4000, 43 | isClosable: true, 44 | }); 45 | }) 46 | .catch((err) => { 47 | console.log(err.reponse.data); 48 | }); 49 | }; 50 | 51 | const Add = (form, setForm) => { 52 | axios 53 | .post('/api/users', form) 54 | .then((res) => { 55 | setUsers([...users, res.data]); 56 | toast({ 57 | title: 'User Added', 58 | status: 'success', 59 | duration: 4000, 60 | isClosable: true, 61 | }); 62 | setErrors({}); 63 | setForm({}); 64 | onClose(); 65 | }) 66 | .catch((err) => { 67 | setErrors(err.response.data.error); 68 | }); 69 | }; 70 | 71 | const FindOne = async (id) => { 72 | await axios 73 | .get(`/api/users/${id}`) 74 | .then((res) => { 75 | setUser(res.data); 76 | }) 77 | .catch((err) => { 78 | setErrors(err.response.data.error); 79 | }); 80 | }; 81 | 82 | const Update = (form, setForm, id) => { 83 | axios 84 | .put(`/api/users/${id}`, form) 85 | .then((res) => { 86 | toast({ 87 | title: 'User Updated', 88 | status: 'success', 89 | duration: 4000, 90 | isClosable: true, 91 | }); 92 | setErrors({}); 93 | setForm({}); 94 | onClose(); 95 | FetchUsers(); 96 | }) 97 | .catch((err) => { 98 | setErrors(err.response.data.error); 99 | }); 100 | }; 101 | return ( 102 | 120 | {children} 121 | 122 | ); 123 | } 124 | -------------------------------------------------------------------------------- /client/src/index.css: -------------------------------------------------------------------------------- 1 | @import url('https://fonts.googleapis.com/css2?family=Lato:wght@500&display=swap'); 2 | body { 3 | font-family: 'Lato', sans-serif !important; 4 | } 5 | -------------------------------------------------------------------------------- /client/src/index.js: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ReactDOM from 'react-dom/client'; 3 | import './index.css'; 4 | import App from './App'; 5 | import Wrapper from './context/GlobalWrapper'; 6 | import { ChakraProvider } from '@chakra-ui/react'; 7 | 8 | const root = ReactDOM.createRoot(document.getElementById('root')); 9 | root.render( 10 | 11 | 12 | 13 | 14 | , 15 | ); 16 | -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/nest-cli", 3 | "collection": "@nestjs/schematics", 4 | "sourceRoot": "src" 5 | } 6 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "crud-app", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "", 6 | "private": true, 7 | "license": "UNLICENSED", 8 | "scripts": { 9 | "prebuild": "rimraf dist", 10 | "build": "nest build", 11 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 12 | "start": "nest start", 13 | "start:dev": "nest start --watch", 14 | "start:debug": "nest start --debug --watch", 15 | "start:prod": "node dist/main", 16 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 17 | "test": "jest", 18 | "test:watch": "jest --watch", 19 | "test:cov": "jest --coverage", 20 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 21 | "test:e2e": "jest --config ./test/jest-e2e.json", 22 | "start:together": "concurrently 'npm run start:dev' 'npm start --prefix client'" 23 | }, 24 | "dependencies": { 25 | "@nestjs/common": "^9.0.0", 26 | "@nestjs/config": "^2.2.0", 27 | "@nestjs/core": "^9.0.0", 28 | "@nestjs/mongoose": "^9.2.0", 29 | "@nestjs/platform-express": "^9.0.0", 30 | "class-transformer": "^0.5.1", 31 | "class-validator": "^0.13.2", 32 | "concurrently": "^7.4.0", 33 | "mongoose": "^6.5.4", 34 | "reflect-metadata": "^0.1.13", 35 | "rimraf": "^3.0.2", 36 | "rxjs": "^7.2.0" 37 | }, 38 | "devDependencies": { 39 | "@faker-js/faker": "^7.5.0", 40 | "@nestjs/cli": "^9.0.0", 41 | "@nestjs/schematics": "^9.0.0", 42 | "@nestjs/testing": "^9.0.0", 43 | "@types/express": "^4.17.13", 44 | "@types/jest": "28.1.4", 45 | "@types/node": "^16.0.0", 46 | "@types/supertest": "^2.0.11", 47 | "@typescript-eslint/eslint-plugin": "^5.0.0", 48 | "@typescript-eslint/parser": "^5.0.0", 49 | "eslint": "^8.0.1", 50 | "eslint-config-prettier": "^8.3.0", 51 | "eslint-plugin-prettier": "^4.0.0", 52 | "jest": "28.1.2", 53 | "prettier": "^2.3.2", 54 | "source-map-support": "^0.5.20", 55 | "supertest": "^6.1.3", 56 | "ts-jest": "28.0.5", 57 | "ts-loader": "^9.2.3", 58 | "ts-node": "^10.0.0", 59 | "tsconfig-paths": "4.0.0", 60 | "typescript": "^4.3.5" 61 | }, 62 | "jest": { 63 | "moduleFileExtensions": [ 64 | "js", 65 | "json", 66 | "ts" 67 | ], 68 | "rootDir": "src", 69 | "testRegex": ".*\\.spec\\.ts$", 70 | "transform": { 71 | "^.+\\.(t|j)s$": "ts-jest" 72 | }, 73 | "collectCoverageFrom": [ 74 | "**/*.(t|j)s" 75 | ], 76 | "coverageDirectory": "../coverage", 77 | "testEnvironment": "node" 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { ConfigModule } from '@nestjs/config'; 3 | import { MongooseModule } from '@nestjs/mongoose'; 4 | import { UsersModule } from './users/users.module'; 5 | 6 | @Module({ 7 | imports: [ 8 | ConfigModule.forRoot(), 9 | MongooseModule.forRoot(process.env.MONGO_URI), 10 | UsersModule, 11 | ], 12 | }) 13 | export class AppModule {} 14 | -------------------------------------------------------------------------------- /src/dto/users.dto.ts: -------------------------------------------------------------------------------- 1 | import { IsEmail, IsNotEmpty } from 'class-validator'; 2 | 3 | export class UserDto { 4 | @IsNotEmpty() 5 | fullname: string; 6 | 7 | @IsEmail() 8 | email: string; 9 | 10 | @IsNotEmpty() 11 | age: number; 12 | 13 | @IsNotEmpty() 14 | country: string; 15 | } 16 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { ValidationPipe } from '@nestjs/common'; 2 | import { NestFactory } from '@nestjs/core'; 3 | import { ValidationError } from 'class-validator'; 4 | import { AppModule } from './app.module'; 5 | import { 6 | ValidationException, 7 | ValidationFilter, 8 | } from './util/filter.validation'; 9 | 10 | async function bootstrap() { 11 | const app = await NestFactory.create(AppModule); 12 | app.setGlobalPrefix('/api'); 13 | 14 | app.useGlobalFilters(new ValidationFilter()); 15 | app.useGlobalPipes( 16 | new ValidationPipe({ 17 | skipMissingProperties: false, 18 | exceptionFactory: (errors: ValidationError[]) => { 19 | const errMsg = {}; 20 | errors.forEach((err) => { 21 | errMsg[err.property] = [...Object.values(err.constraints)]; 22 | }); 23 | return new ValidationException(errMsg); 24 | }, 25 | }), 26 | ); 27 | 28 | const port = process.env.PORT; 29 | await app.listen(port); 30 | } 31 | bootstrap(); 32 | -------------------------------------------------------------------------------- /src/models/users.models.ts: -------------------------------------------------------------------------------- 1 | import { Prop, Schema, SchemaFactory } from '@nestjs/mongoose'; 2 | import { Document } from 'mongoose'; 3 | 4 | export type UserDocument = User & Document; 5 | 6 | @Schema() 7 | export class User { 8 | @Prop({ required: true }) 9 | fullname: string; 10 | 11 | @Prop({ required: true }) 12 | email: string; 13 | 14 | @Prop({ required: true }) 15 | age: number; 16 | 17 | @Prop({ required: true }) 18 | country: string; 19 | } 20 | 21 | export const UserSchema = SchemaFactory.createForClass(User); 22 | -------------------------------------------------------------------------------- /src/users/users.controller.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Body, 3 | Controller, 4 | Delete, 5 | Get, 6 | Param, 7 | Post, 8 | Put, 9 | Query, 10 | } from '@nestjs/common'; 11 | import { UserDto } from 'src/dto/users.dto'; 12 | import { UsersService } from './users.service'; 13 | 14 | @Controller('users') 15 | export class UsersController { 16 | constructor(private readonly service: UsersService) {} 17 | 18 | @Post() 19 | Add(@Body() body: UserDto) { 20 | return this.service.Add(body); 21 | } 22 | 23 | @Get() 24 | FindAll() { 25 | return this.service.FindAll(); 26 | } 27 | 28 | @Get('/:id') 29 | FindOne(@Param('id') id: string) { 30 | return this.service.FindOne(id); 31 | } 32 | 33 | @Put('/:id') 34 | Update(@Param('id') id: string, @Body() body: UserDto) { 35 | return this.service.Update(id, body); 36 | } 37 | 38 | @Delete('/:id') 39 | Delete(@Param('id') id: string) { 40 | return this.service.Delete(id); 41 | } 42 | 43 | @Post('/search') 44 | Search(@Query('key') key) { 45 | return this.service.Search(key); 46 | } 47 | 48 | @Post('faker') 49 | Faker() { 50 | return this.service.Faker(); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/users/users.module.ts: -------------------------------------------------------------------------------- 1 | import { Module } from '@nestjs/common'; 2 | import { MongooseModule } from '@nestjs/mongoose'; 3 | import { User, UserSchema } from 'src/models/users.models'; 4 | import { UsersController } from './users.controller'; 5 | import { UsersService } from './users.service'; 6 | 7 | @Module({ 8 | imports: [ 9 | MongooseModule.forFeature([{ name: User.name, schema: UserSchema }]), 10 | ], 11 | controllers: [UsersController], 12 | providers: [UsersService], 13 | }) 14 | export class UsersModule {} 15 | -------------------------------------------------------------------------------- /src/users/users.service.ts: -------------------------------------------------------------------------------- 1 | import { Body, Injectable } from '@nestjs/common'; 2 | import { InjectModel } from '@nestjs/mongoose'; 3 | import { Model } from 'mongoose'; 4 | import { UserDto } from 'src/dto/users.dto'; 5 | import { User, UserDocument } from 'src/models/users.models'; 6 | import { faker } from '@faker-js/faker'; 7 | 8 | @Injectable() 9 | export class UsersService { 10 | constructor(@InjectModel(User.name) private userModel: Model) {} 11 | Add(body: UserDto) { 12 | return this.userModel.create(body); 13 | } 14 | 15 | FindAll() { 16 | return this.userModel.find(); 17 | } 18 | 19 | FindOne(id: string) { 20 | return this.userModel.findOne({ _id: id }); 21 | } 22 | 23 | Update(id: string, body: UserDto) { 24 | return this.userModel.findByIdAndUpdate( 25 | { _id: id }, 26 | { $set: body }, 27 | { new: true }, 28 | ); 29 | } 30 | 31 | Delete(id: string) { 32 | return this.userModel.remove({ _id: id }); 33 | } 34 | 35 | Search(key: string) { 36 | const keyword = key 37 | ? { 38 | $or: [ 39 | { fullname: { $regex: key, $options: 'i' } }, 40 | { email: { $regex: key, $options: 'i' } }, 41 | ], 42 | } 43 | : {}; 44 | return this.userModel.find(keyword); 45 | } 46 | 47 | Faker() { 48 | for (let index = 0; index < 30; index++) { 49 | const fakeUser = { 50 | fullname: faker.name.fullName(), 51 | email: faker.internet.email(), 52 | age: 30, 53 | country: faker.address.city(), 54 | }; 55 | this.userModel.create(fakeUser); 56 | } 57 | return 'success'; 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/util/filter.validation.ts: -------------------------------------------------------------------------------- 1 | import { 2 | ArgumentsHost, 3 | BadRequestException, 4 | Catch, 5 | ExceptionFilter, 6 | } from '@nestjs/common'; 7 | 8 | export class ValidationException extends BadRequestException { 9 | constructor(public validationErrors: any) { 10 | super(); 11 | } 12 | } 13 | 14 | @Catch(ValidationException) 15 | export class ValidationFilter implements ExceptionFilter { 16 | catch(exception: ValidationException, host: ArgumentsHost): any { 17 | const ctx = host.switchToHttp(); 18 | const response = ctx.getResponse(); 19 | 20 | return response.status(400).json({ 21 | statusCode: 400, 22 | success: false, 23 | message: '', 24 | error: exception.validationErrors, 25 | }); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /test/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { INestApplication } from '@nestjs/common'; 3 | import * as request from 'supertest'; 4 | import { AppModule } from './../src/app.module'; 5 | 6 | describe('AppController (e2e)', () => { 7 | let app: INestApplication; 8 | 9 | beforeEach(async () => { 10 | const moduleFixture: TestingModule = await Test.createTestingModule({ 11 | imports: [AppModule], 12 | }).compile(); 13 | 14 | app = moduleFixture.createNestApplication(); 15 | await app.init(); 16 | }); 17 | 18 | it('/ (GET)', () => { 19 | return request(app.getHttpServer()) 20 | .get('/') 21 | .expect(200) 22 | .expect('Hello World!'); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /test/jest-e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "moduleFileExtensions": ["js", "json", "ts"], 3 | "rootDir": ".", 4 | "testEnvironment": "node", 5 | "testRegex": ".e2e-spec.ts$", 6 | "transform": { 7 | "^.+\\.(t|j)s$": "ts-jest" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "allowSyntheticDefaultImports": true, 9 | "target": "es2017", 10 | "sourceMap": true, 11 | "outDir": "./dist", 12 | "baseUrl": "./", 13 | "incremental": true, 14 | "skipLibCheck": true, 15 | "strictNullChecks": false, 16 | "noImplicitAny": false, 17 | "strictBindCallApply": false, 18 | "forceConsistentCasingInFileNames": false, 19 | "noFallthroughCasesInSwitch": false 20 | } 21 | } 22 | --------------------------------------------------------------------------------