├── .github └── FUNDING.yml ├── .vscode └── settings.json ├── LICENSE.md ├── README.md ├── client-search ├── .eslintrc.cjs ├── .gitignore ├── README.md ├── index.html ├── jsconfig.json ├── package-lock.json ├── package.json ├── postcss.config.js ├── public │ └── vite.svg ├── src │ ├── App.css │ ├── App.jsx │ ├── assets │ │ └── react.svg │ ├── hooks │ │ └── useDebounce.jsx │ ├── index.css │ ├── main.jsx │ ├── pages │ │ ├── cars │ │ │ ├── add │ │ │ │ └── page.jsx │ │ │ └── page.jsx │ │ ├── error.jsx │ │ ├── loading.jsx │ │ ├── movies │ │ │ └── page.jsx │ │ └── notfound.jsx │ └── routes │ │ └── index.jsx ├── tailwind.config.js ├── vite.config.js └── yarn.lock ├── service-search-algolia ├── .env.example ├── .eslintignore ├── .eslintrc.js ├── .gitattributes ├── .gitignore ├── .prettierignore ├── .prettierrc ├── .vscode │ └── settings.json ├── LICENSE.md ├── README.md ├── SEARCH.md ├── package.json ├── server.js └── src │ ├── app.js │ ├── app │ └── v1 │ │ ├── controllers │ │ └── car.controller.js │ │ ├── models │ │ └── .gitkeep │ │ ├── routes │ │ ├── cars │ │ │ └── index.js │ │ └── index.js │ │ └── services │ │ └── car.service.js │ ├── common │ ├── configs │ │ └── app.config.js │ ├── constants │ │ └── index.js │ ├── helpers │ │ ├── asyncHandler.js │ │ └── validate │ │ │ ├── index.js │ │ │ └── todo.validate.js │ ├── index │ │ └── cart.js │ └── utils │ │ ├── httpStatusCode.js │ │ ├── reasonPhrases.js │ │ └── statusCodes.js │ ├── cores │ ├── error.response.js │ └── success.response.js │ ├── dbs │ └── index.js │ ├── loggers │ └── winston.log.js │ └── middlewares │ └── rateLimitMiddleware.js ├── service-search-elastic ├── .dockerignore ├── .env.example ├── .eslintignore ├── .eslintrc.js ├── .gitattributes ├── .gitignore ├── .prettierignore ├── .prettierrc ├── .vscode │ └── settings.json ├── ELASTIC.md ├── LICENSE.md ├── README.md ├── SEARCH.md ├── addons │ ├── frontend-zips │ │ └── client-search.zip │ └── postman │ │ ├── Elastic Search.postman_collection.json │ │ └── ElasticSearch.postman_environment.json ├── docker-compose.yml ├── docker │ └── Dockerfile ├── elasticsearch │ └── config │ │ └── elasticsearch.yml ├── makefile ├── package.json ├── server.js └── src │ ├── app.js │ ├── app │ └── v1 │ │ ├── controllers │ │ └── car.controller.js │ │ ├── models │ │ └── .gitkeep │ │ ├── routes │ │ ├── cars │ │ │ └── index.js │ │ └── index.js │ │ └── services │ │ └── car.service.js │ ├── common │ ├── configs │ │ └── app.config.js │ ├── constants │ │ └── index.js │ ├── helpers │ │ ├── asyncHandler.js │ │ └── validate │ │ │ ├── index.js │ │ │ └── todo.validate.js │ ├── index │ │ └── cars.js │ └── utils │ │ ├── httpStatusCode.js │ │ ├── reasonPhrases.js │ │ └── statusCodes.js │ ├── cores │ ├── error.response.js │ └── success.response.js │ ├── dbs │ └── index.js │ ├── loggers │ └── winston.log.js │ └── middlewares │ └── rateLimitMiddleware.js └── service-search-redis ├── .dockerignore ├── .env.example ├── .eslintignore ├── .eslintrc.js ├── .gitattributes ├── .gitignore ├── .prettierignore ├── .prettierrc ├── README.md ├── docker-compose.yml ├── docker ├── Dockerfile ├── Dockerfile-redis ├── dataset │ ├── import_actors.redis │ ├── import_create_index.redis │ ├── import_movies.redis │ ├── import_theaters.redis │ └── import_users.redis └── import-data.sh ├── makefile ├── package.json ├── server.js └── src ├── app.js ├── app └── v1 │ ├── controllers │ ├── car.controller.js │ └── movie.controller.js │ ├── models │ ├── .gitkeep │ └── schemas │ │ └── car.schema.js │ ├── routes │ ├── cars │ │ └── index.js │ ├── index.js │ └── movies │ │ └── index.js │ └── services │ ├── car.service.js │ └── movie.service.js ├── common ├── cache │ └── cart.js ├── configs │ ├── app.config.js │ └── redis.config.js ├── constants │ └── index.js ├── helpers │ ├── asyncHandler.js │ └── validate │ │ ├── index.js │ │ └── todo.validate.js └── utils │ ├── httpStatusCode.js │ ├── reasonPhrases.js │ └── statusCodes.js ├── cores ├── error.response.js └── success.response.js ├── dbs ├── client.js └── index.js ├── loggers └── winston.log.js └── middlewares └── rateLimitMiddleware.js /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | github: 3 | - fdhhhdjd 4 | # Up to 4 GitHub Sponsors-enabled usernames, e.g., [user1, user2] 5 | patreon: 6 | user?u=65668237 7 | # A single Patreon username with user ID, e.g., user?u=65668237 8 | open_collective: 9 | # A single Open Collective username 10 | ko_fi: 11 | tientainguyen 12 | # A single Ko-fi username 13 | tidelift: 14 | # A single Tidelift platform-name/package-name, e.g., npm/babel 15 | community_bridge: 16 | # A single Community Bridge project-name, e.g., cloud-foundry 17 | liberapay: nguyentientai 18 | 19 | issuehunt: 20 | # A single IssueHunt username 21 | otechie: 22 | # A single Otechie username 23 | custom: https://profile-forme.com 24 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "typescript.tsdk": "node_modules/typescript/lib", 3 | "typescript.enablePromptUseWorkspaceTsdk": true, 4 | "editor.formatOnSave": true, 5 | "editor.defaultFormatter": "esbenp.prettier-vscode", 6 | "files.exclude": { 7 | "**/node_modules": false, 8 | "**/dist": true, 9 | "tsconfig.json": true 10 | }, 11 | "emmet.triggerExpansionOnTab": true, 12 | "editor.autoClosingBrackets": "always", 13 | "editor.autoClosingQuotes": "always" 14 | } 15 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Nguyen Tien Tai 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | Linkedin 5 | Profile 6 | Phone 7 | License 8 |

9 | 10 | ## Project: Redis Search Engine 11 | 12 | ## Team Word: Liên hệ công việc https://profile-forme.com 13 | 14 | ## 1. Nguyen Tien Tai( MainTain 🚩). 15 | 16 | ## Tài Khoản Donate li Cf để có động lực code cho anh em tham khảo 😄. 17 | 18 | ![giphy](https://3.bp.blogspot.com/-SzGvXn2sTmw/V6k-90GH3ZI/AAAAAAAAIsk/Q678Pil-0kITLPa3fD--JkNdnJVKi_BygCLcB/s1600/cf10-fbc08%2B%25281%2529.gif) 19 | 20 | ## Mk: NGUYEN TIEN TAI 21 | 22 | ## STK: 1651002972052 23 | 24 | ## Chi Nhánh: NGAN HANG TMCP AN BINH (ABBANK). 25 | 26 | ## SUPPORT CONTACT: [https://profile-forme.com](https://profile-forme.com) 27 | 28 | ## Thank You <3. 29 | -------------------------------------------------------------------------------- /client-search/.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { browser: true, es2020: true }, 4 | extends: [ 5 | 'eslint:recommended', 6 | 'plugin:react/recommended', 7 | 'plugin:react/jsx-runtime', 8 | 'plugin:react-hooks/recommended', 9 | ], 10 | ignorePatterns: ['dist', '.eslintrc.cjs'], 11 | parserOptions: { ecmaVersion: 'latest', sourceType: 'module' }, 12 | settings: { react: { version: '18.2' } }, 13 | plugins: ['react-refresh'], 14 | rules: { 15 | 'react-refresh/only-export-components': [ 16 | 'warn', 17 | { allowConstantExport: true }, 18 | ], 19 | }, 20 | } 21 | -------------------------------------------------------------------------------- /client-search/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | pnpm-debug.log* 8 | lerna-debug.log* 9 | 10 | node_modules 11 | dist 12 | dist-ssr 13 | *.local 14 | 15 | # Editor directories and files 16 | .vscode/* 17 | !.vscode/extensions.json 18 | .idea 19 | .DS_Store 20 | *.suo 21 | *.ntvs* 22 | *.njsproj 23 | *.sln 24 | *.sw? 25 | -------------------------------------------------------------------------------- /client-search/README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | Linkedin 5 | Profile 6 | Phone 7 | License 8 |

9 | 10 | ## Project: Service Search 11 | 12 | ## Team Word: Liên hệ công việc https://profile-forme.com 13 | 14 | ## 1. Nguyen Tien Tai( MainTain 🚩). 15 | 16 | ## Tài Khoản Donate li Cf để có động lực code cho anh em tham khảo 😄. 17 | 18 | ![giphy](https://3.bp.blogspot.com/-SzGvXn2sTmw/V6k-90GH3ZI/AAAAAAAAIsk/Q678Pil-0kITLPa3fD--JkNdnJVKi_BygCLcB/s1600/cf10-fbc08%2B%25281%2529.gif) 19 | 20 | ## Mk: NGUYEN TIEN TAI 21 | 22 | ## STK: 1651002972052 23 | 24 | ## Chi Nhánh: NGAN HANG TMCP AN BINH (ABBANK). 25 | 26 | ## SUPPORT CONTACT: [https://profile-forme.com](https://profile-forme.com) 27 | 28 | ## Thank You <3. 29 | -------------------------------------------------------------------------------- /client-search/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | Vite + React 8 | 9 | 10 |
11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /client-search/jsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "baseUrl": ".", 4 | "paths": { 5 | "@/*": ["src/*"] 6 | } 7 | }, 8 | "include": ["src/**/*"] 9 | } 10 | -------------------------------------------------------------------------------- /client-search/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "client-search", 3 | "private": true, 4 | "version": "0.0.0", 5 | "type": "module", 6 | "scripts": { 7 | "dev": "vite", 8 | "build": "vite build", 9 | "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0", 10 | "preview": "vite preview" 11 | }, 12 | "dependencies": { 13 | "lodash": "^4.17.21", 14 | "react": "^18.2.0", 15 | "react-dom": "^18.2.0", 16 | "react-router-dom": "^6.21.2", 17 | "react-toastify": "^10.0.3" 18 | }, 19 | "devDependencies": { 20 | "@types/react": "^18.2.43", 21 | "@types/react-dom": "^18.2.17", 22 | "@vitejs/plugin-react": "^4.2.1", 23 | "@vitejs/plugin-react-swc": "^3.5.0", 24 | "autoprefixer": "^10.4.16", 25 | "eslint": "^8.55.0", 26 | "eslint-plugin-react": "^7.33.2", 27 | "eslint-plugin-react-hooks": "^4.6.0", 28 | "eslint-plugin-react-refresh": "^0.4.5", 29 | "postcss": "^8.4.33", 30 | "tailwindcss": "^3.4.1", 31 | "vite": "^5.0.8" 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /client-search/postcss.config.js: -------------------------------------------------------------------------------- 1 | export default { 2 | plugins: { 3 | tailwindcss: {}, 4 | autoprefixer: {}, 5 | }, 6 | } 7 | -------------------------------------------------------------------------------- /client-search/public/vite.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client-search/src/App.css: -------------------------------------------------------------------------------- 1 | .top-100 {top: 100%} 2 | .bottom-100 {bottom: 100%} 3 | .max-h-select { 4 | max-height: 300px; 5 | } 6 | body { 7 | background-color: rgb(154, 149, 149); 8 | } -------------------------------------------------------------------------------- /client-search/src/App.jsx: -------------------------------------------------------------------------------- 1 | //* LIB 2 | import React from "react"; 3 | import { Outlet } from "react-router-dom"; 4 | import { ToastContainer } from "react-toastify"; 5 | 6 | const App = () => { 7 | return ( 8 | 9 | 20 | 21 | 22 | ); 23 | }; 24 | 25 | export default App; 26 | -------------------------------------------------------------------------------- /client-search/src/assets/react.svg: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /client-search/src/hooks/useDebounce.jsx: -------------------------------------------------------------------------------- 1 | import React from "react"; 2 | 3 | const useDebounce = (value, delay) => { 4 | const [debouncedValue, setDebouncedValue] = React.useState(value); 5 | 6 | React.useEffect(() => { 7 | const timeoutId = setTimeout(() => { 8 | setDebouncedValue(value); 9 | }, delay); 10 | 11 | return () => { 12 | clearTimeout(timeoutId); 13 | }; 14 | }, [value, delay]); 15 | 16 | return debouncedValue; 17 | }; 18 | 19 | export default useDebounce; 20 | -------------------------------------------------------------------------------- /client-search/src/index.css: -------------------------------------------------------------------------------- 1 | @tailwind base; 2 | @tailwind components; 3 | @tailwind utilities; 4 | -------------------------------------------------------------------------------- /client-search/src/main.jsx: -------------------------------------------------------------------------------- 1 | //* LIB 2 | import ReactDOM from "react-dom/client"; 3 | import { RouterProvider } from "react-router-dom"; 4 | 5 | //* IMPORT 6 | import "./App.css"; 7 | import "./index.css"; 8 | import "react-toastify/dist/ReactToastify.css"; 9 | import LoadingPage from "@/pages/loading.jsx"; 10 | import router from "@/routes/index.jsx"; 11 | 12 | ReactDOM.createRoot(document.getElementById("root")).render( 13 | } /> 14 | ); 15 | -------------------------------------------------------------------------------- /client-search/src/pages/cars/add/page.jsx: -------------------------------------------------------------------------------- 1 | //* LIB 2 | import React from "react"; 3 | import { useNavigate } from "react-router-dom"; 4 | import { toast } from "react-toastify"; 5 | 6 | const AddCarPage = () => { 7 | const Navigate = useNavigate(); 8 | 9 | const [formData, setFormData] = React.useState({ 10 | make: "", 11 | model: "", 12 | image: "", 13 | description: "", 14 | }); 15 | 16 | const handleSubmit = async (event) => { 17 | event.preventDefault(); 18 | if ( 19 | !formData.make || 20 | !formData.model || 21 | !formData.image || 22 | !formData.description 23 | ) { 24 | return toast.error("Please fill in all fields"); 25 | } 26 | try { 27 | const username = "elastic"; 28 | const password = "rvfyXraoEchd5S3g4k5J"; 29 | 30 | const credentials = btoa(`${username}:${password}`); 31 | const authorizationHeader = `Basic ${credentials}`; 32 | const response = await fetch("http://localhost:9200/car_info/_doc", { 33 | method: "POST", 34 | headers: { 35 | "Content-Type": "application/json", 36 | "Authorization": authorizationHeader 37 | }, 38 | body: JSON.stringify(formData), 39 | }); 40 | 41 | if (response.ok) { 42 | toast.success("Data sent successfully"); 43 | resetForm(); 44 | return Navigate("/cars"); 45 | } else { 46 | toast.error("Failed to send data"); 47 | } 48 | } catch (error) { 49 | toast.error("Error:", error); 50 | } 51 | }; 52 | 53 | const handleChange = (event) => { 54 | const { name, value } = event.target; 55 | setFormData((prevData) => ({ 56 | ...prevData, 57 | [name]: value, 58 | })); 59 | }; 60 | 61 | const resetForm = () => { 62 | return setFormData({ 63 | make: "", 64 | model: "", 65 | image: "", 66 | description: "", 67 | }); 68 | }; 69 | 70 | return ( 71 | <> 72 |
73 |
74 |
75 |

76 | Create Data Search 77 |

78 |
79 | 80 |
81 | {/* ... other form elements ... */} 82 |
83 |
84 | 90 | 99 | {/*

100 | Please fill out this field. 101 |

*/} 102 |
103 | 104 |
105 | 111 | 120 |
121 |
122 | 128 | 137 |
138 |
139 | 145 | 154 |
155 |
156 | 157 | {/* ... other form elements ... */} 158 | 159 |
160 |
161 | 167 |
168 |
169 |
170 |
171 | 172 | ); 173 | }; 174 | 175 | export default AddCarPage; 176 | -------------------------------------------------------------------------------- /client-search/src/pages/cars/page.jsx: -------------------------------------------------------------------------------- 1 | //* LIB 2 | import useDebounce from "@/hooks/useDebounce"; 3 | import React from "react"; 4 | import { Link, Outlet } from "react-router-dom"; 5 | 6 | const CarPage = () => { 7 | const [search, setSearch] = React.useState(""); 8 | const [open, setOpen] = React.useState(false); 9 | const [items, setItems] = React.useState([]); 10 | const [count, setCount] = React.useState(0); 11 | 12 | const searchInputRef = React.useRef(null); 13 | 14 | const debouncedQuery = useDebounce(search, 300); 15 | 16 | const handleToggle = () => { 17 | setOpen(!open); 18 | if (debouncedQuery.trim() !== "") { 19 | fetchData( 20 | `http://localhost:2000/api/v1/cars/search?q=${encodeURIComponent( 21 | search 22 | )}` 23 | ); 24 | } else { 25 | fetchData(`http://localhost:2000/api/v1/cars/get/all`); 26 | } 27 | }; 28 | 29 | const handleClickOutside = (event) => { 30 | if ( 31 | searchInputRef.current && 32 | !searchInputRef.current.contains(event.target) 33 | ) { 34 | setOpen(false); 35 | setItems([]); 36 | setCount(0); 37 | } 38 | }; 39 | 40 | const fetchData = async ( 41 | url = "http://localhost:2000/api/v1/cars/get/all" 42 | ) => { 43 | try { 44 | const response = await fetch(url); 45 | const data = await response.json(); 46 | setItems(data?.metadata?.cars); 47 | setCount(data?.metadata?.count); 48 | } catch (error) { 49 | console.error("Error fetching data:", error); 50 | } 51 | }; 52 | 53 | React.useEffect(() => { 54 | document.addEventListener("click", handleClickOutside); 55 | 56 | return () => { 57 | document.removeEventListener("click", handleClickOutside); 58 | }; 59 | }, []); 60 | 61 | React.useEffect(() => { 62 | if (debouncedQuery.trim() !== "") { 63 | fetchData( 64 | `http://localhost:2000/api/v1/cars/search?q=${encodeURIComponent( 65 | search 66 | )}` 67 | ); 68 | } else { 69 | fetchData(`http://localhost:2000/api/v1/cars/get/all`); 70 | } 71 | }, [debouncedQuery]); 72 | 73 | return ( 74 |
75 |
76 |

77 | Redis Search Count: {count} 78 |

79 |
80 | setSearch(e.target.value)} 85 | placeholder="Search Here..." 86 | className="py-3 px-4 w-1/2 rounded shadow font-thin focus:outline-none focus:shadow-lg focus:shadow-slate-200 duration-100 shadow-gray-100" 87 | ref={searchInputRef} 88 | /> 89 | 90 | 120 |
121 | ); 122 | }; 123 | 124 | export default CarPage; 125 | -------------------------------------------------------------------------------- /client-search/src/pages/error.jsx: -------------------------------------------------------------------------------- 1 | const ErrorPage = () => { 2 | return

ErrorPage

; 3 | }; 4 | 5 | export default ErrorPage; 6 | -------------------------------------------------------------------------------- /client-search/src/pages/loading.jsx: -------------------------------------------------------------------------------- 1 | const LoadingPage = () => { 2 | return

LoadingPage

; 3 | }; 4 | 5 | export default LoadingPage; 6 | -------------------------------------------------------------------------------- /client-search/src/pages/movies/page.jsx: -------------------------------------------------------------------------------- 1 | //* LIB 2 | import React from "react"; 3 | 4 | //* IMPORT 5 | import useDebounce from "@/hooks/useDebounce"; 6 | 7 | const MoviePage = () => { 8 | const [flag, setFlag] = React.useState(false); 9 | const dropdownRef = React.useRef(null); 10 | const [query, setQuery] = React.useState(""); 11 | const [results, setResults] = React.useState([]); 12 | 13 | const handleSearch = async () => { 14 | try { 15 | const response = await fetch( 16 | `http://localhost:5000/api/v1/movies/search/idx?idx=idx:movie&query=${query}` 17 | ); 18 | const data = await response.json(); 19 | setResults(data?.metadata?.documents); 20 | } catch (error) { 21 | console.error("Error fetching search results:", error); 22 | } 23 | }; 24 | 25 | const debouncedQuery = useDebounce(query, 300); 26 | 27 | const handleToggle = () => { 28 | setFlag(true); 29 | }; 30 | 31 | React.useEffect(() => { 32 | if (debouncedQuery.trim() !== "") { 33 | handleSearch(); 34 | } else { 35 | setResults([]); 36 | } 37 | }, [debouncedQuery]); 38 | 39 | const handleOutsideClick = (e) => { 40 | if (dropdownRef.current && !dropdownRef.current.contains(e.target)) { 41 | setFlag(false); 42 | } 43 | }; 44 | 45 | React.useEffect(() => { 46 | handleSearch(); 47 | document.addEventListener("mousedown", handleOutsideClick); 48 | return () => { 49 | document.removeEventListener("mousedown", handleOutsideClick); 50 | }; 51 | }, [debouncedQuery]); 52 | 53 | return ( 54 | <> 55 |
56 |
57 |
58 |
59 |
60 |
61 | setQuery(e.target.value)} 66 | placeholder="Search movies..." 67 | onFocus={handleToggle} 68 | /> 69 |
70 | 87 |
88 |
89 |
90 | {flag && ( 91 |
92 |
93 | {results?.map((option, index) => ( 94 | 95 |
96 |
97 |
98 |
99 | A 108 |
109 |
110 |
111 |
112 | 113 | {option.value.title + 114 | " " + 115 | option.value.genre} 116 | 117 |
118 | {option.value.plot} 119 |
120 |
121 |
122 |
123 |
124 |
125 | ))} 126 |
127 |
128 | )} 129 |
130 |
131 |
132 |
133 | 134 | ); 135 | }; 136 | 137 | export default MoviePage; 138 | -------------------------------------------------------------------------------- /client-search/src/pages/notfound.jsx: -------------------------------------------------------------------------------- 1 | const NotFoundPage = () => { 2 | return

NotFoundPage

; 3 | }; 4 | 5 | export default NotFoundPage; 6 | -------------------------------------------------------------------------------- /client-search/src/routes/index.jsx: -------------------------------------------------------------------------------- 1 | //* LIB 2 | import { createBrowserRouter } from "react-router-dom"; 3 | 4 | //* IMPORT 5 | import ErrorPage from "@/pages/error"; 6 | import MoviePage from "@/pages/movies/page"; 7 | import NotFoundPage from "@/pages/notfound"; 8 | import CarPage from "@/pages/cars/page"; 9 | import App from "@/App"; 10 | import AddCarPage from "@/pages/cars/add/page"; 11 | 12 | const routes = [ 13 | { 14 | path: "/", 15 | element: , 16 | errorElement: , 17 | children: [ 18 | { 19 | index: true, 20 | element: , 21 | }, 22 | { 23 | path: "cars", 24 | element: , 25 | }, 26 | { 27 | path: "cars/add", 28 | element: , 29 | }, 30 | ], 31 | }, 32 | { 33 | path: "*", 34 | element: , 35 | errorElement: , 36 | }, 37 | ]; 38 | 39 | const router = createBrowserRouter(routes); 40 | 41 | export default router; 42 | -------------------------------------------------------------------------------- /client-search/tailwind.config.js: -------------------------------------------------------------------------------- 1 | /** @type {import('tailwindcss').Config} */ 2 | export default { 3 | content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"], 4 | theme: { 5 | extend: {}, 6 | }, 7 | plugins: [], 8 | }; 9 | -------------------------------------------------------------------------------- /client-search/vite.config.js: -------------------------------------------------------------------------------- 1 | import { defineConfig, loadEnv } from "vite"; 2 | import react from "@vitejs/plugin-react-swc"; 3 | import path from "path"; 4 | // https://vitejs.dev/config/ 5 | export default defineConfig(({ mode }) => { 6 | // eslint-disable-next-line no-undef 7 | const env = loadEnv(mode, process.cwd(), ""); 8 | 9 | return { 10 | define: { 11 | "process.env": env, 12 | }, 13 | base: "/", 14 | plugins: [react()], 15 | resolve: { 16 | alias: { 17 | // eslint-disable-next-line no-undef 18 | "@": path.resolve(__dirname, "./src"), 19 | }, 20 | }, 21 | }; 22 | }); 23 | -------------------------------------------------------------------------------- /service-search-algolia/.env.example: -------------------------------------------------------------------------------- 1 | # APP NODE 2 | NODE_ENV='' 3 | 4 | # MORGAN 5 | MORGAN='' 6 | 7 | # PORT APP 8 | PORT='' 9 | 10 | # Algolia 11 | ADMIN_API_KEY= 12 | APP_ID= 13 | -------------------------------------------------------------------------------- /service-search-algolia/.eslintignore: -------------------------------------------------------------------------------- 1 | build/_.js 2 | config/_.js 3 | [Bb]uild* 4 | [Dd]ist* 5 | [Bb]in\* 6 | package-lock.json 7 | docker-compose.yml 8 | 9 | node_modules/ 10 | public/ 11 | build/ 12 | .github/ 13 | *.css 14 | *.svg 15 | *.config.js -------------------------------------------------------------------------------- /service-search-algolia/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | node: true, 4 | commonjs: false, 5 | es2021: true, 6 | }, 7 | 8 | extends: ['eslint:recommended', 'plugin:prettier/recommended', 'plugin:security/recommended-legacy'], 9 | plugins: ['prettier', 'import', 'security', 'promise'], 10 | parserOptions: { 11 | ecmaVersion: 2021, 12 | sourceType: 'module', 13 | }, 14 | rules: { 15 | 'prettier/prettier': ['error'], 16 | quotes: ['error', 'single'], 17 | semi: ['error', 'always'], 18 | 'import/order': [ 19 | 'error', 20 | { 21 | groups: [['builtin', 'external'], 'internal', ['sibling', 'parent'], 'index', 'unknown'], 22 | 'newlines-between': 'always', 23 | alphabetize: { 24 | order: 'asc', 25 | caseInsensitive: true, 26 | }, 27 | pathGroups: [ 28 | { 29 | pattern: '@/**', 30 | group: 'internal', 31 | position: 'after', 32 | }, 33 | ], 34 | pathGroupsExcludedImportTypes: ['builtin'], 35 | }, 36 | ], 37 | 38 | 'no-console': [ 39 | 'error', 40 | { 41 | allow: ['info', 'warn', 'error', 'time', 'timeEnd'], 42 | }, 43 | ], 44 | 'prefer-const': 'warn', 45 | 'max-len': ['error', 200], 46 | 'array-bracket-newline': 'warn', 47 | 'consistent-return': 'error', 48 | eqeqeq: 'error', 49 | 'no-unused-expressions': ['error', { allowTernary: true }], 50 | 'no-unused-vars': [ 51 | 'error', 52 | { 53 | varsIgnorePattern: '^_', 54 | argsIgnorePattern: '^_', 55 | vars: 'all', 56 | args: 'after-used', 57 | ignoreRestSiblings: false, 58 | }, 59 | ], 60 | 61 | 'operator-linebreak': [ 62 | 'error', 63 | 'after', 64 | { overrides: { '?': 'before', ':': 'before', '&&': 'before', '||': 'before' } }, 65 | ], 66 | 67 | 'linebreak-style': ['error', process.platform === 'win64' && 'win32' ? 'windows' : 'unix'], 68 | 69 | 'no-plusplus': ['error', { allowForLoopAfterthoughts: true }], 70 | 71 | 'arrow-parens': ['error', 'always'], 72 | 73 | 'lines-between-class-members': ['error', 'always', { exceptAfterSingleLine: true }], 74 | 75 | 'no-extra-parens': 'error', 76 | 'no-return-await': 'error', 77 | 'no-duplicate-imports': 'error', 78 | 79 | 'no-undef': 'off', 80 | 81 | 'security/detect-non-literal-fs-filename': 'error', 82 | 'security/detect-object-injection': 'error', 83 | 84 | 'promise/always-return': 'error', 85 | 'promise/no-return-wrap': 'error', 86 | 'promise/param-names': 'error', 87 | 'promise/catch-or-return': 'error', 88 | 'promise/no-native': 'off', 89 | 'promise/no-nesting': 'warn', 90 | 'promise/no-promise-in-callback': 'warn', 91 | 'promise/no-callback-in-promise': 'warn', 92 | 'promise/avoid-new': 'warn', 93 | 'promise/no-new-statics': 'error', 94 | 'promise/no-return-in-finally': 'warn', 95 | 'promise/valid-params': 'warn', 96 | }, 97 | }; 98 | -------------------------------------------------------------------------------- /service-search-algolia/.gitattributes: -------------------------------------------------------------------------------- 1 | # Handle line endings automatically for files detected as text 2 | # and leave all files detected as binary untouched. 3 | * text=false 4 | 5 | # 6 | # The above will handle all files NOT found below 7 | # 8 | # These files are text and should be normalized (Convert crlf => lf) 9 | *.df eol=lf 10 | *.html eol=lf 11 | *.java eol=lf 12 | *.json eol=lf 13 | *.jsp eol=lf 14 | *.jspf eol=lf 15 | *.jspx eol=lf 16 | *.properties eol=lf 17 | *.sh eol=lf 18 | *.tld eol=lf 19 | *.ts eol=lf 20 | *.txt eol=lf 21 | *.tag eol=lf 22 | *.tagx eol=lf 23 | *.xml eol=lf 24 | *.yml eol=lf 25 | *.env eol=lf 26 | 27 | .gitignore eol=lf 28 | .gitattributes eol=lf 29 | .eslintignore eol=lf 30 | .prettierignore eol=lf 31 | .js eol=lf 32 | .css eol=lf 33 | .htm eol=lf 34 | 35 | 36 | 37 | # These files are binary and should be left untouched 38 | # (binary is a macro for -text -diff) 39 | *.class binary 40 | *.dll binary 41 | *.ear binary 42 | *.gif binary 43 | *.ico binary 44 | *.jar binary 45 | *.jpg binary 46 | *.jpeg binary 47 | *.png binary 48 | *.so binary 49 | *.war binary -------------------------------------------------------------------------------- /service-search-algolia/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | *.log 3 | npm-debug.log* 4 | yarn-debug.log* 5 | yarn-error.log* 6 | pnpm-debug.log* 7 | lerna-debug.log* 8 | 9 | dist-ssr 10 | *.local 11 | 12 | # Editor directories and files 13 | # .vscode/* 14 | !.vscode/extensions.json 15 | .idea 16 | .DS_Store 17 | *.suo 18 | *.ntvs* 19 | *.njsproj 20 | *.sln 21 | *.sw? 22 | 23 | package-lock.json 24 | yarn.lock 25 | .env 26 | 27 | 28 | node_modules 29 | .env 30 | redis-master 31 | redis-slave 32 | docker-entrypoint-initdb.d 33 | setup 34 | file 35 | script/log_script_redis_date.txt 36 | script/.env 37 | test/jest/.env 38 | 39 | redis -------------------------------------------------------------------------------- /service-search-algolia/.prettierignore: -------------------------------------------------------------------------------- 1 | package.json 2 | package-lock.json 3 | public 4 | node_modules 5 | build 6 | .github 7 | -------------------------------------------------------------------------------- /service-search-algolia/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "arrowParens": "always", 3 | "bracketSameLine": false, 4 | "bracketSpacing": true, 5 | "embeddedLanguageFormatting": "auto", 6 | "insertPragma": false, 7 | "jsxSingleQuote": false, 8 | "printWidth": 120, 9 | "proseWrap": "preserve", 10 | "quoteProps": "as-needed", 11 | "requirePragma": false, 12 | "semi": true, 13 | "singleQuote": true, 14 | "tabWidth": 4, 15 | "trailingComma": "all", 16 | "useTabs": false, 17 | "vueIndentScriptAndStyle": false, 18 | "endOfLine": "lf" 19 | } 20 | -------------------------------------------------------------------------------- /service-search-algolia/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnSave": true 3 | } 4 | -------------------------------------------------------------------------------- /service-search-algolia/LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Nguyen Tien Tai 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /service-search-algolia/README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | Linkedin 5 | Profile 6 | Phone 7 | License 8 |

9 | 10 | ## Project: Service Search Algolia 11 | 12 | ## Team Word: Liên hệ công việc https://profile-forme.com 13 | 14 | ## 1. Nguyen Tien Tai( MainTain 🚩). 15 | 16 | ## Tài Khoản Donate li Cf để có động lực code cho anh em tham khảo 😄. 17 | 18 | ![giphy](https://3.bp.blogspot.com/-SzGvXn2sTmw/V6k-90GH3ZI/AAAAAAAAIsk/Q678Pil-0kITLPa3fD--JkNdnJVKi_BygCLcB/s1600/cf10-fbc08%2B%25281%2529.gif) 19 | 20 | ## Mk: NGUYEN TIEN TAI 21 | 22 | ## STK: 1651002972052 23 | 24 | ## Chi Nhánh: NGAN HANG TMCP AN BINH (ABBANK). 25 | 26 | ## SUPPORT CONTACT: [https://profile-forme.com](https://profile-forme.com) 27 | 28 | ## Thank You <3. 29 | -------------------------------------------------------------------------------- /service-search-algolia/SEARCH.md: -------------------------------------------------------------------------------- 1 | ## 1: Search Theo Từ khóa: 2 | 3 | ```javascript 4 | const result1 = await index.search('your_keyword'); 5 | ``` 6 | 7 | ## 2: Tìm Kiếm Theo Mô Hình Phân Cấp (Faceting): 8 | 9 | ```javascript 10 | const result2 = await index.search('your_keyword', { 11 | facets: ['category', 'price', 'brand'], 12 | }); 13 | ``` 14 | 15 | ## 3: Tìm Kiếm Theo Dải Giá: 16 | 17 | ```javascript 18 | const result3 = await index.search('', { 19 | filters: 'price:[min_price TO max_price]', 20 | }); 21 | ``` 22 | 23 | ## 4: Tìm Kiếm Gần Đúng (Fuzzy Search): 24 | 25 | ```javascript 26 | const result4 = await index.search('your_keyword~'); 27 | ``` 28 | 29 | ## 5: Tìm Kiếm Theo Vị Trí (Geolocation): 30 | 31 | ```javascript 32 | const result5 = await index.search('', { 33 | aroundLatLng: 'lat,lng', 34 | aroundRadius: 10000, // Đơn vị tính mét 35 | }); 36 | ``` 37 | 38 | ## 6: Tìm Kiếm Theo Ngày: 39 | 40 | ```javascript 41 | const result5 = await index.search('', { 42 | aroundLatLng: 'lat,lng', 43 | aroundRadius: 10000, // Đơn vị tính mét 44 | }); 45 | ``` 46 | 47 | ## 7: Tìm Kiếm Theo Danh Mục: 48 | 49 | ```javascript 50 | const result7 = await index.search('your_keyword', { 51 | filters: 'category:electronics', 52 | }); 53 | ``` 54 | 55 | ## 8: Tìm Kiếm Theo Nhiều Từ Khóa (AND): 56 | 57 | ```javascript 58 | const result8 = await index.search('keyword1 AND keyword2'); 59 | ``` 60 | 61 | ## 9: Tìm Kiếm Theo Từ Khóa Phổ Biến: 62 | 63 | ```javascript 64 | const result9 = await index.search('popular_keywords'); 65 | ``` 66 | 67 | ## 10: Tìm Kiếm Đa Truy Vấn (Boolean Query): 68 | 69 | ```javascript 70 | const result10 = await index.search('keyword1 AND (keyword2 OR keyword3) NOT keyword4'); 71 | ``` 72 | 73 | ## 11: Sắp Xếp Kết Quả: 74 | 75 | ```javascript 76 | const result = await index.search('search_query', { 77 | facets: ['category', 'brand', 'price'], 78 | sortBy: ['relevance', 'price:asc'], 79 | }); 80 | ``` 81 | 82 | ## 12: Phân Trang Kết Quả: 83 | 84 | ```javascript 85 | const result = await index.search('search_query', { 86 | facets: ['category', 'brand', 'price'], 87 | hitsPerPage: 10, 88 | page: 1, 89 | }); 90 | ``` 91 | 92 | ## 13: Tìm Kiếm Đa Nguồn: 93 | 94 | ```javascript 95 | const result = await searchClient.multipleQueries([ 96 | { 97 | indexName: 'index1', 98 | query: 'search_query', 99 | }, 100 | { 101 | indexName: 'index2', 102 | query: 'search_query', 103 | }, 104 | ]); 105 | ``` 106 | 107 | ## 14: Gợi Ý Tìm Kiếm (Autocomplete): 108 | 109 | ```javascript 110 | const result = await index.search('partial_query', { 111 | facets: ['category', 'brand', 'price'], 112 | hitsPerPage: 5, 113 | }); 114 | ``` 115 | 116 | ## 15: Lấy những trường cần 117 | 118 | ```javascript 119 | const result = await index.search('search_query', { 120 | facets: ['category', 'brand', 'price'], 121 | attributesToRetrieve: ['make', 'model', 'image', 'description'], 122 | hitsPerPage: 10, 123 | }); 124 | 125 | // Kết quả sẽ chỉ chứa các trường được chỉ định trong attributesToRetrieve 126 | console.log(result); 127 | ``` 128 | 129 | ## 16: Tìm kiếm nhiều option v1 130 | 131 | ```javascript 132 | const searchQuery = { 133 | query: 'your_search_term', // Từ khóa tìm kiếm 134 | attributesToHighlight: ['name', 'description'], // Nổi bật các trường 135 | attributesToSnippet: ['content:10'], // Hiển thị đoạn văn bản snippet 136 | facetFilters: [['category:Electronics', 'brand:Samsung']], // Bộ lọc động 137 | aroundLatLng: '37.7749, -122.4194', // Tìm kiếm xung quanh vị trí 138 | aroundRadius: 10000, // Bán kính tìm kiếm xung quanh 139 | numericFilters: ['price >= 50', 'price <= 100'], // Bộ lọc số học 140 | queryType: 'prefixLast', // Loại truy vấn 141 | typoTolerance: 'min', // Chấp nhận ít lỗi chính tả hơn 142 | }; 143 | 144 | index 145 | .search('search_query', searchQuery) 146 | .then(({ hits }) => { 147 | console.log('Result', hits); 148 | }) 149 | .catch((err) => { 150 | console.error('Error:', err); 151 | }); 152 | ``` 153 | 154 | ## 17: Tìm kiếm nhiều option v2 155 | 156 | ```javascript 157 | const searchQuery = { 158 | // Chỉ lấy các trường cần thiết từ kết quả tìm kiếm 159 | attributesToRetrieve: ['name', 'price', 'image'], 160 | 161 | // Chỉ trả về một số lượng kết quả cụ thể 162 | hitsPerPage: 10, 163 | 164 | // Sắp xếp kết quả theo giá giảm dần 165 | sortBy: ['price:desc'], 166 | 167 | // Đánh dấu các từ khóa trong trường mô tả 168 | highlightPreTag: '', 169 | highlightPostTag: '', 170 | 171 | // Chỉ tìm kiếm trong một số trường cụ thể 172 | restrictSearchableAttributes: ['name', 'description'], 173 | 174 | // Tùy chọn tìm kiếm thông minh 175 | enableABTest: true, 176 | ruleContexts: ['mobile'], 177 | 178 | // Chỉ trả về các kết quả có chất lượng cao (Relevance Score >= 50) 179 | minRelevanceScore: 50, 180 | }; 181 | 182 | index 183 | .search('search_query', searchQuery) 184 | .then(({ hits }) => { 185 | console.log('Kết quả tìm kiếm:', hits); 186 | }) 187 | .catch((err) => { 188 | console.error('Lỗi tìm kiếm:', err); 189 | }); 190 | ``` 191 | -------------------------------------------------------------------------------- /service-search-algolia/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Service Search Algolia", 3 | "version": "0.0.1", 4 | "main": "server.js", 5 | "repository": "https://github.com/fdhhhdjd/Class_Redis_Search_Engine", 6 | "author": "fdhhhdjd ", 7 | "type": "commonjs", 8 | "license": "MIT", 9 | "scripts": { 10 | "start": "node server.js", 11 | "dev": "node --watch server.js", 12 | "build": "tsc && vite build", 13 | "preview": "vite preview", 14 | "lint": "eslint . --ext .cjs,.mjs,.js,.cts,.mts --fix --ignore-path .gitignore && echo \"Tai Dev Check Eslint ✅\"", 15 | "lint:fix": "eslint . --fix --ext .js", 16 | "format": "prettier --write src/**/*.{js}" 17 | }, 18 | "engines": { 19 | "node": ">=16.20.1", 20 | "npm": ">= 8.19.4" 21 | }, 22 | "dependencies": { 23 | "algoliasearch": "^4.22.1", 24 | "body-parser": "^1.20.2", 25 | "compression": "^1.7.4", 26 | "cors": "^2.8.5", 27 | "dotenv": "^16.3.1", 28 | "express": "^4.18.2", 29 | "express-rate-limit": "^7.1.5", 30 | "helmet": "^7.1.0", 31 | "lodash": "^4.17.21", 32 | "morgan": "^1.10.0", 33 | "uuid": "^9.0.1", 34 | "winston": "^3.11.0" 35 | }, 36 | "devDependencies": { 37 | "eslint": "^8.56.0", 38 | "eslint-config-prettier": "^9.0.0", 39 | "eslint-import-resolver-alias": "^1.1.2", 40 | "eslint-plugin-import": "^2.29.1", 41 | "eslint-plugin-prettier": "^5.0.1", 42 | "eslint-plugin-promise": "^6.1.1", 43 | "eslint-plugin-security": "^2.1.0", 44 | "prettier": "^3.0.3" 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /service-search-algolia/server.js: -------------------------------------------------------------------------------- 1 | //* IMPORT 2 | const app = require('./src/app'); 3 | const { 4 | app: { port: PORT }, 5 | } = require('./src/common/configs/app.config'); 6 | 7 | const server = app.listen(PORT, () => { 8 | console.info(`Api backend start with http://localhost:${PORT}`); 9 | }); 10 | 11 | process.on('SIGINT', () => { 12 | server.close(() => console.info('Exit Server Express')); 13 | }); 14 | -------------------------------------------------------------------------------- /service-search-algolia/src/app.js: -------------------------------------------------------------------------------- 1 | //* LIB 2 | const compression = require('compression'); 3 | const cors = require('cors'); 4 | const express = require('express'); 5 | const { default: helmet } = require('helmet'); 6 | const morgan = require('morgan'); 7 | 8 | const app = express(); 9 | require('dotenv').config(); 10 | 11 | //* IMPORT 12 | const { 13 | app: { morgan: morganConfig, node }, 14 | } = require('./common/configs/app.config'); 15 | const { NODE_ENV, LIMIT } = require('./common/constants'); 16 | const { StatusCodes, ReasonPhrases } = require('./common/utils/httpStatusCode'); 17 | const RateLimitIp = require('./middlewares/rateLimitMiddleware'); 18 | 19 | app.use(morgan(morganConfig)); 20 | app.enable(); 21 | app.use(cors()); 22 | app.use(helmet()); 23 | app.use(compression()); 24 | app.use( 25 | express.json({ 26 | limit: LIMIT._5_MB, 27 | }), 28 | ); 29 | app.use(RateLimitIp); 30 | app.use( 31 | express.urlencoded({ 32 | extended: true, 33 | }), 34 | ); 35 | 36 | //* V1 37 | app.use('/api', require('./app/v1/routes')); 38 | 39 | //* Error 40 | app.use((_, __, next) => { 41 | const ErrorCode = new Error(StatusCodes.NOT_FOUND); 42 | ErrorCode.status = StatusCodes.NOT_FOUND; 43 | return next(ErrorCode); 44 | }); 45 | 46 | app.use((error, _, res, __) => { 47 | const statusCode = error.status || StatusCodes.INTERNAL_SERVER_ERROR; 48 | const message = error.message || ReasonPhrases.INTERNAL_SERVER_ERROR; 49 | 50 | const response = { 51 | message, 52 | status: statusCode, 53 | }; 54 | 55 | const checkNodeApp = node === NODE_ENV.DEV; 56 | if (checkNodeApp) { 57 | Object.assign(response, { stack: error.stack }); 58 | } 59 | 60 | return res.status(statusCode).json(response); 61 | }); 62 | 63 | module.exports = app; 64 | -------------------------------------------------------------------------------- /service-search-algolia/src/app/v1/controllers/car.controller.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* IMPORT 4 | const { SuccessResponse, Created } = require('../../../cores/success.response'); 5 | const CarService = require('../services/car.service'); 6 | 7 | class CarControllers { 8 | async searchAll(req, res, __) { 9 | const query = req.query.q; 10 | new SuccessResponse({ 11 | message: 'Search All key success.', 12 | metadata: await CarService.searchAll({ query }), 13 | }).send(res); 14 | } 15 | 16 | async getAllCars(_, res, __) { 17 | new SuccessResponse({ 18 | message: 'Get All Cars success.', 19 | metadata: await CarService.getAllCars(), 20 | }).send(res); 21 | } 22 | 23 | async searchAllIndex(req, res, __) { 24 | const { idx, query } = req.body; 25 | 26 | new SuccessResponse({ 27 | message: `Query ${idx} success.`, 28 | metadata: await CarService.searchAllIndex({ idx, query }), 29 | }).send(res); 30 | } 31 | 32 | async getDetailId(req, res, __) { 33 | const id = req.params.id; 34 | new SuccessResponse({ 35 | message: 'Get detail todo success.', 36 | metadata: await CarService.getDetailId({ id }), 37 | }).send(res); 38 | } 39 | 40 | async create(req, res, __) { 41 | new Created({ 42 | message: 'Create todo success.', 43 | metadata: await CarService.create(req.body), 44 | }).send(res); 45 | } 46 | 47 | async update(req, res, __) { 48 | new SuccessResponse({ 49 | message: 'Update todo success', 50 | metadata: await CarService.update(req.body), 51 | }).send(res); 52 | } 53 | 54 | async delete(req, res, __) { 55 | const id = req.params.id; 56 | 57 | new SuccessResponse({ 58 | message: 'Delete todo success.', 59 | metadata: await CarService.delete({ id }), 60 | }).send(res); 61 | } 62 | } 63 | 64 | module.exports = new CarControllers(); 65 | -------------------------------------------------------------------------------- /service-search-algolia/src/app/v1/models/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fdhhhdjd/Class_Search_Engine/16d30bafdf33febce9556353981efc86c488899d/service-search-algolia/src/app/v1/models/.gitkeep -------------------------------------------------------------------------------- /service-search-algolia/src/app/v1/routes/cars/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* LIB 4 | const express = require('express'); 5 | const router = express.Router(); 6 | 7 | //* IMPORT 8 | const { asyncHandler } = require('../../../../common/helpers/asyncHandler'); 9 | const CarControllers = require('../../controllers/car.controller'); 10 | 11 | // -- CURD 12 | // Todo 1. Get All 13 | router.get('/get/all', asyncHandler(CarControllers.getAllCars)); 14 | 15 | // Todo 2. Get Detail 16 | router.get('/get/:id', asyncHandler(CarControllers.getDetailId)); 17 | 18 | // Todo 3. Create 19 | router.post('/create', asyncHandler(CarControllers.create)); 20 | 21 | // Todo 4. Update 22 | router.patch('/update', asyncHandler(CarControllers.update)); 23 | 24 | // Todo 5. Delete 25 | router.delete('/delete/:id', asyncHandler(CarControllers.delete)); 26 | 27 | // -- SEARCH 28 | router.get('/search/all', asyncHandler(CarControllers.searchAll)); 29 | 30 | module.exports = router; 31 | -------------------------------------------------------------------------------- /service-search-algolia/src/app/v1/routes/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* LIB 4 | const express = require('express'); 5 | 6 | //* IMPORT 7 | const { StatusCodes, ReasonPhrases } = require('../../../common/utils/httpStatusCode'); 8 | 9 | const router = express.Router(); 10 | 11 | // Todo: 1. Cars 12 | router.use('/v1/cars', require('./cars')); 13 | 14 | router.get('/v1', async (_, res, __) => { 15 | const healthCheck = { 16 | uptime: process.uptime(), 17 | message: ReasonPhrases.OK, 18 | timestamp: Date.now(), 19 | }; 20 | return res.status(StatusCodes.OK).json(healthCheck); 21 | }); 22 | 23 | module.exports = router; 24 | -------------------------------------------------------------------------------- /service-search-algolia/src/app/v1/services/car.service.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable security/detect-object-injection */ 2 | 'use strict'; 3 | 4 | //* IMPORT 5 | const index = require('../../../dbs'); 6 | 7 | class CarService { 8 | static async searchAll({ query }) { 9 | const searchQuery = { 10 | attributesToHighlight: ['make', 'model'], 11 | attributesToSnippet: ['content:2'], 12 | attributesToRetrieve: ['make', 'model'], 13 | typoTolerance: 'min', 14 | }; 15 | 16 | const result = await index.search(query, searchQuery); 17 | return result; 18 | } 19 | 20 | static async getAllCars() { 21 | const objects = []; 22 | await index.browseObjects({ 23 | query: '', 24 | batch: (response) => { 25 | objects.push(...response); 26 | }, 27 | }); 28 | 29 | return objects; 30 | } 31 | 32 | static async getDetailId({ id }) { 33 | const result = await index.getObject(id); 34 | return result; 35 | } 36 | 37 | static async create({ make, model, image, description }) { 38 | const result = await index 39 | .saveObjects([{ make, model, image, description }], { autoGenerateObjectIDIfNotExist: true }) 40 | .then((result) => result) 41 | .catch((err) => err); 42 | 43 | return result; 44 | } 45 | 46 | static async update({ id, make, model, image, description }) { 47 | const updatedObject = { 48 | objectID: id, 49 | make, 50 | model, 51 | image, 52 | description, 53 | }; 54 | 55 | return index 56 | .saveObject(updatedObject) 57 | .then(({ objectID }) => `Object with objectID ${objectID} updated successfully.`) 58 | .catch((err) => err); 59 | } 60 | 61 | static async delete({ id }) { 62 | const objectIDToDelete = id; 63 | 64 | return index 65 | .deleteObject(objectIDToDelete) 66 | .then(() => `Object with objectID ${objectIDToDelete} deleted successfully.`) 67 | .catch((err) => { 68 | return err; 69 | }); 70 | } 71 | } 72 | 73 | module.exports = CarService; 74 | -------------------------------------------------------------------------------- /service-search-algolia/src/common/configs/app.config.js: -------------------------------------------------------------------------------- 1 | const DEV = { 2 | app: { 3 | port: process.env.PORT || 5000, 4 | morgan: process.env.MORGAN || 'dev', 5 | node: process.env.NODE_ENV, 6 | web_server: process.env.WEB_SERVER, 7 | }, 8 | }; 9 | const PRO = { 10 | app: { 11 | port: process.env.PORT || 5000, 12 | morgan: process.env.MORGAN || 'combined', 13 | node: process.env.NODE_ENV, 14 | web_server: process.env.WEB_SERVER, 15 | }, 16 | }; 17 | const config = { DEV, PRO }; 18 | 19 | const env = process.env.NODE_ENV || 'DEV'; 20 | 21 | module.exports = config[env]; 22 | -------------------------------------------------------------------------------- /service-search-algolia/src/common/constants/index.js: -------------------------------------------------------------------------------- 1 | const NODE_ENV = { 2 | DEV: 'DEV', 3 | PRO: 'PRO', 4 | }; 5 | 6 | const ENABLE_IP = 'trust proxy'; 7 | 8 | const LIMIT = { 9 | _5_MB: '5mb', 10 | }; 11 | 12 | const REQUEST = { 13 | _WINDOW_MS: 1 * 60 * 1000, 14 | _MAX: 100, 15 | }; 16 | 17 | module.exports = { 18 | NODE_ENV, 19 | ENABLE_IP, 20 | LIMIT, 21 | REQUEST, 22 | }; 23 | -------------------------------------------------------------------------------- /service-search-algolia/src/common/helpers/asyncHandler.js: -------------------------------------------------------------------------------- 1 | const asyncHandler = (fn) => { 2 | return (req, res, next) => { 3 | Promise.resolve(fn(req, res, next)).catch((error) => { 4 | next(error); 5 | }); 6 | }; 7 | }; 8 | 9 | module.exports = { asyncHandler }; 10 | -------------------------------------------------------------------------------- /service-search-algolia/src/common/helpers/validate/index.js: -------------------------------------------------------------------------------- 1 | //* IMPORT 2 | const { BadRequestRequestError } = require('../../../cores/error.response.js'); 3 | 4 | class ValidationUtils { 5 | static validateField({ value, fieldName, validators }) { 6 | const invalidValidator = validators.find(({ validate }) => !validate(value)); 7 | if (invalidValidator) { 8 | const { message } = invalidValidator; 9 | throw new BadRequestRequestError({ 10 | message: `${fieldName} ${message}`, 11 | }); 12 | } 13 | } 14 | } 15 | 16 | module.exports = ValidationUtils; 17 | -------------------------------------------------------------------------------- /service-search-algolia/src/common/helpers/validate/todo.validate.js: -------------------------------------------------------------------------------- 1 | //* IMPORT 2 | const ValidationUtils = require('.'); 3 | 4 | class TodoBuilder { 5 | build() { 6 | throw new Error('Method not implemented.'); 7 | } 8 | 9 | constructor() { 10 | this.id = ''; 11 | this.text = ''; 12 | } 13 | 14 | setId(id) { 15 | this.id = id; 16 | return this; 17 | } 18 | 19 | setText(text) { 20 | this.text = text; 21 | return this; 22 | } 23 | 24 | validateEmptyId(id) { 25 | return id; 26 | } 27 | 28 | validateEmptyText(text) { 29 | return text; 30 | } 31 | } 32 | 33 | class RDBuilder extends TodoBuilder { 34 | build() { 35 | ValidationUtils.validateField({ 36 | value: this.id, 37 | fieldName: 'Id', 38 | validators: [ 39 | { 40 | validate: this.validateEmptyId, 41 | message: 'is invalid', 42 | }, 43 | ], 44 | }); 45 | } 46 | } 47 | 48 | class CUBuilder extends TodoBuilder { 49 | build() { 50 | ValidationUtils.validateField({ 51 | value: this.id, 52 | fieldName: 'Id', 53 | validators: [ 54 | { 55 | validate: this.validateEmptyId, 56 | message: 'is invalid', 57 | }, 58 | ], 59 | }); 60 | ValidationUtils.validateField({ 61 | value: this.text, 62 | fieldName: 'Text', 63 | validators: [ 64 | { 65 | validate: this.validateEmptyText, 66 | message: 'is empty', 67 | }, 68 | ], 69 | }); 70 | } 71 | } 72 | 73 | const RDInputBuilder = new RDBuilder(); 74 | const CUInputBuilder = new CUBuilder(); 75 | 76 | module.exports = { RDInputBuilder, CUInputBuilder }; 77 | -------------------------------------------------------------------------------- /service-search-algolia/src/common/index/cart.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | NameIndex: 'cart:search', 3 | }; 4 | -------------------------------------------------------------------------------- /service-search-algolia/src/common/utils/httpStatusCode.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | StatusCodes: require('../utils/statusCodes'), 3 | ReasonPhrases: require('../utils/reasonPhrases'), 4 | }; 5 | -------------------------------------------------------------------------------- /service-search-algolia/src/common/utils/statusCodes.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable max-len */ 2 | module.exports = { 3 | /** 4 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.1 5 | * 6 | * 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. 7 | */ 8 | CONTINUE: 100, 9 | /** 10 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.2 11 | * 12 | * This code is sent in response to an Upgrade request header by the client, and indicates the protocol the server is switching too. 13 | */ 14 | SWITCHING_PROTOCOLS: 101, 15 | /** 16 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.1 17 | * 18 | * This code indicates that the server has received and is processing the request, but no response is available yet. 19 | */ 20 | PROCESSING: 102, 21 | /** 22 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.1 23 | * 24 | * The request has succeeded. The meaning of a success varies depending on the HTTP method: 25 | * GET: The resource has been fetched and is transmitted in the message body. 26 | * HEAD: The entity headers are in the message body. 27 | * POST: The resource describing the result of the action is transmitted in the message body. 28 | * TRACE: The message body contains the request message as received by the server 29 | */ 30 | OK: 200, 31 | /** 32 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.2 33 | * 34 | * 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. 35 | */ 36 | CREATED: 201, 37 | /** 38 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.3 39 | * 40 | * 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. 41 | */ 42 | ACCEPTED: 202, 43 | /** 44 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.4 45 | * 46 | * 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. 47 | */ 48 | NON_AUTHORITATIVE_INFORMATION: 203, 49 | /** 50 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.5 51 | * 52 | * 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. 53 | */ 54 | NO_CONTENT: 204, 55 | /** 56 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.6 57 | * 58 | * This response code is sent after accomplishing request to tell user agent reset document view which sent this request. 59 | */ 60 | RESET_CONTENT: 205, 61 | /** 62 | * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.1 63 | * 64 | * This response code is used because of range header sent by the client to separate download into multiple streams. 65 | */ 66 | PARTIAL_CONTENT: 206, 67 | /** 68 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.2 69 | * 70 | * A Multi-Status response conveys information about multiple resources in situations where multiple status codes might be appropriate. 71 | */ 72 | MULTI_STATUS: 207, 73 | /** 74 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.1 75 | * 76 | * 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. 77 | */ 78 | MULTIPLE_CHOICES: 300, 79 | /** 80 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.2 81 | * 82 | * This response code means that URI of requested resource has been changed. Probably, new URI would be given in the response. 83 | */ 84 | MOVED_PERMANENTLY: 301, 85 | /** 86 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.3 87 | * 88 | * 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. 89 | */ 90 | MOVED_TEMPORARILY: 302, 91 | /** 92 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.4 93 | * 94 | * Server sent this response to directing client to get requested resource to another URI with an GET request. 95 | */ 96 | SEE_OTHER: 303, 97 | /** 98 | * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.1 99 | * 100 | * 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. 101 | */ 102 | NOT_MODIFIED: 304, 103 | /** 104 | * @deprecated 105 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.6 106 | * 107 | * 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. 108 | */ 109 | USE_PROXY: 305, 110 | /** 111 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.7 112 | * 113 | * 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. 114 | */ 115 | TEMPORARY_REDIRECT: 307, 116 | /** 117 | * Official Documentation @ https://tools.ietf.org/html/rfc7538#section-3 118 | * 119 | * 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. 120 | */ 121 | PERMANENT_REDIRECT: 308, 122 | /** 123 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.1 124 | * 125 | * This response means that server could not understand the request due to invalid syntax. 126 | */ 127 | BAD_REQUEST: 400, 128 | /** 129 | * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.1 130 | * 131 | * Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response. 132 | */ 133 | UNAUTHORIZED: 401, 134 | /** 135 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.2 136 | * 137 | * 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. 138 | */ 139 | PAYMENT_REQUIRED: 402, 140 | /** 141 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.3 142 | * 143 | * 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. 144 | */ 145 | FORBIDDEN: 403, 146 | /** 147 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.4 148 | * 149 | * 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. 150 | */ 151 | NOT_FOUND: 404, 152 | /** 153 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.5 154 | * 155 | * 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. 156 | */ 157 | METHOD_NOT_ALLOWED: 405, 158 | /** 159 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.6 160 | * 161 | * 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. 162 | */ 163 | NOT_ACCEPTABLE: 406, 164 | /** 165 | * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.2 166 | * 167 | * This is similar to 401 but authentication is needed to be done by a proxy. 168 | */ 169 | PROXY_AUTHENTICATION_REQUIRED: 407, 170 | /** 171 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.7 172 | * 173 | * 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. 174 | */ 175 | REQUEST_TIMEOUT: 408, 176 | /** 177 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.8 178 | * 179 | * This response is sent when a request conflicts with the current state of the server. 180 | */ 181 | CONFLICT: 409, 182 | /** 183 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.9 184 | * 185 | * 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. 186 | */ 187 | GONE: 410, 188 | /** 189 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.10 190 | * 191 | * The server rejected the request because the Content-Length header field is not defined and the server requires it. 192 | */ 193 | LENGTH_REQUIRED: 411, 194 | /** 195 | * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.2 196 | * 197 | * The client has indicated preconditions in its headers which the server does not meet. 198 | */ 199 | PRECONDITION_FAILED: 412, 200 | /** 201 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.11 202 | * 203 | * Request entity is larger than limits defined by server; the server might close the connection or return an Retry-After header field. 204 | */ 205 | REQUEST_TOO_LONG: 413, 206 | /** 207 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.12 208 | * 209 | * The URI requested by the client is longer than the server is willing to interpret. 210 | */ 211 | REQUEST_URI_TOO_LONG: 414, 212 | /** 213 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.13 214 | * 215 | * The media format of the requested data is not supported by the server, so the server is rejecting the request. 216 | */ 217 | UNSUPPORTED_MEDIA_TYPE: 415, 218 | /** 219 | * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.4 220 | * 221 | * 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. 222 | */ 223 | REQUESTED_RANGE_NOT_SATISFIABLE: 416, 224 | /** 225 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.14 226 | * 227 | * This response code means the expectation indicated by the Expect request header field can't be met by the server. 228 | */ 229 | EXPECTATION_FAILED: 417, 230 | /** 231 | * Official Documentation @ https://tools.ietf.org/html/rfc2324#section-2.3.2 232 | * 233 | * 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. 234 | */ 235 | IM_A_TEAPOT: 418, 236 | /** 237 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6 238 | * 239 | * 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. 240 | */ 241 | INSUFFICIENT_SPACE_ON_RESOURCE: 419, 242 | /** 243 | * @deprecated 244 | * Official Documentation @ https://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt 245 | * 246 | * A deprecated response used by the Spring Framework when a method has failed. 247 | */ 248 | METHOD_FAILURE: 420, 249 | /** 250 | * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7540#section-9.1.2 251 | * 252 | * 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. 253 | */ 254 | MISDIRECTED_REQUEST: 421, 255 | /** 256 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.3 257 | * 258 | * The request was well-formed but was unable to be followed due to semantic errors. 259 | */ 260 | UNPROCESSABLE_ENTITY: 422, 261 | /** 262 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.4 263 | * 264 | * The resource that is being accessed is locked. 265 | */ 266 | LOCKED: 423, 267 | /** 268 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.5 269 | * 270 | * The request failed due to failure of a previous request. 271 | */ 272 | FAILED_DEPENDENCY: 424, 273 | /** 274 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-3 275 | * 276 | * 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. 277 | */ 278 | PRECONDITION_REQUIRED: 428, 279 | /** 280 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-4 281 | * 282 | * The user has sent too many requests in a given amount of time ("rate limiting"). 283 | */ 284 | TOO_MANY_REQUESTS: 429, 285 | /** 286 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-5 287 | * 288 | * 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. 289 | */ 290 | REQUEST_HEADER_FIELDS_TOO_LARGE: 431, 291 | /** 292 | * Official Documentation @ https://tools.ietf.org/html/rfc7725 293 | * 294 | * The user-agent requested a resource that cannot legally be provided, such as a web page censored by a government. 295 | */ 296 | UNAVAILABLE_FOR_LEGAL_REASONS: 451, 297 | /** 298 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.1 299 | * 300 | * The server encountered an unexpected condition that prevented it from fulfilling the request. 301 | */ 302 | INTERNAL_SERVER_ERROR: 500, 303 | /** 304 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.2 305 | * 306 | * 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. 307 | */ 308 | NOT_IMPLEMENTED: 501, 309 | /** 310 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.3 311 | * 312 | * 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. 313 | */ 314 | BAD_GATEWAY: 502, 315 | /** 316 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.4 317 | * 318 | * 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. 319 | */ 320 | SERVICE_UNAVAILABLE: 503, 321 | /** 322 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.5 323 | * 324 | * This error response is given when the server is acting as a gateway and cannot get a response in time. 325 | */ 326 | GATEWAY_TIMEOUT: 504, 327 | /** 328 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.6 329 | * 330 | * The HTTP version used in the request is not supported by the server. 331 | */ 332 | HTTP_VERSION_NOT_SUPPORTED: 505, 333 | /** 334 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6 335 | * 336 | * 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. 337 | */ 338 | INSUFFICIENT_STORAGE: 507, 339 | /** 340 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-6 341 | * 342 | * The 511 status code indicates that the client needs to authenticate to gain network access. 343 | */ 344 | NETWORK_AUTHENTICATION_REQUIRED: 511, 345 | }; 346 | -------------------------------------------------------------------------------- /service-search-algolia/src/cores/error.response.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* IMPORT 4 | const { StatusCodes, ReasonPhrases } = require('../common/utils/httpStatusCode'); 5 | const logger = require('../loggers/winston.log'); 6 | class ErrorResponse extends Error { 7 | constructor(message, status) { 8 | super(message); 9 | this.status = status; 10 | 11 | // Log error 12 | logger.error(`${this.status} = ${this.message}`); 13 | } 14 | } 15 | class BadRequestRequestError extends ErrorResponse { 16 | constructor(message = ReasonPhrases.BAD_REQUEST, statusCode = StatusCodes.BAD_REQUEST) { 17 | super(message, statusCode); 18 | } 19 | } 20 | 21 | class NotFoundError extends ErrorResponse { 22 | constructor(message = ReasonPhrases.NOT_FOUND, statusCode = StatusCodes.NOT_FOUND) { 23 | super(message, statusCode); 24 | } 25 | } 26 | class InternalServerError extends ErrorResponse { 27 | constructor(message = ReasonPhrases.INTERNAL_SERVER_ERROR, statusCode = StatusCodes.INTERNAL_SERVER_ERROR) { 28 | super(message, statusCode); 29 | } 30 | } 31 | module.exports = { 32 | BadRequestRequestError, 33 | InternalServerError, 34 | NotFoundError, 35 | }; 36 | -------------------------------------------------------------------------------- /service-search-algolia/src/cores/success.response.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* IMPORT 4 | const { StatusCodes, ReasonPhrases } = require('../common/utils/httpStatusCode'); 5 | 6 | class SuccessResponse { 7 | constructor({ message, statusCode = StatusCodes.OK, reasonStatusCode = ReasonPhrases.OK, metadata = {} }) { 8 | this.message = !message ? reasonStatusCode : message; 9 | this.status = statusCode; 10 | this.metadata = metadata; 11 | } 12 | 13 | send(res, _ = {}) { 14 | return res.status(this.status).json(this); 15 | } 16 | } 17 | 18 | class Ok extends SuccessResponse { 19 | constructor({ message, metadata }) { 20 | super({ message, metadata }); 21 | } 22 | } 23 | 24 | class Created extends SuccessResponse { 25 | constructor({ 26 | option = {}, 27 | message, 28 | statusCode = StatusCodes.CREATED, 29 | reasonStatusCode = ReasonPhrases.CREATED, 30 | metadata = {}, 31 | }) { 32 | super({ message, statusCode, reasonStatusCode, metadata }); 33 | this.option = option; 34 | } 35 | } 36 | module.exports = { 37 | Ok, 38 | Created, 39 | SuccessResponse, 40 | }; 41 | -------------------------------------------------------------------------------- /service-search-algolia/src/dbs/index.js: -------------------------------------------------------------------------------- 1 | //* LIB 2 | const algoliasearch = require('algoliasearch'); 3 | 4 | //* IMPORT 5 | const { NameIndex } = require('../common/index/cart'); 6 | 7 | const client = algoliasearch(process.env.APP_ID, process.env.ADMIN_API_KEY); 8 | 9 | const index = client.initIndex(NameIndex); 10 | 11 | module.exports = index; 12 | -------------------------------------------------------------------------------- /service-search-algolia/src/loggers/winston.log.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* LIB 4 | const path = require('path'); 5 | const winston = require('winston'); 6 | 7 | const { combine, timestamp, align, printf } = winston.format; 8 | const logsDirectory = path.join(__dirname, '../logs'); // Use an absolute path 9 | 10 | const logger = winston.createLogger({ 11 | level: process.env.LOG_LEVEL || 'debug', 12 | format: combine( 13 | timestamp({ 14 | format: 'YYYY-MM-DD hh:mm:ss.SSS A', 15 | }), 16 | align(), 17 | printf((info) => `[${info.timestamp}] ${info.level.toUpperCase()}: ${info.message}`), 18 | ), 19 | transports: [ 20 | new winston.transports.Console(), 21 | new winston.transports.File({ dirname: logsDirectory, filename: 'test.log' }), 22 | ], 23 | }); 24 | 25 | module.exports = logger; 26 | -------------------------------------------------------------------------------- /service-search-algolia/src/middlewares/rateLimitMiddleware.js: -------------------------------------------------------------------------------- 1 | //* LIB 2 | const rateLimit = require('express-rate-limit'); 3 | 4 | //* IMPORT 5 | const { REQUEST } = require('../common/constants'); 6 | const { ReasonPhrases, StatusCodes } = require('../common/utils/httpStatusCode'); 7 | 8 | module.exports = rateLimit({ 9 | windowMs: REQUEST._WINDOW_MS, 10 | max: REQUEST._MAX, 11 | message: { 12 | status: StatusCodes.TOO_MANY_REQUESTS, 13 | message: ReasonPhrases.TOO_MANY_REQUESTS, 14 | }, 15 | standardHeaders: true, 16 | }); 17 | -------------------------------------------------------------------------------- /service-search-elastic/.dockerignore: -------------------------------------------------------------------------------- 1 | .git 2 | .github 3 | .vscode 4 | coverage 5 | docs 6 | mock-config 7 | *.sh 8 | .editorconfig 9 | .prettierignore 10 | config.yaml 11 | jest* 12 | npm-debug.log 13 | yarn-error.log 14 | **/*.test.ts 15 | src/test 16 | **/*.pem 17 | 18 | # Data 19 | db_data 20 | minio_data 21 | 22 | # Git 23 | .git 24 | .gitignore 25 | 26 | # Docker 27 | Dockerfile* 28 | docker-compose* 29 | 30 | # NPM dependencies 31 | node_modules 32 | 33 | 34 | # Eslint 35 | .eslintignore 36 | .eslintrc.js 37 | 38 | #prettieri 39 | .prettierignore 40 | .prettierrc 41 | 42 | #unittest 43 | test 44 | *.md 45 | addons 46 | commitlint.config.js 47 | makefile 48 | setup 49 | script -------------------------------------------------------------------------------- /service-search-elastic/.env.example: -------------------------------------------------------------------------------- 1 | # APP NODE 2 | NODE_ENV='' 3 | 4 | # MORGAN 5 | MORGAN='' 6 | 7 | # PORT APP 8 | PORT='' 9 | 10 | # Algolia 11 | ADMIN_API_KEY= 12 | APP_ID= 13 | 14 | 15 | ELASTIC_SEARCH_PORT=9200 16 | ELASTIC_SEARCH_HOST=ELASTIC_SEARCH_HOST 17 | KIBANA_PORT=5601 18 | ELASTIC_USERNAME=elastic 19 | ELASTIC_PASSWORD=ELASTIC_PASSWORD 20 | ELASTIC_TOKEN=ELASTIC_TOKEN -------------------------------------------------------------------------------- /service-search-elastic/.eslintignore: -------------------------------------------------------------------------------- 1 | build/_.js 2 | config/_.js 3 | [Bb]uild* 4 | [Dd]ist* 5 | [Bb]in\* 6 | package-lock.json 7 | docker-compose.yml 8 | 9 | node_modules/ 10 | public/ 11 | build/ 12 | .github/ 13 | *.css 14 | *.svg 15 | *.config.js -------------------------------------------------------------------------------- /service-search-elastic/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | node: true, 4 | commonjs: false, 5 | es2021: true, 6 | }, 7 | 8 | extends: ['eslint:recommended', 'plugin:prettier/recommended', 'plugin:security/recommended-legacy'], 9 | plugins: ['prettier', 'import', 'security', 'promise'], 10 | parserOptions: { 11 | ecmaVersion: 2021, 12 | sourceType: 'module', 13 | }, 14 | rules: { 15 | 'prettier/prettier': ['error'], 16 | quotes: ['error', 'single'], 17 | semi: ['error', 'always'], 18 | 'import/order': [ 19 | 'error', 20 | { 21 | groups: [['builtin', 'external'], 'internal', ['sibling', 'parent'], 'index', 'unknown'], 22 | 'newlines-between': 'always', 23 | alphabetize: { 24 | order: 'asc', 25 | caseInsensitive: true, 26 | }, 27 | pathGroups: [ 28 | { 29 | pattern: '@/**', 30 | group: 'internal', 31 | position: 'after', 32 | }, 33 | ], 34 | pathGroupsExcludedImportTypes: ['builtin'], 35 | }, 36 | ], 37 | 38 | 'no-console': [ 39 | 'error', 40 | { 41 | allow: ['info', 'warn', 'error', 'time', 'timeEnd'], 42 | }, 43 | ], 44 | 'prefer-const': 'warn', 45 | 'max-len': ['error', 200], 46 | 'array-bracket-newline': 'warn', 47 | 'consistent-return': 'error', 48 | eqeqeq: 'error', 49 | 'no-unused-expressions': ['error', { allowTernary: true }], 50 | 'no-unused-vars': [ 51 | 'error', 52 | { 53 | varsIgnorePattern: '^_', 54 | argsIgnorePattern: '^_', 55 | vars: 'all', 56 | args: 'after-used', 57 | ignoreRestSiblings: false, 58 | }, 59 | ], 60 | 61 | 'operator-linebreak': [ 62 | 'error', 63 | 'after', 64 | { overrides: { '?': 'before', ':': 'before', '&&': 'before', '||': 'before' } }, 65 | ], 66 | 67 | 'linebreak-style': ['error', process.platform === 'win64' && 'win32' ? 'windows' : 'unix'], 68 | 69 | 'no-plusplus': ['error', { allowForLoopAfterthoughts: true }], 70 | 71 | 'arrow-parens': ['error', 'always'], 72 | 73 | 'lines-between-class-members': ['error', 'always', { exceptAfterSingleLine: true }], 74 | 75 | 'no-extra-parens': 'error', 76 | 'no-return-await': 'error', 77 | 'no-duplicate-imports': 'error', 78 | 79 | 'no-undef': 'off', 80 | 81 | 'security/detect-non-literal-fs-filename': 'error', 82 | 'security/detect-object-injection': 'error', 83 | 84 | 'promise/always-return': 'error', 85 | 'promise/no-return-wrap': 'error', 86 | 'promise/param-names': 'error', 87 | 'promise/catch-or-return': 'error', 88 | 'promise/no-native': 'off', 89 | 'promise/no-nesting': 'warn', 90 | 'promise/no-promise-in-callback': 'warn', 91 | 'promise/no-callback-in-promise': 'warn', 92 | 'promise/avoid-new': 'warn', 93 | 'promise/no-new-statics': 'error', 94 | 'promise/no-return-in-finally': 'warn', 95 | 'promise/valid-params': 'warn', 96 | }, 97 | }; 98 | -------------------------------------------------------------------------------- /service-search-elastic/.gitattributes: -------------------------------------------------------------------------------- 1 | # Handle line endings automatically for files detected as text 2 | # and leave all files detected as binary untouched. 3 | * text=false 4 | 5 | # 6 | # The above will handle all files NOT found below 7 | # 8 | # These files are text and should be normalized (Convert crlf => lf) 9 | *.df eol=lf 10 | *.html eol=lf 11 | *.java eol=lf 12 | *.json eol=lf 13 | *.jsp eol=lf 14 | *.jspf eol=lf 15 | *.jspx eol=lf 16 | *.properties eol=lf 17 | *.sh eol=lf 18 | *.tld eol=lf 19 | *.ts eol=lf 20 | *.txt eol=lf 21 | *.tag eol=lf 22 | *.tagx eol=lf 23 | *.xml eol=lf 24 | *.yml eol=lf 25 | *.env eol=lf 26 | 27 | .gitignore eol=lf 28 | .gitattributes eol=lf 29 | .eslintignore eol=lf 30 | .prettierignore eol=lf 31 | .js eol=lf 32 | .css eol=lf 33 | .htm eol=lf 34 | 35 | 36 | 37 | # These files are binary and should be left untouched 38 | # (binary is a macro for -text -diff) 39 | *.class binary 40 | *.dll binary 41 | *.ear binary 42 | *.gif binary 43 | *.ico binary 44 | *.jar binary 45 | *.jpg binary 46 | *.jpeg binary 47 | *.png binary 48 | *.so binary 49 | *.war binary -------------------------------------------------------------------------------- /service-search-elastic/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | *.log 3 | npm-debug.log* 4 | yarn-debug.log* 5 | yarn-error.log* 6 | pnpm-debug.log* 7 | lerna-debug.log* 8 | 9 | dist-ssr 10 | *.local 11 | 12 | # Editor directories and files 13 | # .vscode/* 14 | !.vscode/extensions.json 15 | .idea 16 | .DS_Store 17 | *.suo 18 | *.ntvs* 19 | *.njsproj 20 | *.sln 21 | *.sw? 22 | 23 | package-lock.json 24 | yarn.lock 25 | .env 26 | 27 | 28 | node_modules 29 | .env 30 | redis-master 31 | redis-slave 32 | docker-entrypoint-initdb.d 33 | setup 34 | file 35 | script/log_script_redis_date.txt 36 | script/.env 37 | test/jest/.env 38 | 39 | redis -------------------------------------------------------------------------------- /service-search-elastic/.prettierignore: -------------------------------------------------------------------------------- 1 | package.json 2 | package-lock.json 3 | public 4 | node_modules 5 | build 6 | .github 7 | -------------------------------------------------------------------------------- /service-search-elastic/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "arrowParens": "always", 3 | "bracketSameLine": false, 4 | "bracketSpacing": true, 5 | "embeddedLanguageFormatting": "auto", 6 | "insertPragma": false, 7 | "jsxSingleQuote": false, 8 | "printWidth": 120, 9 | "proseWrap": "preserve", 10 | "quoteProps": "as-needed", 11 | "requirePragma": false, 12 | "semi": true, 13 | "singleQuote": true, 14 | "tabWidth": 4, 15 | "trailingComma": "all", 16 | "useTabs": false, 17 | "vueIndentScriptAndStyle": false, 18 | "endOfLine": "lf" 19 | } 20 | -------------------------------------------------------------------------------- /service-search-elastic/.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "editor.formatOnSave": true 3 | } 4 | -------------------------------------------------------------------------------- /service-search-elastic/ELASTIC.md: -------------------------------------------------------------------------------- 1 | # This is command to create an index 2 | ```cmd 3 | PUT product_info 4 | ``` 5 | 6 | # This is creating a document 7 | ```cmd 8 | POST product_info/_doc 9 | { 10 | "@timestamp": "2024-05-08", 11 | "fullname": "Nguyen Vo Tien", 12 | "url_profile": "https://tien.com" 13 | } 14 | ``` 15 | 16 | # This is creating a document with a specific ID 17 | ```cmd 18 | POST product_info/_doc/0001 19 | { 20 | "@timestamp": "2021-01-08", 21 | "fullname": "Nguyen Van D", 22 | "url_profile": "https://d.com" 23 | } 24 | ``` 25 | 26 | # This is creating a document with a specific ID (alternative method) 27 | ```cmd 28 | PUT product_info/_doc/0002 29 | { 30 | "@timestamp": "2021-01-08", 31 | "fullname": "Nguyen Vo Tien", 32 | "url_profile": "https://tien.com" 33 | } 34 | ``` 35 | 36 | # Adding multiple documents using bulk API 37 | ```cmd 38 | POST _bulk 39 | { "index": { "_index": "product_info" }} 40 | { "@timestamp": "2024-05-08", "fullname": "Nguyen Van A", "url_profile": "https://vanA.com" } 41 | { "index": { "_index": "product_info" }} 42 | { "@timestamp": "2020-06-23", "fullname": "Nguyen Van B", "url_profile": "https://vanB.com" } 43 | { "index": { "_index": "product_info" }} 44 | { "@timestamp": "2021-02-23", "fullname": "Nguyen Van C", "url_profile": "https://vanC.com" } 45 | ``` 46 | 47 | # Check index 48 | ```cmd 49 | GET _cat/indices 50 | ``` 51 | 52 | # Retrieve all documents 53 | ```cmd 54 | GET product_info/_search 55 | ``` 56 | 57 | # Delete a document 58 | ```cmd 59 | DELETE product_info/_doc/7mPWWI8Bp27zrf6omSeA 60 | ``` 61 | 62 | # Update a document 63 | ```cmd 64 | PUT product_info/_doc/7WPWWI8Bp27zrf6omSeA 65 | { 66 | "@timestamp": "2020-02-02", 67 | "fullname": "Nguyen Van A", 68 | "url_profile": "https://a.com" 69 | } 70 | ``` 71 | 72 | # Update a single field in a document 73 | ```cmd 74 | POST /product_info/_update/6WPHWI8Bp27zrf6ojCeo 75 | { 76 | "doc": { 77 | "fullname": "Nguyen Tien Tai 1" 78 | } 79 | } 80 | ``` 81 | 82 | # Sort documents in descending order 83 | ```cmd 84 | GET product_info/_search 85 | { 86 | "query": { 87 | "match_all": {} 88 | }, 89 | "sort": [ 90 | { 91 | "@timestamp": { 92 | "order": "desc" 93 | } 94 | } 95 | ] 96 | } 97 | ``` 98 | 99 | # Retrieve a specific field from documents 100 | ```cmd 101 | GET product_info/_search 102 | { 103 | "query": { 104 | "match_all": {} 105 | }, 106 | "fields": [ 107 | "fullname" 108 | ], 109 | "_source": false, 110 | "sort": [ 111 | { 112 | "@timestamp": { 113 | "order": "desc" 114 | } 115 | } 116 | ] 117 | } 118 | ``` 119 | 120 | # Retrieve document details 121 | ```cmd 122 | GET product_info/_doc/6WPHWI8Bp27zrf6ojCeo?_source=fullname 123 | GET product_info/_doc/6WPHWI8Bp27zrf6ojCeo?filter_path=_source 124 | ``` 125 | # Retrieve multiple documents with different IDs 126 | ```cmd 127 | GET _mget 128 | { 129 | "docs": [ 130 | { 131 | "_index": "product_info", 132 | "_id": "6WPHWI8Bp27zrf6ojCeo", 133 | "_source": [ 134 | "fullname" 135 | ] 136 | }, 137 | { 138 | "_index": "product_info", 139 | "_id": "0002", 140 | "_source": [ 141 | "fullname" 142 | ] 143 | } 144 | ] 145 | } 146 | ``` 147 | 148 | # Check if a document exists 149 | ```cmd 150 | HEAD product_info/_doc/0002 151 | ``` 152 | 153 | # Get total count of documents 154 | ```cmd 155 | GET product_info/_count 156 | ``` 157 | 158 | # Search documents with a condition 159 | ```cmd 160 | GET product_info/_search 161 | { 162 | "query": { 163 | "match": { 164 | "fullname": "Tai" 165 | } 166 | }, 167 | "fields": [ 168 | "fullname" 169 | ], 170 | "_source": false, 171 | "sort": [ 172 | { 173 | "@timestamp": { 174 | "order": "desc" 175 | } 176 | } 177 | ] 178 | } 179 | ``` 180 | 181 | # Search documents with true conditions 182 | ```cmd 183 | GET product_info/_search 184 | { 185 | "query": { 186 | "match": { 187 | "fullname": { 188 | "query": "Tien Tai", 189 | "operator": "and" 190 | } 191 | } 192 | }, 193 | "fields": [ 194 | "fullname" 195 | ], 196 | "_source": false, 197 | "sort": [ 198 | { 199 | "@timestamp": { 200 | "order": "desc" 201 | } 202 | } 203 | ] 204 | } 205 | ``` 206 | 207 | # Search for documents with only one true word 208 | ```cmd 209 | GET product_info/_search 210 | { 211 | "query": { 212 | "match": { 213 | "fullname": { 214 | "query": "Tien Taia", 215 | "minimum_should_match": 1 216 | } 217 | } 218 | }, 219 | "fields": [ 220 | "fullname" 221 | ], 222 | "_source": false, 223 | "sort": [ 224 | { 225 | "@timestamp": { 226 | "order": "desc" 227 | } 228 | } 229 | ] 230 | } 231 | ``` 232 | 233 | # Search flow sentence 234 | ```cmd 235 | POST product_info/_search 236 | { 237 | "query": { 238 | "match_phrase": { 239 | "fullname": "Van" 240 | } 241 | } 242 | } 243 | ``` 244 | 245 | # Search flow prefix - sunfix 246 | ```cmd 247 | POST product_info/_search 248 | { 249 | "query": { 250 | "match_phrase_prefix": { 251 | "fullname": { 252 | "query": "ag" 253 | } 254 | } 255 | } 256 | } 257 | ``` 258 | 259 | ```cmd 260 | POST product_info/_search 261 | { 262 | "query": { 263 | "match_phrase_prefix": { 264 | "fullname": { 265 | "query": "nguy", 266 | "max_expansions": 2 267 | } 268 | } 269 | } 270 | } 271 | ``` -------------------------------------------------------------------------------- /service-search-elastic/LICENSE.md: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2024 Nguyen Tien Tai 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /service-search-elastic/README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | Linkedin 5 | Profile 6 | Phone 7 | License 8 |

9 | 10 | ## Project: Service Search Algolia 11 | 12 | ## Team Word: Liên hệ công việc https://profile-forme.com 13 | 14 | ## 1. Nguyen Tien Tai( MainTain 🚩). 15 | 16 | ## Tài Khoản Donate li Cf để có động lực code cho anh em tham khảo 😄. 17 | 18 | ![giphy](https://3.bp.blogspot.com/-SzGvXn2sTmw/V6k-90GH3ZI/AAAAAAAAIsk/Q678Pil-0kITLPa3fD--JkNdnJVKi_BygCLcB/s1600/cf10-fbc08%2B%25281%2529.gif) 19 | 20 | ## Mk: NGUYEN TIEN TAI 21 | 22 | ## STK: 1651002972052 23 | 24 | ## Chi Nhánh: NGAN HANG TMCP AN BINH (ABBANK). 25 | 26 | ## SUPPORT CONTACT: [https://profile-forme.com](https://profile-forme.com) 27 | 28 | ## Thank You <3. 29 | -------------------------------------------------------------------------------- /service-search-elastic/SEARCH.md: -------------------------------------------------------------------------------- 1 | ## 1: Search Theo Từ khóa: 2 | 3 | ```javascript 4 | const result1 = await index.search('your_keyword'); 5 | ``` 6 | 7 | ## 2: Tìm Kiếm Theo Mô Hình Phân Cấp (Faceting): 8 | 9 | ```javascript 10 | const result2 = await index.search('your_keyword', { 11 | facets: ['category', 'price', 'brand'], 12 | }); 13 | ``` 14 | 15 | ## 3: Tìm Kiếm Theo Dải Giá: 16 | 17 | ```javascript 18 | const result3 = await index.search('', { 19 | filters: 'price:[min_price TO max_price]', 20 | }); 21 | ``` 22 | 23 | ## 4: Tìm Kiếm Gần Đúng (Fuzzy Search): 24 | 25 | ```javascript 26 | const result4 = await index.search('your_keyword~'); 27 | ``` 28 | 29 | ## 5: Tìm Kiếm Theo Vị Trí (Geolocation): 30 | 31 | ```javascript 32 | const result5 = await index.search('', { 33 | aroundLatLng: 'lat,lng', 34 | aroundRadius: 10000, // Đơn vị tính mét 35 | }); 36 | ``` 37 | 38 | ## 6: Tìm Kiếm Theo Ngày: 39 | 40 | ```javascript 41 | const result5 = await index.search('', { 42 | aroundLatLng: 'lat,lng', 43 | aroundRadius: 10000, // Đơn vị tính mét 44 | }); 45 | ``` 46 | 47 | ## 7: Tìm Kiếm Theo Danh Mục: 48 | 49 | ```javascript 50 | const result7 = await index.search('your_keyword', { 51 | filters: 'category:electronics', 52 | }); 53 | ``` 54 | 55 | ## 8: Tìm Kiếm Theo Nhiều Từ Khóa (AND): 56 | 57 | ```javascript 58 | const result8 = await index.search('keyword1 AND keyword2'); 59 | ``` 60 | 61 | ## 9: Tìm Kiếm Theo Từ Khóa Phổ Biến: 62 | 63 | ```javascript 64 | const result9 = await index.search('popular_keywords'); 65 | ``` 66 | 67 | ## 10: Tìm Kiếm Đa Truy Vấn (Boolean Query): 68 | 69 | ```javascript 70 | const result10 = await index.search('keyword1 AND (keyword2 OR keyword3) NOT keyword4'); 71 | ``` 72 | 73 | ## 11: Sắp Xếp Kết Quả: 74 | 75 | ```javascript 76 | const result = await index.search('search_query', { 77 | facets: ['category', 'brand', 'price'], 78 | sortBy: ['relevance', 'price:asc'], 79 | }); 80 | ``` 81 | 82 | ## 12: Phân Trang Kết Quả: 83 | 84 | ```javascript 85 | const result = await index.search('search_query', { 86 | facets: ['category', 'brand', 'price'], 87 | hitsPerPage: 10, 88 | page: 1, 89 | }); 90 | ``` 91 | 92 | ## 13: Tìm Kiếm Đa Nguồn: 93 | 94 | ```javascript 95 | const result = await searchClient.multipleQueries([ 96 | { 97 | indexName: 'index1', 98 | query: 'search_query', 99 | }, 100 | { 101 | indexName: 'index2', 102 | query: 'search_query', 103 | }, 104 | ]); 105 | ``` 106 | 107 | ## 14: Gợi Ý Tìm Kiếm (Autocomplete): 108 | 109 | ```javascript 110 | const result = await index.search('partial_query', { 111 | facets: ['category', 'brand', 'price'], 112 | hitsPerPage: 5, 113 | }); 114 | ``` 115 | 116 | ## 15: Lấy những trường cần 117 | 118 | ```javascript 119 | const result = await index.search('search_query', { 120 | facets: ['category', 'brand', 'price'], 121 | attributesToRetrieve: ['make', 'model', 'image', 'description'], 122 | hitsPerPage: 10, 123 | }); 124 | 125 | // Kết quả sẽ chỉ chứa các trường được chỉ định trong attributesToRetrieve 126 | console.log(result); 127 | ``` 128 | 129 | ## 16: Tìm kiếm nhiều option v1 130 | 131 | ```javascript 132 | const searchQuery = { 133 | query: 'your_search_term', // Từ khóa tìm kiếm 134 | attributesToHighlight: ['name', 'description'], // Nổi bật các trường 135 | attributesToSnippet: ['content:10'], // Hiển thị đoạn văn bản snippet 136 | facetFilters: [['category:Electronics', 'brand:Samsung']], // Bộ lọc động 137 | aroundLatLng: '37.7749, -122.4194', // Tìm kiếm xung quanh vị trí 138 | aroundRadius: 10000, // Bán kính tìm kiếm xung quanh 139 | numericFilters: ['price >= 50', 'price <= 100'], // Bộ lọc số học 140 | queryType: 'prefixLast', // Loại truy vấn 141 | typoTolerance: 'min', // Chấp nhận ít lỗi chính tả hơn 142 | }; 143 | 144 | index 145 | .search('search_query', searchQuery) 146 | .then(({ hits }) => { 147 | console.log('Result', hits); 148 | }) 149 | .catch((err) => { 150 | console.error('Error:', err); 151 | }); 152 | ``` 153 | 154 | ## 17: Tìm kiếm nhiều option v2 155 | 156 | ```javascript 157 | const searchQuery = { 158 | // Chỉ lấy các trường cần thiết từ kết quả tìm kiếm 159 | attributesToRetrieve: ['name', 'price', 'image'], 160 | 161 | // Chỉ trả về một số lượng kết quả cụ thể 162 | hitsPerPage: 10, 163 | 164 | // Sắp xếp kết quả theo giá giảm dần 165 | sortBy: ['price:desc'], 166 | 167 | // Đánh dấu các từ khóa trong trường mô tả 168 | highlightPreTag: '', 169 | highlightPostTag: '', 170 | 171 | // Chỉ tìm kiếm trong một số trường cụ thể 172 | restrictSearchableAttributes: ['name', 'description'], 173 | 174 | // Tùy chọn tìm kiếm thông minh 175 | enableABTest: true, 176 | ruleContexts: ['mobile'], 177 | 178 | // Chỉ trả về các kết quả có chất lượng cao (Relevance Score >= 50) 179 | minRelevanceScore: 50, 180 | }; 181 | 182 | index 183 | .search('search_query', searchQuery) 184 | .then(({ hits }) => { 185 | console.log('Kết quả tìm kiếm:', hits); 186 | }) 187 | .catch((err) => { 188 | console.error('Lỗi tìm kiếm:', err); 189 | }); 190 | ``` 191 | -------------------------------------------------------------------------------- /service-search-elastic/addons/frontend-zips/client-search.zip: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fdhhhdjd/Class_Search_Engine/16d30bafdf33febce9556353981efc86c488899d/service-search-elastic/addons/frontend-zips/client-search.zip -------------------------------------------------------------------------------- /service-search-elastic/addons/postman/ElasticSearch.postman_environment.json: -------------------------------------------------------------------------------- 1 | { 2 | "id": "b79931d4-3b39-4b3d-8806-c1463fec9653", 3 | "name": "ElasticSearch", 4 | "values": [ 5 | { 6 | "key": "URL_EL", 7 | "value": "http://localhost:9200", 8 | "type": "default", 9 | "enabled": true 10 | }, 11 | { 12 | "key": "EL_USER", 13 | "value": "elastic", 14 | "type": "default", 15 | "enabled": true 16 | }, 17 | { 18 | "key": "EL_PASS", 19 | "value": "taidev", 20 | "type": "default", 21 | "enabled": true 22 | }, 23 | { 24 | "key": "EL_TOKEN", 25 | "value": "AAEAAWVsYXN0aWMva2liYW5hL3Rva2VuMTprcmJlM29RY1MxUzlqeWtEcHJJM0hR", 26 | "type": "default", 27 | "enabled": true 28 | } 29 | ], 30 | "_postman_variable_scope": "environment", 31 | "_postman_exported_at": "2024-04-25T08:12:05.458Z", 32 | "_postman_exported_using": "Postman/10.24.24" 33 | } -------------------------------------------------------------------------------- /service-search-elastic/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | services: 3 | # Todo: 1. Service Search 4 | service_search: 5 | container_name: service_search 6 | depends_on: 7 | - elastic-search 8 | - kibana 9 | restart: always 10 | build: 11 | context: . 12 | dockerfile: ./docker/Dockerfile 13 | environment: 14 | - NODE_ENV=${NODE_ENV} 15 | ports: 16 | - ${PORT}:${PORT} 17 | volumes: 18 | - './src:/usr/src/app/src' 19 | env_file: 20 | - .env 21 | command: yarn dev 22 | networks: 23 | - service_search_service-network 24 | 25 | # Todo: 2. Elastic search 26 | elasticsearch: 27 | container_name: elasticsearch 28 | image: docker.elastic.co/elasticsearch/elasticsearch:8.4.3 29 | environment: 30 | node.name: elasticsearch 31 | ES_JAVA_OPTS: -Xms512m -Xmx512m 32 | discovery.type: single-node 33 | ELASTIC_PASSWORD: ${ELASTIC_PASSWORD:-} 34 | volumes: 35 | - ./elasticsearch/config/elasticsearch.yml:/usr/share/elasticsearch/config/elasticsearch.yml:ro,Z 36 | - elasticsearch-data:/usr/share/elasticsearch/data:Z 37 | ports: 38 | - ${ELASTIC_SEARCH_PORT}:${ELASTIC_SEARCH_PORT} 39 | env_file: 40 | - .env 41 | networks: 42 | - elk 43 | 44 | kibana: 45 | container_name: kibana 46 | image: docker.elastic.co/kibana/kibana:8.4.3 47 | depends_on: 48 | - elasticsearch 49 | environment: 50 | ELASTICSEARCH_HOSTS: ${ELASTIC_SEARCH_HOST:-} 51 | ELASTICSEARCH_SERVICEACCOUNTTOKEN: ${ELASTIC_TOKEN:-} 52 | ulimits: 53 | memlock: 54 | soft: -1 55 | hard: -1 56 | nofile: 57 | soft: 65536 58 | hard: 65536 59 | cap_add: 60 | - IPC_LOCK 61 | links: 62 | - elasticsearch 63 | ports: 64 | - ${KIBANA_PORT}:${KIBANA_PORT} 65 | env_file: 66 | - .env 67 | networks: 68 | - elk 69 | networks: 70 | elk: 71 | driver: bridge 72 | 73 | volumes: 74 | elasticsearch-data: 75 | driver: local 76 | -------------------------------------------------------------------------------- /service-search-elastic/docker/Dockerfile: -------------------------------------------------------------------------------- 1 | # Stage 1: Builder 2 | FROM node:18-alpine as builder 3 | 4 | 5 | # Create folder if it not exits 6 | RUN mkdir -p /usr/src/app 7 | 8 | WORKDIR /usr/src/app 9 | 10 | COPY package.json ./ 11 | RUN yarn install --no-optional && \ 12 | yarn cache clean 13 | 14 | COPY . . 15 | 16 | USER root 17 | 18 | # Define available eviroment with port 19 | ARG PORT 20 | ENV PORT $PORT 21 | 22 | # Stage 2: Final 23 | FROM node:18-alpine as final 24 | 25 | # Set the working directory to /usr/src/app 26 | WORKDIR /usr/src/app 27 | 28 | # Copy các tệp từ stage builder 29 | COPY --from=builder /usr/src/app . 30 | 31 | # Setting user not must is root 32 | USER node 33 | 34 | # Expose port 35 | EXPOSE $PORT 36 | 37 | # Check heal of applycation 38 | HEALTHCHECK --interval=60s --timeout=2s --retries=3 CMD sh -c "wget localhost:${PORT}/api/v1 -q -O - > /dev/null 2>&1" 39 | 40 | # Command run applycation 41 | CMD ["yarn", "dev"] 42 | -------------------------------------------------------------------------------- /service-search-elastic/elasticsearch/config/elasticsearch.yml: -------------------------------------------------------------------------------- 1 | ## - http 2 | cluster.name: docker-cluster 3 | network.host: 0.0.0.0 4 | xpack.license.self_generated.type: trial 5 | xpack.security.enabled: true 6 | bootstrap.memory_lock: true 7 | http.cors.enabled : true 8 | http.cors.allow-origin: "*" 9 | http.cors.allow-methods: OPTIONS, HEAD, GET, POST, PUT, DELETE 10 | http.cors.allow-headers: X-Requested-With,X-Auth-Token,Content-Type,Content-Length,Authorization 11 | http.cors.allow-credentials: true 12 | path.data: /usr/share/elasticsearch/data 13 | 14 | # xpack.security.http.ssl.enabled: true 15 | # xpack.security.http.ssl.key: elasticsearch.key 16 | # xpack.security.http.ssl.certificate: elasticsearch.crt 17 | # xpack.security.http.ssl.certificate_authorities: ca.crt 18 | # xpack.security.http.ssl.client_authentication: optional -------------------------------------------------------------------------------- /service-search-elastic/makefile: -------------------------------------------------------------------------------- 1 | # Get file .env 2 | include .env 3 | export $(shell sed 's/=.*//' .env) 4 | 5 | # Folder constants 6 | DOCKER_COMPOSE := docker-compose.yml 7 | DOCKER_EXEC_APP := service_search 8 | DOCKER_EXEC_CACHE := redis-search 9 | 10 | # Run auto 11 | default: 12 | docker ps 13 | 14 | run-build: 15 | docker-compose -f $(DOCKER_COMPOSE) up -d --build 16 | make remove-image-none 17 | 18 | run-dev: 19 | docker-compose -f $(DOCKER_COMPOSE) up -d 20 | 21 | run-down: 22 | docker-compose -f $(DOCKER_COMPOSE) down 23 | 24 | into-source: 25 | docker exec -it $(DOCKER_EXEC_APP) sh 26 | 27 | into-source-redis: 28 | docker exec -it $(DOCKER_EXEC_CACHE) sh 29 | 30 | remove-image-none: 31 | docker images --filter "dangling=true" -q --no-trunc | xargs -r docker rmi || true 32 | 33 | create-token: 34 | curl -X POST -u elastic:taidev "localhost:9200/_security/service/elastic/kibana/credential/token/token1?pretty" 35 | 36 | -------------------------------------------------------------------------------- /service-search-elastic/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "service-search-elastic", 3 | "version": "0.0.1", 4 | "main": "server.js", 5 | "repository": "https://github.com/fdhhhdjd/Class_Redis_Search_Engine", 6 | "author": "fdhhhdjd ", 7 | "type": "commonjs", 8 | "license": "MIT", 9 | "scripts": { 10 | "start": "node server.js", 11 | "dev": "node --watch server.js", 12 | "build": "tsc && vite build", 13 | "preview": "vite preview", 14 | "lint": "eslint . --ext .cjs,.mjs,.js,.cts,.mts --fix --ignore-path .gitignore && echo \"Tai Dev Check Eslint ✅\"", 15 | "lint:fix": "eslint . --fix --ext .js", 16 | "format": "prettier --write src/**/*.{js}" 17 | }, 18 | "engines": { 19 | "node": ">=16.20.1", 20 | "npm": ">= 8.19.4" 21 | }, 22 | "dependencies": { 23 | "@elastic/elasticsearch": "^8.11.0", 24 | "body-parser": "^1.20.2", 25 | "compression": "^1.7.4", 26 | "cors": "^2.8.5", 27 | "dotenv": "^16.3.1", 28 | "express": "^4.18.2", 29 | "express-rate-limit": "^7.1.5", 30 | "helmet": "^7.1.0", 31 | "lodash": "^4.17.21", 32 | "morgan": "^1.10.0", 33 | "uuid": "^9.0.1", 34 | "winston": "^3.11.0" 35 | }, 36 | "devDependencies": { 37 | "eslint": "^8.56.0", 38 | "eslint-config-prettier": "^9.0.0", 39 | "eslint-import-resolver-alias": "^1.1.2", 40 | "eslint-plugin-import": "^2.29.1", 41 | "eslint-plugin-prettier": "^5.0.1", 42 | "eslint-plugin-promise": "^6.1.1", 43 | "eslint-plugin-security": "^2.1.0", 44 | "prettier": "^3.0.3" 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /service-search-elastic/server.js: -------------------------------------------------------------------------------- 1 | //* IMPORT 2 | const app = require('./src/app'); 3 | const { 4 | app: { port: PORT }, 5 | } = require('./src/common/configs/app.config'); 6 | 7 | const server = app.listen(PORT, () => { 8 | console.info(`Api backend start with http://localhost:${PORT}`); 9 | }); 10 | 11 | process.on('SIGINT', () => { 12 | server.close(() => console.info('Exit Server Express')); 13 | }); 14 | -------------------------------------------------------------------------------- /service-search-elastic/src/app.js: -------------------------------------------------------------------------------- 1 | //* LIB 2 | const compression = require('compression'); 3 | const cors = require('cors'); 4 | const express = require('express'); 5 | const { default: helmet } = require('helmet'); 6 | const morgan = require('morgan'); 7 | 8 | const app = express(); 9 | require('dotenv').config(); 10 | 11 | //* IMPORT 12 | const { 13 | app: { morgan: morganConfig, node }, 14 | } = require('./common/configs/app.config'); 15 | const { NODE_ENV, LIMIT } = require('./common/constants'); 16 | const { StatusCodes, ReasonPhrases } = require('./common/utils/httpStatusCode'); 17 | const RateLimitIp = require('./middlewares/rateLimitMiddleware'); 18 | 19 | app.use(morgan(morganConfig)); 20 | app.enable(); 21 | app.use(cors()); 22 | app.use(helmet()); 23 | app.use(compression()); 24 | app.use( 25 | express.json({ 26 | limit: LIMIT._5_MB, 27 | }), 28 | ); 29 | app.use(RateLimitIp); 30 | app.use( 31 | express.urlencoded({ 32 | extended: true, 33 | }), 34 | ); 35 | 36 | //* V1 37 | app.use('/api', require('./app/v1/routes')); 38 | 39 | //* Error 40 | app.use((_, __, next) => { 41 | const ErrorCode = new Error(StatusCodes.NOT_FOUND); 42 | ErrorCode.status = StatusCodes.NOT_FOUND; 43 | return next(ErrorCode); 44 | }); 45 | 46 | app.use((error, _, res, __) => { 47 | const statusCode = error.status || StatusCodes.INTERNAL_SERVER_ERROR; 48 | const message = error.message || ReasonPhrases.INTERNAL_SERVER_ERROR; 49 | 50 | const response = { 51 | message, 52 | status: statusCode, 53 | }; 54 | 55 | const checkNodeApp = node === NODE_ENV.DEV; 56 | if (checkNodeApp) { 57 | Object.assign(response, { stack: error.stack }); 58 | } 59 | 60 | return res.status(statusCode).json(response); 61 | }); 62 | 63 | module.exports = app; 64 | -------------------------------------------------------------------------------- /service-search-elastic/src/app/v1/controllers/car.controller.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* IMPORT 4 | const { SuccessResponse, Created } = require('../../../cores/success.response'); 5 | const CarService = require('../services/car.service'); 6 | 7 | class CarControllers { 8 | async searchAll(req, res, __) { 9 | const query = req.query.q; 10 | new SuccessResponse({ 11 | message: 'Search All key success.', 12 | metadata: await CarService.searchAll({ query }), 13 | }).send(res); 14 | } 15 | 16 | async getAllCars(_, res, __) { 17 | new SuccessResponse({ 18 | message: 'Get All Cars success.', 19 | metadata: await CarService.getAllCars(), 20 | }).send(res); 21 | } 22 | 23 | async searchAllIndex(req, res, __) { 24 | const { idx, query } = req.body; 25 | 26 | new SuccessResponse({ 27 | message: `Query ${idx} success.`, 28 | metadata: await CarService.searchAllIndex({ idx, query }), 29 | }).send(res); 30 | } 31 | 32 | async getDetailId(req, res, __) { 33 | const id = req.params.id; 34 | new SuccessResponse({ 35 | message: 'Get detail todo success.', 36 | metadata: await CarService.getDetailId({ id }), 37 | }).send(res); 38 | } 39 | 40 | async create(req, res, __) { 41 | new Created({ 42 | message: 'Create todo success.', 43 | metadata: await CarService.create(req.body), 44 | }).send(res); 45 | } 46 | 47 | async update(req, res, __) { 48 | new SuccessResponse({ 49 | message: 'Update todo success', 50 | metadata: await CarService.update(req.body), 51 | }).send(res); 52 | } 53 | 54 | async delete(req, res, __) { 55 | const id = req.params.id; 56 | 57 | new SuccessResponse({ 58 | message: 'Delete todo success.', 59 | metadata: await CarService.delete({ id }), 60 | }).send(res); 61 | } 62 | } 63 | 64 | module.exports = new CarControllers(); 65 | -------------------------------------------------------------------------------- /service-search-elastic/src/app/v1/models/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fdhhhdjd/Class_Search_Engine/16d30bafdf33febce9556353981efc86c488899d/service-search-elastic/src/app/v1/models/.gitkeep -------------------------------------------------------------------------------- /service-search-elastic/src/app/v1/routes/cars/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* LIB 4 | const express = require('express'); 5 | const router = express.Router(); 6 | 7 | //* IMPORT 8 | const { asyncHandler } = require('../../../../common/helpers/asyncHandler'); 9 | const CarControllers = require('../../controllers/car.controller'); 10 | 11 | // -- CURD 12 | // Todo 1. Get All 13 | router.get('/get/all', asyncHandler(CarControllers.getAllCars)); 14 | 15 | // Todo 2. Get Detail 16 | router.get('/get/:id', asyncHandler(CarControllers.getDetailId)); 17 | 18 | // Todo 3. Create 19 | router.post('/create', asyncHandler(CarControllers.create)); 20 | 21 | // Todo 4. Update 22 | router.patch('/update', asyncHandler(CarControllers.update)); 23 | 24 | // Todo 5. Delete 25 | router.delete('/delete/:id', asyncHandler(CarControllers.delete)); 26 | 27 | // -- SEARCH 28 | router.get('/search/all', asyncHandler(CarControllers.searchAll)); 29 | 30 | module.exports = router; 31 | -------------------------------------------------------------------------------- /service-search-elastic/src/app/v1/routes/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* LIB 4 | const express = require('express'); 5 | 6 | //* IMPORT 7 | const { StatusCodes, ReasonPhrases } = require('../../../common/utils/httpStatusCode'); 8 | 9 | const router = express.Router(); 10 | 11 | // Todo: 1. Cars 12 | router.use('/v1/cars', require('./cars')); 13 | 14 | router.get('/v1', async (_, res, __) => { 15 | const healthCheck = { 16 | uptime: process.uptime(), 17 | message: ReasonPhrases.OK, 18 | timestamp: Date.now(), 19 | }; 20 | return res.status(StatusCodes.OK).json(healthCheck); 21 | }); 22 | 23 | module.exports = router; 24 | -------------------------------------------------------------------------------- /service-search-elastic/src/app/v1/services/car.service.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable no-useless-catch */ 2 | 'use strict'; 3 | 4 | const { NameIndex } = require('../../../common/index/cars'); 5 | const client = require('../../../dbs'); 6 | 7 | //* IMPORT 8 | 9 | class CarService { 10 | static async searchAll({ query }) { 11 | const result = await client.search({ 12 | index: NameIndex, 13 | body: { 14 | query: { 15 | multi_match: { 16 | query: query, 17 | fields: ['make', 'model'], 18 | }, 19 | }, 20 | suggest: { 21 | makeSuggestion: { 22 | prefix: query, 23 | completion: { 24 | field: 'make.suggest', 25 | size: 5, 26 | }, 27 | }, 28 | modelSuggestion: { 29 | prefix: query, 30 | completion: { 31 | field: 'model.suggest', 32 | size: 5, 33 | }, 34 | }, 35 | }, 36 | }, 37 | }); 38 | 39 | return result.hits; 40 | } 41 | 42 | static async getAllCars() { 43 | try { 44 | const result = await client.search({ 45 | index: NameIndex, 46 | body: { 47 | query: { match_all: {} }, 48 | }, 49 | }); 50 | 51 | // const data = result.hits.hits.map((hit) => hit._source); 52 | return result.hits; 53 | } catch (error) { 54 | throw error; 55 | } 56 | } 57 | 58 | static async getDetailId({ id }) { 59 | try { 60 | const result = await client.get({ 61 | index: NameIndex, 62 | id: id, 63 | }); 64 | 65 | return result; 66 | } catch (error) { 67 | throw error; 68 | } 69 | } 70 | 71 | static async create({ make, model, image, description }) { 72 | try { 73 | const result = await client.index({ 74 | index: NameIndex, 75 | body: { 76 | make: make, 77 | model: model, 78 | image: image, 79 | description: description, 80 | }, 81 | }); 82 | 83 | return result; 84 | } catch (error) { 85 | throw error; 86 | } 87 | } 88 | 89 | static async update({ id, make, model, image, description }) { 90 | try { 91 | const result = await client.update({ 92 | index: NameIndex, 93 | id: id, 94 | body: { 95 | doc: { 96 | make: make, 97 | model: model, 98 | image: image, 99 | description: description, 100 | }, 101 | }, 102 | }); 103 | 104 | return result; 105 | } catch (error) { 106 | throw error; 107 | } 108 | } 109 | 110 | static async delete({ id }) { 111 | try { 112 | const result = await client.delete({ 113 | index: NameIndex, 114 | id: id, 115 | }); 116 | 117 | return result; 118 | } catch (error) { 119 | throw error; 120 | } 121 | } 122 | } 123 | 124 | module.exports = CarService; 125 | -------------------------------------------------------------------------------- /service-search-elastic/src/common/configs/app.config.js: -------------------------------------------------------------------------------- 1 | const DEV = { 2 | app: { 3 | port: process.env.PORT || 5000, 4 | morgan: process.env.MORGAN || 'dev', 5 | node: process.env.NODE_ENV, 6 | web_server: process.env.WEB_SERVER, 7 | }, 8 | }; 9 | const PRO = { 10 | app: { 11 | port: process.env.PORT || 5000, 12 | morgan: process.env.MORGAN || 'combined', 13 | node: process.env.NODE_ENV, 14 | web_server: process.env.WEB_SERVER, 15 | }, 16 | }; 17 | const config = { DEV, PRO }; 18 | 19 | const env = process.env.NODE_ENV || 'DEV'; 20 | 21 | module.exports = config[env]; 22 | -------------------------------------------------------------------------------- /service-search-elastic/src/common/constants/index.js: -------------------------------------------------------------------------------- 1 | const NODE_ENV = { 2 | DEV: 'DEV', 3 | PRO: 'PRO', 4 | }; 5 | 6 | const ENABLE_IP = 'trust proxy'; 7 | 8 | const LIMIT = { 9 | _5_MB: '5mb', 10 | }; 11 | 12 | const REQUEST = { 13 | _WINDOW_MS: 1 * 60 * 1000, 14 | _MAX: 100, 15 | }; 16 | 17 | module.exports = { 18 | NODE_ENV, 19 | ENABLE_IP, 20 | LIMIT, 21 | REQUEST, 22 | }; 23 | -------------------------------------------------------------------------------- /service-search-elastic/src/common/helpers/asyncHandler.js: -------------------------------------------------------------------------------- 1 | const asyncHandler = (fn) => { 2 | return (req, res, next) => { 3 | Promise.resolve(fn(req, res, next)).catch((error) => { 4 | next(error); 5 | }); 6 | }; 7 | }; 8 | 9 | module.exports = { asyncHandler }; 10 | -------------------------------------------------------------------------------- /service-search-elastic/src/common/helpers/validate/index.js: -------------------------------------------------------------------------------- 1 | //* IMPORT 2 | const { BadRequestRequestError } = require('../../../cores/error.response.js'); 3 | 4 | class ValidationUtils { 5 | static validateField({ value, fieldName, validators }) { 6 | const invalidValidator = validators.find(({ validate }) => !validate(value)); 7 | if (invalidValidator) { 8 | const { message } = invalidValidator; 9 | throw new BadRequestRequestError({ 10 | message: `${fieldName} ${message}`, 11 | }); 12 | } 13 | } 14 | } 15 | 16 | module.exports = ValidationUtils; 17 | -------------------------------------------------------------------------------- /service-search-elastic/src/common/helpers/validate/todo.validate.js: -------------------------------------------------------------------------------- 1 | //* IMPORT 2 | const ValidationUtils = require('.'); 3 | 4 | class TodoBuilder { 5 | build() { 6 | throw new Error('Method not implemented.'); 7 | } 8 | 9 | constructor() { 10 | this.id = ''; 11 | this.text = ''; 12 | } 13 | 14 | setId(id) { 15 | this.id = id; 16 | return this; 17 | } 18 | 19 | setText(text) { 20 | this.text = text; 21 | return this; 22 | } 23 | 24 | validateEmptyId(id) { 25 | return id; 26 | } 27 | 28 | validateEmptyText(text) { 29 | return text; 30 | } 31 | } 32 | 33 | class RDBuilder extends TodoBuilder { 34 | build() { 35 | ValidationUtils.validateField({ 36 | value: this.id, 37 | fieldName: 'Id', 38 | validators: [ 39 | { 40 | validate: this.validateEmptyId, 41 | message: 'is invalid', 42 | }, 43 | ], 44 | }); 45 | } 46 | } 47 | 48 | class CUBuilder extends TodoBuilder { 49 | build() { 50 | ValidationUtils.validateField({ 51 | value: this.id, 52 | fieldName: 'Id', 53 | validators: [ 54 | { 55 | validate: this.validateEmptyId, 56 | message: 'is invalid', 57 | }, 58 | ], 59 | }); 60 | ValidationUtils.validateField({ 61 | value: this.text, 62 | fieldName: 'Text', 63 | validators: [ 64 | { 65 | validate: this.validateEmptyText, 66 | message: 'is empty', 67 | }, 68 | ], 69 | }); 70 | } 71 | } 72 | 73 | const RDInputBuilder = new RDBuilder(); 74 | const CUInputBuilder = new CUBuilder(); 75 | 76 | module.exports = { RDInputBuilder, CUInputBuilder }; 77 | -------------------------------------------------------------------------------- /service-search-elastic/src/common/index/cars.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | NameIndex: 'cars', 3 | }; 4 | -------------------------------------------------------------------------------- /service-search-elastic/src/common/utils/httpStatusCode.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | StatusCodes: require('../utils/statusCodes'), 3 | ReasonPhrases: require('../utils/reasonPhrases'), 4 | }; 5 | -------------------------------------------------------------------------------- /service-search-elastic/src/common/utils/statusCodes.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable max-len */ 2 | module.exports = { 3 | /** 4 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.1 5 | * 6 | * 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. 7 | */ 8 | CONTINUE: 100, 9 | /** 10 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.2 11 | * 12 | * This code is sent in response to an Upgrade request header by the client, and indicates the protocol the server is switching too. 13 | */ 14 | SWITCHING_PROTOCOLS: 101, 15 | /** 16 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.1 17 | * 18 | * This code indicates that the server has received and is processing the request, but no response is available yet. 19 | */ 20 | PROCESSING: 102, 21 | /** 22 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.1 23 | * 24 | * The request has succeeded. The meaning of a success varies depending on the HTTP method: 25 | * GET: The resource has been fetched and is transmitted in the message body. 26 | * HEAD: The entity headers are in the message body. 27 | * POST: The resource describing the result of the action is transmitted in the message body. 28 | * TRACE: The message body contains the request message as received by the server 29 | */ 30 | OK: 200, 31 | /** 32 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.2 33 | * 34 | * 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. 35 | */ 36 | CREATED: 201, 37 | /** 38 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.3 39 | * 40 | * 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. 41 | */ 42 | ACCEPTED: 202, 43 | /** 44 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.4 45 | * 46 | * 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. 47 | */ 48 | NON_AUTHORITATIVE_INFORMATION: 203, 49 | /** 50 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.5 51 | * 52 | * 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. 53 | */ 54 | NO_CONTENT: 204, 55 | /** 56 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.6 57 | * 58 | * This response code is sent after accomplishing request to tell user agent reset document view which sent this request. 59 | */ 60 | RESET_CONTENT: 205, 61 | /** 62 | * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.1 63 | * 64 | * This response code is used because of range header sent by the client to separate download into multiple streams. 65 | */ 66 | PARTIAL_CONTENT: 206, 67 | /** 68 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.2 69 | * 70 | * A Multi-Status response conveys information about multiple resources in situations where multiple status codes might be appropriate. 71 | */ 72 | MULTI_STATUS: 207, 73 | /** 74 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.1 75 | * 76 | * 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. 77 | */ 78 | MULTIPLE_CHOICES: 300, 79 | /** 80 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.2 81 | * 82 | * This response code means that URI of requested resource has been changed. Probably, new URI would be given in the response. 83 | */ 84 | MOVED_PERMANENTLY: 301, 85 | /** 86 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.3 87 | * 88 | * 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. 89 | */ 90 | MOVED_TEMPORARILY: 302, 91 | /** 92 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.4 93 | * 94 | * Server sent this response to directing client to get requested resource to another URI with an GET request. 95 | */ 96 | SEE_OTHER: 303, 97 | /** 98 | * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.1 99 | * 100 | * 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. 101 | */ 102 | NOT_MODIFIED: 304, 103 | /** 104 | * @deprecated 105 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.6 106 | * 107 | * 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. 108 | */ 109 | USE_PROXY: 305, 110 | /** 111 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.7 112 | * 113 | * 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. 114 | */ 115 | TEMPORARY_REDIRECT: 307, 116 | /** 117 | * Official Documentation @ https://tools.ietf.org/html/rfc7538#section-3 118 | * 119 | * 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. 120 | */ 121 | PERMANENT_REDIRECT: 308, 122 | /** 123 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.1 124 | * 125 | * This response means that server could not understand the request due to invalid syntax. 126 | */ 127 | BAD_REQUEST: 400, 128 | /** 129 | * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.1 130 | * 131 | * Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response. 132 | */ 133 | UNAUTHORIZED: 401, 134 | /** 135 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.2 136 | * 137 | * 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. 138 | */ 139 | PAYMENT_REQUIRED: 402, 140 | /** 141 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.3 142 | * 143 | * 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. 144 | */ 145 | FORBIDDEN: 403, 146 | /** 147 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.4 148 | * 149 | * 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. 150 | */ 151 | NOT_FOUND: 404, 152 | /** 153 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.5 154 | * 155 | * 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. 156 | */ 157 | METHOD_NOT_ALLOWED: 405, 158 | /** 159 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.6 160 | * 161 | * 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. 162 | */ 163 | NOT_ACCEPTABLE: 406, 164 | /** 165 | * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.2 166 | * 167 | * This is similar to 401 but authentication is needed to be done by a proxy. 168 | */ 169 | PROXY_AUTHENTICATION_REQUIRED: 407, 170 | /** 171 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.7 172 | * 173 | * 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. 174 | */ 175 | REQUEST_TIMEOUT: 408, 176 | /** 177 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.8 178 | * 179 | * This response is sent when a request conflicts with the current state of the server. 180 | */ 181 | CONFLICT: 409, 182 | /** 183 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.9 184 | * 185 | * 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. 186 | */ 187 | GONE: 410, 188 | /** 189 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.10 190 | * 191 | * The server rejected the request because the Content-Length header field is not defined and the server requires it. 192 | */ 193 | LENGTH_REQUIRED: 411, 194 | /** 195 | * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.2 196 | * 197 | * The client has indicated preconditions in its headers which the server does not meet. 198 | */ 199 | PRECONDITION_FAILED: 412, 200 | /** 201 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.11 202 | * 203 | * Request entity is larger than limits defined by server; the server might close the connection or return an Retry-After header field. 204 | */ 205 | REQUEST_TOO_LONG: 413, 206 | /** 207 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.12 208 | * 209 | * The URI requested by the client is longer than the server is willing to interpret. 210 | */ 211 | REQUEST_URI_TOO_LONG: 414, 212 | /** 213 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.13 214 | * 215 | * The media format of the requested data is not supported by the server, so the server is rejecting the request. 216 | */ 217 | UNSUPPORTED_MEDIA_TYPE: 415, 218 | /** 219 | * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.4 220 | * 221 | * 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. 222 | */ 223 | REQUESTED_RANGE_NOT_SATISFIABLE: 416, 224 | /** 225 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.14 226 | * 227 | * This response code means the expectation indicated by the Expect request header field can't be met by the server. 228 | */ 229 | EXPECTATION_FAILED: 417, 230 | /** 231 | * Official Documentation @ https://tools.ietf.org/html/rfc2324#section-2.3.2 232 | * 233 | * 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. 234 | */ 235 | IM_A_TEAPOT: 418, 236 | /** 237 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6 238 | * 239 | * 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. 240 | */ 241 | INSUFFICIENT_SPACE_ON_RESOURCE: 419, 242 | /** 243 | * @deprecated 244 | * Official Documentation @ https://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt 245 | * 246 | * A deprecated response used by the Spring Framework when a method has failed. 247 | */ 248 | METHOD_FAILURE: 420, 249 | /** 250 | * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7540#section-9.1.2 251 | * 252 | * 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. 253 | */ 254 | MISDIRECTED_REQUEST: 421, 255 | /** 256 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.3 257 | * 258 | * The request was well-formed but was unable to be followed due to semantic errors. 259 | */ 260 | UNPROCESSABLE_ENTITY: 422, 261 | /** 262 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.4 263 | * 264 | * The resource that is being accessed is locked. 265 | */ 266 | LOCKED: 423, 267 | /** 268 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.5 269 | * 270 | * The request failed due to failure of a previous request. 271 | */ 272 | FAILED_DEPENDENCY: 424, 273 | /** 274 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-3 275 | * 276 | * 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. 277 | */ 278 | PRECONDITION_REQUIRED: 428, 279 | /** 280 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-4 281 | * 282 | * The user has sent too many requests in a given amount of time ("rate limiting"). 283 | */ 284 | TOO_MANY_REQUESTS: 429, 285 | /** 286 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-5 287 | * 288 | * 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. 289 | */ 290 | REQUEST_HEADER_FIELDS_TOO_LARGE: 431, 291 | /** 292 | * Official Documentation @ https://tools.ietf.org/html/rfc7725 293 | * 294 | * The user-agent requested a resource that cannot legally be provided, such as a web page censored by a government. 295 | */ 296 | UNAVAILABLE_FOR_LEGAL_REASONS: 451, 297 | /** 298 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.1 299 | * 300 | * The server encountered an unexpected condition that prevented it from fulfilling the request. 301 | */ 302 | INTERNAL_SERVER_ERROR: 500, 303 | /** 304 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.2 305 | * 306 | * 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. 307 | */ 308 | NOT_IMPLEMENTED: 501, 309 | /** 310 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.3 311 | * 312 | * 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. 313 | */ 314 | BAD_GATEWAY: 502, 315 | /** 316 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.4 317 | * 318 | * 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. 319 | */ 320 | SERVICE_UNAVAILABLE: 503, 321 | /** 322 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.5 323 | * 324 | * This error response is given when the server is acting as a gateway and cannot get a response in time. 325 | */ 326 | GATEWAY_TIMEOUT: 504, 327 | /** 328 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.6 329 | * 330 | * The HTTP version used in the request is not supported by the server. 331 | */ 332 | HTTP_VERSION_NOT_SUPPORTED: 505, 333 | /** 334 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6 335 | * 336 | * 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. 337 | */ 338 | INSUFFICIENT_STORAGE: 507, 339 | /** 340 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-6 341 | * 342 | * The 511 status code indicates that the client needs to authenticate to gain network access. 343 | */ 344 | NETWORK_AUTHENTICATION_REQUIRED: 511, 345 | }; 346 | -------------------------------------------------------------------------------- /service-search-elastic/src/cores/error.response.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* IMPORT 4 | const { StatusCodes, ReasonPhrases } = require('../common/utils/httpStatusCode'); 5 | const logger = require('../loggers/winston.log'); 6 | class ErrorResponse extends Error { 7 | constructor(message, status) { 8 | super(message); 9 | this.status = status; 10 | 11 | // Log error 12 | logger.error(`${this.status} = ${this.message}`); 13 | } 14 | } 15 | class BadRequestRequestError extends ErrorResponse { 16 | constructor(message = ReasonPhrases.BAD_REQUEST, statusCode = StatusCodes.BAD_REQUEST) { 17 | super(message, statusCode); 18 | } 19 | } 20 | 21 | class NotFoundError extends ErrorResponse { 22 | constructor(message = ReasonPhrases.NOT_FOUND, statusCode = StatusCodes.NOT_FOUND) { 23 | super(message, statusCode); 24 | } 25 | } 26 | class InternalServerError extends ErrorResponse { 27 | constructor(message = ReasonPhrases.INTERNAL_SERVER_ERROR, statusCode = StatusCodes.INTERNAL_SERVER_ERROR) { 28 | super(message, statusCode); 29 | } 30 | } 31 | module.exports = { 32 | BadRequestRequestError, 33 | InternalServerError, 34 | NotFoundError, 35 | }; 36 | -------------------------------------------------------------------------------- /service-search-elastic/src/cores/success.response.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* IMPORT 4 | const { StatusCodes, ReasonPhrases } = require('../common/utils/httpStatusCode'); 5 | 6 | class SuccessResponse { 7 | constructor({ message, statusCode = StatusCodes.OK, reasonStatusCode = ReasonPhrases.OK, metadata = {} }) { 8 | this.message = !message ? reasonStatusCode : message; 9 | this.status = statusCode; 10 | this.metadata = metadata; 11 | } 12 | 13 | send(res, _ = {}) { 14 | return res.status(this.status).json(this); 15 | } 16 | } 17 | 18 | class Ok extends SuccessResponse { 19 | constructor({ message, metadata }) { 20 | super({ message, metadata }); 21 | } 22 | } 23 | 24 | class Created extends SuccessResponse { 25 | constructor({ 26 | option = {}, 27 | message, 28 | statusCode = StatusCodes.CREATED, 29 | reasonStatusCode = ReasonPhrases.CREATED, 30 | metadata = {}, 31 | }) { 32 | super({ message, statusCode, reasonStatusCode, metadata }); 33 | this.option = option; 34 | } 35 | } 36 | module.exports = { 37 | Ok, 38 | Created, 39 | SuccessResponse, 40 | }; 41 | -------------------------------------------------------------------------------- /service-search-elastic/src/dbs/index.js: -------------------------------------------------------------------------------- 1 | //* LIB 2 | const { Client } = require('@elastic/elasticsearch'); 3 | 4 | //* IMPORT 5 | const { NameIndex } = require('../common/index/cars'); 6 | 7 | const client = new Client({ 8 | node: process.env.CONNECT_ELASTICSEARCH, 9 | }); 10 | 11 | createCarsIndex = async () => { 12 | const indexName = NameIndex; 13 | 14 | try { 15 | const indexExists = await client.indices.exists({ 16 | index: indexName, 17 | }); 18 | 19 | if (indexExists) { 20 | console.info(`Index "${indexName}" already exists.`); 21 | } else { 22 | await client.indices.create({ 23 | index: indexName, 24 | body: { 25 | mappings: { 26 | properties: { 27 | make: { type: 'text' }, 28 | model: { type: 'text' }, 29 | image: { type: 'text' }, 30 | description: { type: 'text' }, 31 | }, 32 | }, 33 | }, 34 | }); 35 | console.info(`Index "${indexName}" created successfully.`); 36 | } 37 | } catch (error) { 38 | console.error('Error checking/creating index:', error); 39 | } 40 | }; 41 | 42 | createCarsIndex(); 43 | 44 | module.exports = client; 45 | -------------------------------------------------------------------------------- /service-search-elastic/src/loggers/winston.log.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* LIB 4 | const path = require('path'); 5 | const winston = require('winston'); 6 | 7 | const { combine, timestamp, align, printf } = winston.format; 8 | const logsDirectory = path.join(__dirname, '../logs'); // Use an absolute path 9 | 10 | const logger = winston.createLogger({ 11 | level: process.env.LOG_LEVEL || 'debug', 12 | format: combine( 13 | timestamp({ 14 | format: 'YYYY-MM-DD hh:mm:ss.SSS A', 15 | }), 16 | align(), 17 | printf((info) => `[${info.timestamp}] ${info.level.toUpperCase()}: ${info.message}`), 18 | ), 19 | transports: [ 20 | new winston.transports.Console(), 21 | new winston.transports.File({ dirname: logsDirectory, filename: 'test.log' }), 22 | ], 23 | }); 24 | 25 | module.exports = logger; 26 | -------------------------------------------------------------------------------- /service-search-elastic/src/middlewares/rateLimitMiddleware.js: -------------------------------------------------------------------------------- 1 | //* LIB 2 | const rateLimit = require('express-rate-limit'); 3 | 4 | //* IMPORT 5 | const { REQUEST } = require('../common/constants'); 6 | const { ReasonPhrases, StatusCodes } = require('../common/utils/httpStatusCode'); 7 | 8 | module.exports = rateLimit({ 9 | windowMs: REQUEST._WINDOW_MS, 10 | max: REQUEST._MAX, 11 | message: { 12 | status: StatusCodes.TOO_MANY_REQUESTS, 13 | message: ReasonPhrases.TOO_MANY_REQUESTS, 14 | }, 15 | standardHeaders: true, 16 | }); 17 | -------------------------------------------------------------------------------- /service-search-redis/.dockerignore: -------------------------------------------------------------------------------- 1 | .git 2 | .github 3 | .vscode 4 | coverage 5 | docs 6 | mock-config 7 | *.sh 8 | .editorconfig 9 | .prettierignore 10 | config.yaml 11 | jest* 12 | npm-debug.log 13 | yarn-error.log 14 | **/*.test.ts 15 | src/test 16 | **/*.pem 17 | 18 | # Data 19 | db_data 20 | minio_data 21 | 22 | # Git 23 | .git 24 | .gitignore 25 | 26 | # Docker 27 | Dockerfile* 28 | docker-compose* 29 | 30 | # NPM dependencies 31 | node_modules 32 | 33 | 34 | # Eslint 35 | .eslintignore 36 | .eslintrc.js 37 | 38 | #prettieri 39 | .prettierignore 40 | .prettierrc 41 | 42 | #unittest 43 | test 44 | *.md 45 | addons 46 | commitlint.config.js 47 | makefile 48 | setup 49 | script -------------------------------------------------------------------------------- /service-search-redis/.env.example: -------------------------------------------------------------------------------- 1 | # APP NODE 2 | NODE_ENV='' 3 | 4 | # MORGAN 5 | MORGAN='' 6 | 7 | # PORT APP 8 | PORT='' 9 | 10 | # REDIS 11 | REDIS_HOST= 12 | REDIS_PORT= 13 | REDIS_PROTOCOL= 14 | 15 | REDIS_MAPPING= 16 | -------------------------------------------------------------------------------- /service-search-redis/.eslintignore: -------------------------------------------------------------------------------- 1 | build/_.js 2 | config/_.js 3 | [Bb]uild* 4 | [Dd]ist* 5 | [Bb]in\* 6 | package-lock.json 7 | docker-compose.yml 8 | 9 | node_modules/ 10 | public/ 11 | build/ 12 | .github/ 13 | *.css 14 | *.svg 15 | *.config.js -------------------------------------------------------------------------------- /service-search-redis/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | env: { 3 | node: true, 4 | commonjs: false, 5 | es2021: true, 6 | }, 7 | 8 | extends: ['eslint:recommended', 'plugin:prettier/recommended', 'plugin:security/recommended-legacy'], 9 | plugins: ['prettier', 'import', 'security', 'promise'], 10 | parserOptions: { 11 | ecmaVersion: 2021, 12 | sourceType: 'module', 13 | }, 14 | rules: { 15 | 'prettier/prettier': ['error'], 16 | quotes: ['error', 'single'], 17 | semi: ['error', 'always'], 18 | 'import/order': [ 19 | 'error', 20 | { 21 | groups: [['builtin', 'external'], 'internal', ['sibling', 'parent'], 'index', 'unknown'], 22 | 'newlines-between': 'always', 23 | alphabetize: { 24 | order: 'asc', 25 | caseInsensitive: true, 26 | }, 27 | pathGroups: [ 28 | { 29 | pattern: '@/**', 30 | group: 'internal', 31 | position: 'after', 32 | }, 33 | ], 34 | pathGroupsExcludedImportTypes: ['builtin'], 35 | }, 36 | ], 37 | 38 | 'no-console': [ 39 | 'error', 40 | { 41 | allow: ['info', 'warn', 'error', 'time', 'timeEnd'], 42 | }, 43 | ], 44 | 'prefer-const': 'warn', 45 | 'max-len': ['error', 200], 46 | 'array-bracket-newline': 'warn', 47 | 'consistent-return': 'error', 48 | eqeqeq: 'error', 49 | 'no-unused-expressions': ['error', { allowTernary: true }], 50 | 'no-unused-vars': [ 51 | 'error', 52 | { 53 | varsIgnorePattern: '^_', 54 | argsIgnorePattern: '^_', 55 | vars: 'all', 56 | args: 'after-used', 57 | ignoreRestSiblings: false, 58 | }, 59 | ], 60 | 61 | 'operator-linebreak': [ 62 | 'error', 63 | 'after', 64 | { overrides: { '?': 'before', ':': 'before', '&&': 'before', '||': 'before' } }, 65 | ], 66 | 67 | 'linebreak-style': ['error', process.platform === 'win64' && 'win32' ? 'windows' : 'unix'], 68 | 69 | 'no-plusplus': ['error', { allowForLoopAfterthoughts: true }], 70 | 71 | 'arrow-parens': ['error', 'always'], 72 | 73 | 'lines-between-class-members': ['error', 'always', { exceptAfterSingleLine: true }], 74 | 75 | 'no-extra-parens': 'error', 76 | 'no-return-await': 'error', 77 | 'no-duplicate-imports': 'error', 78 | 79 | 'no-undef': 'off', 80 | 81 | 'security/detect-non-literal-fs-filename': 'error', 82 | 'security/detect-object-injection': 'error', 83 | 84 | 'promise/always-return': 'error', 85 | 'promise/no-return-wrap': 'error', 86 | 'promise/param-names': 'error', 87 | 'promise/catch-or-return': 'error', 88 | 'promise/no-native': 'off', 89 | 'promise/no-nesting': 'warn', 90 | 'promise/no-promise-in-callback': 'warn', 91 | 'promise/no-callback-in-promise': 'warn', 92 | 'promise/avoid-new': 'warn', 93 | 'promise/no-new-statics': 'error', 94 | 'promise/no-return-in-finally': 'warn', 95 | 'promise/valid-params': 'warn', 96 | }, 97 | }; 98 | -------------------------------------------------------------------------------- /service-search-redis/.gitattributes: -------------------------------------------------------------------------------- 1 | # Handle line endings automatically for files detected as text 2 | # and leave all files detected as binary untouched. 3 | * text=false 4 | 5 | # 6 | # The above will handle all files NOT found below 7 | # 8 | # These files are text and should be normalized (Convert crlf => lf) 9 | *.df eol=lf 10 | *.html eol=lf 11 | *.java eol=lf 12 | *.json eol=lf 13 | *.jsp eol=lf 14 | *.jspf eol=lf 15 | *.jspx eol=lf 16 | *.properties eol=lf 17 | *.sh eol=lf 18 | *.tld eol=lf 19 | *.ts eol=lf 20 | *.txt eol=lf 21 | *.tag eol=lf 22 | *.tagx eol=lf 23 | *.xml eol=lf 24 | *.yml eol=lf 25 | *.env eol=lf 26 | 27 | .gitignore eol=lf 28 | .gitattributes eol=lf 29 | .eslintignore eol=lf 30 | .prettierignore eol=lf 31 | .js eol=lf 32 | .css eol=lf 33 | .htm eol=lf 34 | 35 | 36 | 37 | # These files are binary and should be left untouched 38 | # (binary is a macro for -text -diff) 39 | *.class binary 40 | *.dll binary 41 | *.ear binary 42 | *.gif binary 43 | *.ico binary 44 | *.jar binary 45 | *.jpg binary 46 | *.jpeg binary 47 | *.png binary 48 | *.so binary 49 | *.war binary -------------------------------------------------------------------------------- /service-search-redis/.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | *.log 3 | npm-debug.log* 4 | yarn-debug.log* 5 | yarn-error.log* 6 | pnpm-debug.log* 7 | lerna-debug.log* 8 | 9 | dist-ssr 10 | *.local 11 | 12 | # Editor directories and files 13 | # .vscode/* 14 | !.vscode/extensions.json 15 | .idea 16 | .DS_Store 17 | *.suo 18 | *.ntvs* 19 | *.njsproj 20 | *.sln 21 | *.sw? 22 | 23 | package-lock.json 24 | yarn.lock 25 | .env 26 | 27 | 28 | node_modules 29 | .env 30 | redis-master 31 | redis-slave 32 | docker-entrypoint-initdb.d 33 | setup 34 | file 35 | script/log_script_redis_date.txt 36 | script/.env 37 | test/jest/.env 38 | 39 | redis -------------------------------------------------------------------------------- /service-search-redis/.prettierignore: -------------------------------------------------------------------------------- 1 | package.json 2 | package-lock.json 3 | public 4 | node_modules 5 | build 6 | .github 7 | -------------------------------------------------------------------------------- /service-search-redis/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "arrowParens": "always", 3 | "bracketSameLine": false, 4 | "bracketSpacing": true, 5 | "embeddedLanguageFormatting": "auto", 6 | "insertPragma": false, 7 | "jsxSingleQuote": false, 8 | "printWidth": 120, 9 | "proseWrap": "preserve", 10 | "quoteProps": "as-needed", 11 | "requirePragma": false, 12 | "semi": true, 13 | "singleQuote": true, 14 | "tabWidth": 4, 15 | "trailingComma": "all", 16 | "useTabs": false, 17 | "vueIndentScriptAndStyle": false, 18 | "endOfLine": "lf" 19 | } 20 | -------------------------------------------------------------------------------- /service-search-redis/README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | Linkedin 5 | Profile 6 | Phone 7 | License 8 |

9 | 10 | ## Project: Service Search 11 | 12 | ## Team Word: Liên hệ công việc https://profile-forme.com 13 | 14 | ## 1. Nguyen Tien Tai( MainTain 🚩). 15 | 16 | ## Tài Khoản Donate li Cf để có động lực code cho anh em tham khảo 😄. 17 | 18 | ![giphy](https://3.bp.blogspot.com/-SzGvXn2sTmw/V6k-90GH3ZI/AAAAAAAAIsk/Q678Pil-0kITLPa3fD--JkNdnJVKi_BygCLcB/s1600/cf10-fbc08%2B%25281%2529.gif) 19 | 20 | ## Mk: NGUYEN TIEN TAI 21 | 22 | ## STK: 1651002972052 23 | 24 | ## Chi Nhánh: NGAN HANG TMCP AN BINH (ABBANK). 25 | 26 | ## SUPPORT CONTACT: [https://profile-forme.com](https://profile-forme.com) 27 | 28 | ## Thank You <3. 29 | -------------------------------------------------------------------------------- /service-search-redis/docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: '3.8' 2 | services: 3 | # Todo: 1. Service Search 4 | service_search: 5 | container_name: service_search 6 | depends_on: 7 | - redis-search 8 | restart: always 9 | build: 10 | context: . 11 | dockerfile: ./docker/Dockerfile 12 | environment: 13 | - NODE_ENV=${NODE_ENV} 14 | ports: 15 | - ${PORT}:${PORT} 16 | volumes: 17 | - './src:/usr/src/app/src' 18 | env_file: 19 | - .env 20 | command: yarn dev 21 | networks: 22 | - service_search_service-network 23 | 24 | # Todo: 2. Redis search 25 | redis-search: 26 | container_name: redis-search 27 | build: 28 | context: ./docker 29 | dockerfile: Dockerfile-redis 30 | restart: always 31 | env_file: 32 | - .env 33 | command: sh /data/import-data.sh 34 | ports: 35 | - ${REDIS_PORT}:${REDIS_PORT} 36 | networks: 37 | - service_search_service-network 38 | healthcheck: 39 | test: ['CMD', 'redis-cli', 'ping'] 40 | interval: 30s 41 | timeout: 10s 42 | retries: 5 43 | networks: 44 | service_search_service-network: 45 | driver: bridge 46 | -------------------------------------------------------------------------------- /service-search-redis/docker/Dockerfile: -------------------------------------------------------------------------------- 1 | # Stage 1: Builder 2 | FROM node:18-alpine as builder 3 | 4 | 5 | # Create folder if it not exits 6 | RUN mkdir -p /usr/src/app 7 | 8 | WORKDIR /usr/src/app 9 | 10 | COPY package.json ./ 11 | RUN yarn install --no-optional && \ 12 | yarn cache clean 13 | 14 | COPY . . 15 | 16 | USER root 17 | 18 | # Define available eviroment with port 19 | ARG PORT 20 | ENV PORT $PORT 21 | 22 | # Stage 2: Final 23 | FROM node:18-alpine as final 24 | 25 | # Set the working directory to /usr/src/app 26 | WORKDIR /usr/src/app 27 | 28 | # Copy các tệp từ stage builder 29 | COPY --from=builder /usr/src/app . 30 | 31 | # Setting user not must is root 32 | USER node 33 | 34 | # Expose port 35 | EXPOSE $PORT 36 | 37 | # Check heal of applycation 38 | HEALTHCHECK --interval=60s --timeout=2s --retries=3 CMD sh -c "wget localhost:${PORT}/api/v1 -q -O - > /dev/null 2>&1" 39 | 40 | # Command run applycation 41 | CMD ["yarn", "dev"] 42 | -------------------------------------------------------------------------------- /service-search-redis/docker/Dockerfile-redis: -------------------------------------------------------------------------------- 1 | FROM redislabs/redisearch:latest 2 | 3 | COPY import-data.sh /data/import-data.sh 4 | 5 | COPY ./dataset/import_actors.redis /data/import_actors.redis 6 | COPY ./dataset/import_movies.redis /data/import_movies.redis 7 | COPY ./dataset/import_create_index.redis /data/import_create_index.redis -------------------------------------------------------------------------------- /service-search-redis/docker/dataset/import_create_index.redis: -------------------------------------------------------------------------------- 1 | 2 | FT.CREATE idx:movie ON hash PREFIX 1 "movie:" SCHEMA title TEXT SORTABLE plot TEXT release_year NUMERIC SORTABLE rating NUMERIC SORTABLE genre TAG SORTABLE 3 | 4 | FT.CREATE idx:actor ON hash PREFIX 1 "actor:" SCHEMA first_name TEXT SORTABLE last_name TEXT SORTABLE date_of_birth NUMERIC SORTABLE 5 | 6 | FT.CREATE idx:user ON hash PREFIX 1 "user:" SCHEMA gender TAG country TAG SORTABLE last_login NUMERIC SORTABLE location GEO 7 | 8 | FT.CREATE idx:comments:movies on HASH PREFIX 1 'comments:' SCHEMA movie_id TAG SORTABLE user_id TEXT SORTABLE comment TEXT WEIGHT 1.0 timestamp NUMERIC SORTABLE rating NUMERIC SORTABLE 9 | -------------------------------------------------------------------------------- /service-search-redis/docker/import-data.sh: -------------------------------------------------------------------------------- 1 | 2 | 3 | redis-server --loadmodule /usr/lib/redis/modules/redisearch.so --daemonize yes && sleep 2 4 | 5 | redis-cli -p 6379 < /data/import_actors.redis 6 | 7 | redis-cli -p 6379 < /data/import_movies.redis 8 | 9 | redis-cli -p 6379 < /data/import_users.redis 10 | 11 | redis-cli -p 6379 < /data/import_create_index.redis 12 | 13 | redis-cli save 14 | 15 | redis-cli shutdown 16 | 17 | redis-server --loadmodule /usr/lib/redis/modules/redisearch.so -------------------------------------------------------------------------------- /service-search-redis/makefile: -------------------------------------------------------------------------------- 1 | # Get file .env 2 | include .env 3 | export $(shell sed 's/=.*//' .env) 4 | 5 | # Folder constants 6 | DOCKER_COMPOSE := docker-compose.yml 7 | DOCKER_EXEC_APP := service_search 8 | DOCKER_EXEC_CACHE := redis-search 9 | 10 | # Run auto 11 | default: 12 | docker ps 13 | 14 | run-build: 15 | docker-compose -f $(DOCKER_COMPOSE) up -d --build 16 | make remove-image-none 17 | 18 | run-dev: 19 | docker-compose -f $(DOCKER_COMPOSE) up -d 20 | 21 | run-down: 22 | docker-compose -f $(DOCKER_COMPOSE) down 23 | 24 | into-source: 25 | docker exec -it $(DOCKER_EXEC_APP) sh 26 | 27 | into-source-redis: 28 | docker exec -it $(DOCKER_EXEC_CACHE) sh 29 | 30 | remove-image-none: 31 | docker images --filter "dangling=true" -q --no-trunc | xargs -r docker rmi || true 32 | 33 | -------------------------------------------------------------------------------- /service-search-redis/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Service-search_Redis", 3 | "version": "0.0.1", 4 | "main": "server.js", 5 | "repository": "git@github.com:fdhhhdjd/Class_Search_Engine", 6 | "author": "fdhhhdjd ", 7 | "type": "commonjs", 8 | "license": "MIT", 9 | "scripts": { 10 | "start": "node server.js", 11 | "dev": "node --watch server.js", 12 | "build": "tsc && vite build", 13 | "preview": "vite preview", 14 | "lint": "eslint . --ext .cjs,.mjs,.js,.cts,.mts --fix --ignore-path .gitignore && echo \"Tai Dev Check Eslint ✅\"", 15 | "lint:fix": "eslint . --fix --ext .js", 16 | "format": "prettier --write src/**/*.{js}" 17 | }, 18 | "engines": { 19 | "node": ">=16.20.1", 20 | "npm": ">= 8.19.4" 21 | }, 22 | "dependencies": { 23 | "body-parser": "^1.20.2", 24 | "compression": "^1.7.4", 25 | "cors": "^2.8.5", 26 | "dotenv": "^16.3.1", 27 | "express": "^4.18.2", 28 | "express-rate-limit": "^7.1.5", 29 | "helmet": "^7.1.0", 30 | "lodash": "^4.17.21", 31 | "morgan": "^1.10.0", 32 | "redis-om": "^0.4.3", 33 | "uuid": "^9.0.1", 34 | "winston": "^3.11.0" 35 | }, 36 | "devDependencies": { 37 | "eslint": "^8.56.0", 38 | "eslint-config-prettier": "^9.0.0", 39 | "eslint-import-resolver-alias": "^1.1.2", 40 | "eslint-plugin-import": "^2.29.1", 41 | "eslint-plugin-prettier": "^5.0.1", 42 | "eslint-plugin-promise": "^6.1.1", 43 | "eslint-plugin-security": "^2.1.0", 44 | "prettier": "^3.0.3" 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /service-search-redis/server.js: -------------------------------------------------------------------------------- 1 | //* IMPORT 2 | const app = require('./src/app'); 3 | const { 4 | app: { port: PORT }, 5 | } = require('./src/common/configs/app.config'); 6 | 7 | const server = app.listen(PORT, () => { 8 | console.info(`Api backend start with http://localhost:${PORT}`); 9 | }); 10 | 11 | process.on('SIGINT', () => { 12 | server.close(() => console.info('Exit Server Express')); 13 | }); 14 | -------------------------------------------------------------------------------- /service-search-redis/src/app.js: -------------------------------------------------------------------------------- 1 | //* LIB 2 | const compression = require('compression'); 3 | const cors = require('cors'); 4 | const express = require('express'); 5 | const { default: helmet } = require('helmet'); 6 | const morgan = require('morgan'); 7 | 8 | const app = express(); 9 | require('dotenv').config(); 10 | 11 | //* IMPORT 12 | const { 13 | app: { morgan: morganConfig, node }, 14 | } = require('./common/configs/app.config'); 15 | const { 16 | cache: { redisMaster }, 17 | } = require('./common/configs/redis.config'); 18 | const { NODE_ENV, LIMIT } = require('./common/constants'); 19 | const { StatusCodes, ReasonPhrases } = require('./common/utils/httpStatusCode'); 20 | const redisConnection = require('./dbs'); 21 | const RateLimitIp = require('./middlewares/rateLimitMiddleware'); 22 | 23 | app.use(morgan(morganConfig)); 24 | app.enable(); 25 | app.use(cors()); 26 | app.use(helmet()); 27 | app.use(compression()); 28 | app.use( 29 | express.json({ 30 | limit: LIMIT._5_MB, 31 | }), 32 | ); 33 | app.use(RateLimitIp); 34 | app.use( 35 | express.urlencoded({ 36 | extended: true, 37 | }), 38 | ); 39 | 40 | const initializeRedis = async () => { 41 | try { 42 | await redisConnection.createConnection(`${redisMaster.protocol}://${redisMaster.host}:${redisMaster.port}`); 43 | } catch (error) { 44 | console.error('Error connecting to Redis:', error); 45 | } 46 | }; 47 | 48 | initializeRedis(); 49 | 50 | //* V1 51 | app.use('/api', require('./app/v1/routes')); 52 | 53 | //* Error 54 | app.use((_, __, next) => { 55 | const ErrorCode = new Error(StatusCodes.NOT_FOUND); 56 | ErrorCode.status = StatusCodes.NOT_FOUND; 57 | return next(ErrorCode); 58 | }); 59 | 60 | app.use((error, _, res, __) => { 61 | const statusCode = error.status || StatusCodes.INTERNAL_SERVER_ERROR; 62 | const message = error.message || ReasonPhrases.INTERNAL_SERVER_ERROR; 63 | 64 | const response = { 65 | message, 66 | status: statusCode, 67 | }; 68 | 69 | const checkNodeApp = node === NODE_ENV.DEV; 70 | if (checkNodeApp) { 71 | Object.assign(response, { stack: error.stack }); 72 | } 73 | 74 | return res.status(statusCode).json(response); 75 | }); 76 | 77 | module.exports = app; 78 | -------------------------------------------------------------------------------- /service-search-redis/src/app/v1/controllers/car.controller.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* IMPORT 4 | const { SuccessResponse, Created } = require('../../../cores/success.response'); 5 | const CarService = require('../services/car.service'); 6 | 7 | class CarControllers { 8 | async searchAll(req, res, __) { 9 | const query = req.query.q; 10 | new SuccessResponse({ 11 | message: 'Search success.', 12 | metadata: await CarService.searchAll({ query }), 13 | }).send(res); 14 | } 15 | 16 | async getAllCars(_, res, __) { 17 | new SuccessResponse({ 18 | message: 'Get All Cars success.', 19 | metadata: await CarService.getAllCars(), 20 | }).send(res); 21 | } 22 | 23 | async searchAllIndex(req, res, __) { 24 | const { idx, query } = req.body; 25 | 26 | new SuccessResponse({ 27 | message: `Query ${idx} success.`, 28 | metadata: await CarService.searchAllIndex({ idx, query }), 29 | }).send(res); 30 | } 31 | 32 | async getDetailId(req, res, __) { 33 | const id = req.params.id; 34 | new SuccessResponse({ 35 | message: 'Get detail todo success.', 36 | metadata: await CarService.getDetailId({ id }), 37 | }).send(res); 38 | } 39 | 40 | async create(req, res, __) { 41 | new Created({ 42 | message: 'Create todo success.', 43 | metadata: await CarService.create(req.body), 44 | }).send(res); 45 | } 46 | 47 | async update(req, res, __) { 48 | new SuccessResponse({ 49 | message: 'Update todo success', 50 | metadata: await CarService.update(req.body), 51 | }).send(res); 52 | } 53 | 54 | async delete(req, res, __) { 55 | const id = req.params.id; 56 | 57 | new SuccessResponse({ 58 | message: 'Delete todo success.', 59 | metadata: await CarService.delete({ id }), 60 | }).send(res); 61 | } 62 | 63 | async expired(req, res, __) { 64 | const id = req.params.id; 65 | 66 | new SuccessResponse({ 67 | message: 'Expire todo success.', 68 | metadata: await CarService.expired({ id }), 69 | }).send(res); 70 | } 71 | } 72 | 73 | module.exports = new CarControllers(); 74 | -------------------------------------------------------------------------------- /service-search-redis/src/app/v1/controllers/movie.controller.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* IMPORT 4 | const { SuccessResponse } = require('../../../cores/success.response'); 5 | const MovieService = require('../services/movie.service'); 6 | 7 | class MovieControllers { 8 | async searchMovieAllIndex(req, res, __) { 9 | const { idx, query } = req.query; 10 | 11 | new SuccessResponse({ 12 | message: `Query ${idx} success.`, 13 | metadata: await MovieService.searchMovieAllIndex({ idx, query }), 14 | }).send(res); 15 | } 16 | 17 | async searchActorAllIndex(req, res, __) { 18 | const { idx, query } = req.params; 19 | 20 | new SuccessResponse({ 21 | message: `Query ${idx} success.`, 22 | metadata: await MovieService.searchActorAllIndex({ idx, query }), 23 | }).send(res); 24 | } 25 | } 26 | 27 | module.exports = new MovieControllers(); 28 | -------------------------------------------------------------------------------- /service-search-redis/src/app/v1/models/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fdhhhdjd/Class_Search_Engine/16d30bafdf33febce9556353981efc86c488899d/service-search-redis/src/app/v1/models/.gitkeep -------------------------------------------------------------------------------- /service-search-redis/src/app/v1/models/schemas/car.schema.js: -------------------------------------------------------------------------------- 1 | //* LIB 2 | const { Schema, Repository } = require('redis-om'); 3 | const { v4: uuidv4 } = require('uuid'); 4 | 5 | //* IMPORT 6 | const { Car, NameIndex } = require('../../../../common/cache/cart'); 7 | const redisClient = require('../../../../dbs/client'); 8 | 9 | const myIDGeneratorFunc = () => uuidv4(); 10 | 11 | const carSchema = new Schema( 12 | 'cart', 13 | { 14 | id: { type: 'string', auto: true }, 15 | make: { type: 'string', sortable: true }, 16 | model: { type: 'string' }, 17 | image: { type: 'string' }, 18 | description: { type: 'text', textSearch: true, normalized: true }, 19 | }, 20 | { 21 | dataStructure: 'HASH', 22 | prefix: 'cart', 23 | idStrategy: myIDGeneratorFunc, 24 | indexHashName: Car, 25 | indexName: NameIndex, 26 | stopWords: ['a', 'an', 'the'], 27 | }, 28 | ); 29 | 30 | const carRepository = new Repository(carSchema, redisClient); 31 | 32 | module.exports = carRepository; 33 | -------------------------------------------------------------------------------- /service-search-redis/src/app/v1/routes/cars/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* LIB 4 | const express = require('express'); 5 | const router = express.Router(); 6 | 7 | //* IMPORT 8 | const { asyncHandler } = require('../../../../common/helpers/asyncHandler'); 9 | const CarControllers = require('../../controllers/car.controller'); 10 | 11 | // Todo 1. Search much 12 | router.get('/search', asyncHandler(CarControllers.searchAll)); 13 | 14 | // Todo 2. Get all 15 | router.get('/get/all', asyncHandler(CarControllers.getAllCars)); 16 | 17 | // Todo 3. Search much index not follow 18 | router.post('/search/idx', asyncHandler(CarControllers.searchAllIndex)); 19 | 20 | // Todo 4. Get detail 21 | router.get('/:id', asyncHandler(CarControllers.getDetailId)); 22 | 23 | // Todo 5. Create 24 | router.post('/create', asyncHandler(CarControllers.create)); 25 | 26 | // Todo 6. Update 27 | router.patch('/update', asyncHandler(CarControllers.update)); 28 | 29 | // Todo 7. Delete 30 | router.delete('/delete/:id', asyncHandler(CarControllers.delete)); 31 | 32 | // Todo 8. Set Expire 33 | router.get('/expire/:id', asyncHandler(CarControllers.expired)); 34 | 35 | module.exports = router; 36 | -------------------------------------------------------------------------------- /service-search-redis/src/app/v1/routes/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* LIB 4 | const express = require('express'); 5 | 6 | //* IMPORT 7 | const { Car } = require('../../../common/cache/cart'); 8 | const { StatusCodes, ReasonPhrases } = require('../../../common/utils/httpStatusCode'); 9 | const redisClient = require('../../../dbs/client'); 10 | 11 | const router = express.Router(); 12 | 13 | // Todo: 1. Cars 14 | router.use('/v1/cars', require('./cars')); 15 | 16 | // Todo: 2 Movie 17 | router.use('/v1/movies', require('./movies')); 18 | 19 | router.get('/v1', async (_, res, __) => { 20 | const dataTestRedis = await redisClient.get(Car); 21 | const healthCheck = { 22 | uptime: process.uptime(), 23 | message: dataTestRedis || ReasonPhrases.OK, 24 | timestamp: Date.now(), 25 | }; 26 | return res.status(StatusCodes.OK).json(healthCheck); 27 | }); 28 | 29 | module.exports = router; 30 | -------------------------------------------------------------------------------- /service-search-redis/src/app/v1/routes/movies/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* LIB 4 | const express = require('express'); 5 | const router = express.Router(); 6 | 7 | //* IMPORT 8 | const { asyncHandler } = require('../../../../common/helpers/asyncHandler'); 9 | const MovieControllers = require('../../controllers/movie.controller'); 10 | 11 | // Todo 1. Search much index movie 12 | router.get('/search/idx', asyncHandler(MovieControllers.searchMovieAllIndex)); 13 | 14 | // Todo 2. Search much index actor 15 | router.get('/search/actor/idx', asyncHandler(MovieControllers.searchActorAllIndex)); 16 | 17 | module.exports = router; 18 | -------------------------------------------------------------------------------- /service-search-redis/src/app/v1/services/car.service.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable security/detect-object-injection */ 2 | 'use strict'; 3 | 4 | const { EntityId } = require('redis-om'); 5 | 6 | //* IMPORT 7 | const { BadRequestRequestError } = require('../../../cores/error.response'); 8 | const redisClient = require('../../../dbs/client'); 9 | const carRepository = require('../models/schemas/car.schema'); 10 | 11 | class CarService { 12 | static async searchAll({ query }) { 13 | // Search follow make and model 14 | const searchQuery = carRepository 15 | .search() 16 | .where('make') 17 | .equals(`*${query}*`) 18 | .or((search) => search.where('model').equals(`*${query}*`)); 19 | 20 | const count = await searchQuery.count(); 21 | 22 | const cars = await searchQuery.return.all(); 23 | 24 | return { count, cars }; 25 | } 26 | 27 | static async getAllCars() { 28 | const searchQuery = carRepository.search(); 29 | 30 | // Count the total number of results 31 | const count = await searchQuery.count(); 32 | 33 | // Retrieve all results without any search condition 34 | const cars = await searchQuery.return.all(); 35 | 36 | return { count, cars }; 37 | } 38 | 39 | static async searchAllIndex({ idx, query }) { 40 | if (!idx || !query) throw new BadRequestRequestError(); 41 | 42 | const searchResults = await redisClient.search(idx, `%${query}%`); 43 | 44 | return searchResults; 45 | } 46 | 47 | static async getDetailId({ id }) { 48 | const car = await carRepository.fetch(id); 49 | return car; 50 | } 51 | 52 | static async create({ make, model, image, description }) { 53 | await carRepository.createIndex(); 54 | 55 | const car = await carRepository.save({ make, model, image, description }); 56 | 57 | Object.assign(car, { id: car?.[EntityId] }); 58 | 59 | await carRepository.save(car); 60 | 61 | return car; 62 | } 63 | 64 | static async update({ id, make, model, image, description }) { 65 | const car = await carRepository.fetch(id); 66 | 67 | Object.assign(car, { id, make, model, image, description }); 68 | 69 | await carRepository.save(car); 70 | 71 | return car; 72 | } 73 | 74 | static async delete({ id }) { 75 | const hadRemoveIndex = await carRepository.remove(id); 76 | 77 | return hadRemoveIndex; 78 | } 79 | 80 | static async expired({ id }) { 81 | const ttlInSeconds = 12 * 60 * 60; // 12 hours 82 | 83 | carRepository.expire(id, ttlInSeconds); 84 | return 'Ok'; 85 | } 86 | } 87 | 88 | module.exports = CarService; 89 | -------------------------------------------------------------------------------- /service-search-redis/src/app/v1/services/movie.service.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* IMPORT 4 | const { BadRequestRequestError } = require('../../../cores/error.response'); 5 | const redisClient = require('../../../dbs/client'); 6 | 7 | class MovieService { 8 | static async searchMovieAllIndex({ idx, query }) { 9 | if (!idx) throw new BadRequestRequestError(); 10 | 11 | const formattedQuery = `%${!query ? 't' : query}%`; 12 | const formattedIndex = `${idx}`; 13 | 14 | const searchResults = await redisClient.search(formattedIndex, `@title:${formattedQuery}`); 15 | 16 | return searchResults; 17 | } 18 | 19 | static async searchActorAllIndex({ idx, query }) { 20 | if (!idx || !query) throw new BadRequestRequestError(); 21 | 22 | const searchResults = await redisClient.search(idx, `%${query}%`); 23 | 24 | return searchResults; 25 | } 26 | } 27 | 28 | module.exports = MovieService; 29 | -------------------------------------------------------------------------------- /service-search-redis/src/common/cache/cart.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | Car: 'cart:index:hash', 3 | NameIndex: 'cart:search', 4 | }; 5 | -------------------------------------------------------------------------------- /service-search-redis/src/common/configs/app.config.js: -------------------------------------------------------------------------------- 1 | const DEV = { 2 | app: { 3 | port: process.env.PORT || 5000, 4 | morgan: process.env.MORGAN || 'dev', 5 | node: process.env.NODE_ENV, 6 | web_server: process.env.WEB_SERVER, 7 | }, 8 | }; 9 | const PRO = { 10 | app: { 11 | port: process.env.PORT || 5000, 12 | morgan: process.env.MORGAN || 'combined', 13 | node: process.env.NODE_ENV, 14 | web_server: process.env.WEB_SERVER, 15 | }, 16 | }; 17 | const config = { DEV, PRO }; 18 | 19 | const env = process.env.NODE_ENV || 'DEV'; 20 | 21 | module.exports = config[env]; 22 | -------------------------------------------------------------------------------- /service-search-redis/src/common/configs/redis.config.js: -------------------------------------------------------------------------------- 1 | //* IMPORT 2 | 3 | const DEV = { 4 | cache: { 5 | redisMaster: { 6 | host: process.env.REDIS_HOST, 7 | port: process.env.REDIS_PORT, 8 | protocol: process.env.REDIS_PROTOCOL, 9 | }, 10 | }, 11 | }; 12 | 13 | const PRO = { 14 | cache: { 15 | redisMaster: { 16 | host: process.env.REDIS_HOST, 17 | port: process.env.REDIS_PORT, 18 | user: process.env.REDIS_USER, 19 | password: process.env.REDIS_PASSWORD, 20 | }, 21 | }, 22 | }; 23 | 24 | const configsRedis = { 25 | DEV, 26 | PRO, 27 | }; 28 | 29 | const env = process.env.NODE_ENV || 'DEV'; 30 | 31 | module.exports = configsRedis[env]; 32 | -------------------------------------------------------------------------------- /service-search-redis/src/common/constants/index.js: -------------------------------------------------------------------------------- 1 | const NODE_ENV = { 2 | DEV: 'DEV', 3 | PRO: 'PRO', 4 | }; 5 | 6 | const ENABLE_IP = 'trust proxy'; 7 | 8 | const LIMIT = { 9 | _5_MB: '5mb', 10 | }; 11 | 12 | const REQUEST = { 13 | _WINDOW_MS: 1 * 60 * 1000, 14 | _MAX: 100, 15 | }; 16 | 17 | module.exports = { 18 | NODE_ENV, 19 | ENABLE_IP, 20 | LIMIT, 21 | REQUEST, 22 | }; 23 | -------------------------------------------------------------------------------- /service-search-redis/src/common/helpers/asyncHandler.js: -------------------------------------------------------------------------------- 1 | const asyncHandler = (fn) => { 2 | return (req, res, next) => { 3 | Promise.resolve(fn(req, res, next)).catch((error) => { 4 | next(error); 5 | }); 6 | }; 7 | }; 8 | 9 | module.exports = { asyncHandler }; 10 | -------------------------------------------------------------------------------- /service-search-redis/src/common/helpers/validate/index.js: -------------------------------------------------------------------------------- 1 | //* IMPORT 2 | const { BadRequestRequestError } = require('../../../cores/error.response.js'); 3 | 4 | class ValidationUtils { 5 | static validateField({ value, fieldName, validators }) { 6 | const invalidValidator = validators.find(({ validate }) => !validate(value)); 7 | if (invalidValidator) { 8 | const { message } = invalidValidator; 9 | throw new BadRequestRequestError({ 10 | message: `${fieldName} ${message}`, 11 | }); 12 | } 13 | } 14 | } 15 | 16 | module.exports = ValidationUtils; 17 | -------------------------------------------------------------------------------- /service-search-redis/src/common/helpers/validate/todo.validate.js: -------------------------------------------------------------------------------- 1 | //* IMPORT 2 | const ValidationUtils = require('.'); 3 | 4 | class TodoBuilder { 5 | build() { 6 | throw new Error('Method not implemented.'); 7 | } 8 | 9 | constructor() { 10 | this.id = ''; 11 | this.text = ''; 12 | } 13 | 14 | setId(id) { 15 | this.id = id; 16 | return this; 17 | } 18 | 19 | setText(text) { 20 | this.text = text; 21 | return this; 22 | } 23 | 24 | validateEmptyId(id) { 25 | return id; 26 | } 27 | 28 | validateEmptyText(text) { 29 | return text; 30 | } 31 | } 32 | 33 | class RDBuilder extends TodoBuilder { 34 | build() { 35 | ValidationUtils.validateField({ 36 | value: this.id, 37 | fieldName: 'Id', 38 | validators: [ 39 | { 40 | validate: this.validateEmptyId, 41 | message: 'is invalid', 42 | }, 43 | ], 44 | }); 45 | } 46 | } 47 | 48 | class CUBuilder extends TodoBuilder { 49 | build() { 50 | ValidationUtils.validateField({ 51 | value: this.id, 52 | fieldName: 'Id', 53 | validators: [ 54 | { 55 | validate: this.validateEmptyId, 56 | message: 'is invalid', 57 | }, 58 | ], 59 | }); 60 | ValidationUtils.validateField({ 61 | value: this.text, 62 | fieldName: 'Text', 63 | validators: [ 64 | { 65 | validate: this.validateEmptyText, 66 | message: 'is empty', 67 | }, 68 | ], 69 | }); 70 | } 71 | } 72 | 73 | const RDInputBuilder = new RDBuilder(); 74 | const CUInputBuilder = new CUBuilder(); 75 | 76 | module.exports = { RDInputBuilder, CUInputBuilder }; 77 | -------------------------------------------------------------------------------- /service-search-redis/src/common/utils/httpStatusCode.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | StatusCodes: require('../utils/statusCodes'), 3 | ReasonPhrases: require('../utils/reasonPhrases'), 4 | }; 5 | -------------------------------------------------------------------------------- /service-search-redis/src/common/utils/statusCodes.js: -------------------------------------------------------------------------------- 1 | /* eslint-disable max-len */ 2 | module.exports = { 3 | /** 4 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.1 5 | * 6 | * 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. 7 | */ 8 | CONTINUE: 100, 9 | /** 10 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.2.2 11 | * 12 | * This code is sent in response to an Upgrade request header by the client, and indicates the protocol the server is switching too. 13 | */ 14 | SWITCHING_PROTOCOLS: 101, 15 | /** 16 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.1 17 | * 18 | * This code indicates that the server has received and is processing the request, but no response is available yet. 19 | */ 20 | PROCESSING: 102, 21 | /** 22 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.1 23 | * 24 | * The request has succeeded. The meaning of a success varies depending on the HTTP method: 25 | * GET: The resource has been fetched and is transmitted in the message body. 26 | * HEAD: The entity headers are in the message body. 27 | * POST: The resource describing the result of the action is transmitted in the message body. 28 | * TRACE: The message body contains the request message as received by the server 29 | */ 30 | OK: 200, 31 | /** 32 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.2 33 | * 34 | * 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. 35 | */ 36 | CREATED: 201, 37 | /** 38 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.3 39 | * 40 | * 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. 41 | */ 42 | ACCEPTED: 202, 43 | /** 44 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.4 45 | * 46 | * 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. 47 | */ 48 | NON_AUTHORITATIVE_INFORMATION: 203, 49 | /** 50 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.5 51 | * 52 | * 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. 53 | */ 54 | NO_CONTENT: 204, 55 | /** 56 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.3.6 57 | * 58 | * This response code is sent after accomplishing request to tell user agent reset document view which sent this request. 59 | */ 60 | RESET_CONTENT: 205, 61 | /** 62 | * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.1 63 | * 64 | * This response code is used because of range header sent by the client to separate download into multiple streams. 65 | */ 66 | PARTIAL_CONTENT: 206, 67 | /** 68 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.2 69 | * 70 | * A Multi-Status response conveys information about multiple resources in situations where multiple status codes might be appropriate. 71 | */ 72 | MULTI_STATUS: 207, 73 | /** 74 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.1 75 | * 76 | * 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. 77 | */ 78 | MULTIPLE_CHOICES: 300, 79 | /** 80 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.2 81 | * 82 | * This response code means that URI of requested resource has been changed. Probably, new URI would be given in the response. 83 | */ 84 | MOVED_PERMANENTLY: 301, 85 | /** 86 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.3 87 | * 88 | * 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. 89 | */ 90 | MOVED_TEMPORARILY: 302, 91 | /** 92 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.4 93 | * 94 | * Server sent this response to directing client to get requested resource to another URI with an GET request. 95 | */ 96 | SEE_OTHER: 303, 97 | /** 98 | * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.1 99 | * 100 | * 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. 101 | */ 102 | NOT_MODIFIED: 304, 103 | /** 104 | * @deprecated 105 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.6 106 | * 107 | * 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. 108 | */ 109 | USE_PROXY: 305, 110 | /** 111 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.4.7 112 | * 113 | * 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. 114 | */ 115 | TEMPORARY_REDIRECT: 307, 116 | /** 117 | * Official Documentation @ https://tools.ietf.org/html/rfc7538#section-3 118 | * 119 | * 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. 120 | */ 121 | PERMANENT_REDIRECT: 308, 122 | /** 123 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.1 124 | * 125 | * This response means that server could not understand the request due to invalid syntax. 126 | */ 127 | BAD_REQUEST: 400, 128 | /** 129 | * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.1 130 | * 131 | * Although the HTTP standard specifies "unauthorized", semantically this response means "unauthenticated". That is, the client must authenticate itself to get the requested response. 132 | */ 133 | UNAUTHORIZED: 401, 134 | /** 135 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.2 136 | * 137 | * 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. 138 | */ 139 | PAYMENT_REQUIRED: 402, 140 | /** 141 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.3 142 | * 143 | * 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. 144 | */ 145 | FORBIDDEN: 403, 146 | /** 147 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.4 148 | * 149 | * 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. 150 | */ 151 | NOT_FOUND: 404, 152 | /** 153 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.5 154 | * 155 | * 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. 156 | */ 157 | METHOD_NOT_ALLOWED: 405, 158 | /** 159 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.6 160 | * 161 | * 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. 162 | */ 163 | NOT_ACCEPTABLE: 406, 164 | /** 165 | * Official Documentation @ https://tools.ietf.org/html/rfc7235#section-3.2 166 | * 167 | * This is similar to 401 but authentication is needed to be done by a proxy. 168 | */ 169 | PROXY_AUTHENTICATION_REQUIRED: 407, 170 | /** 171 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.7 172 | * 173 | * 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. 174 | */ 175 | REQUEST_TIMEOUT: 408, 176 | /** 177 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.8 178 | * 179 | * This response is sent when a request conflicts with the current state of the server. 180 | */ 181 | CONFLICT: 409, 182 | /** 183 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.9 184 | * 185 | * 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. 186 | */ 187 | GONE: 410, 188 | /** 189 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.10 190 | * 191 | * The server rejected the request because the Content-Length header field is not defined and the server requires it. 192 | */ 193 | LENGTH_REQUIRED: 411, 194 | /** 195 | * Official Documentation @ https://tools.ietf.org/html/rfc7232#section-4.2 196 | * 197 | * The client has indicated preconditions in its headers which the server does not meet. 198 | */ 199 | PRECONDITION_FAILED: 412, 200 | /** 201 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.11 202 | * 203 | * Request entity is larger than limits defined by server; the server might close the connection or return an Retry-After header field. 204 | */ 205 | REQUEST_TOO_LONG: 413, 206 | /** 207 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.12 208 | * 209 | * The URI requested by the client is longer than the server is willing to interpret. 210 | */ 211 | REQUEST_URI_TOO_LONG: 414, 212 | /** 213 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.13 214 | * 215 | * The media format of the requested data is not supported by the server, so the server is rejecting the request. 216 | */ 217 | UNSUPPORTED_MEDIA_TYPE: 415, 218 | /** 219 | * Official Documentation @ https://tools.ietf.org/html/rfc7233#section-4.4 220 | * 221 | * 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. 222 | */ 223 | REQUESTED_RANGE_NOT_SATISFIABLE: 416, 224 | /** 225 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.5.14 226 | * 227 | * This response code means the expectation indicated by the Expect request header field can't be met by the server. 228 | */ 229 | EXPECTATION_FAILED: 417, 230 | /** 231 | * Official Documentation @ https://tools.ietf.org/html/rfc2324#section-2.3.2 232 | * 233 | * 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. 234 | */ 235 | IM_A_TEAPOT: 418, 236 | /** 237 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6 238 | * 239 | * 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. 240 | */ 241 | INSUFFICIENT_SPACE_ON_RESOURCE: 419, 242 | /** 243 | * @deprecated 244 | * Official Documentation @ https://tools.ietf.org/rfcdiff?difftype=--hwdiff&url2=draft-ietf-webdav-protocol-06.txt 245 | * 246 | * A deprecated response used by the Spring Framework when a method has failed. 247 | */ 248 | METHOD_FAILURE: 420, 249 | /** 250 | * Official Documentation @ https://datatracker.ietf.org/doc/html/rfc7540#section-9.1.2 251 | * 252 | * 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. 253 | */ 254 | MISDIRECTED_REQUEST: 421, 255 | /** 256 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.3 257 | * 258 | * The request was well-formed but was unable to be followed due to semantic errors. 259 | */ 260 | UNPROCESSABLE_ENTITY: 422, 261 | /** 262 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.4 263 | * 264 | * The resource that is being accessed is locked. 265 | */ 266 | LOCKED: 423, 267 | /** 268 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.5 269 | * 270 | * The request failed due to failure of a previous request. 271 | */ 272 | FAILED_DEPENDENCY: 424, 273 | /** 274 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-3 275 | * 276 | * 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. 277 | */ 278 | PRECONDITION_REQUIRED: 428, 279 | /** 280 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-4 281 | * 282 | * The user has sent too many requests in a given amount of time ("rate limiting"). 283 | */ 284 | TOO_MANY_REQUESTS: 429, 285 | /** 286 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-5 287 | * 288 | * 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. 289 | */ 290 | REQUEST_HEADER_FIELDS_TOO_LARGE: 431, 291 | /** 292 | * Official Documentation @ https://tools.ietf.org/html/rfc7725 293 | * 294 | * The user-agent requested a resource that cannot legally be provided, such as a web page censored by a government. 295 | */ 296 | UNAVAILABLE_FOR_LEGAL_REASONS: 451, 297 | /** 298 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.1 299 | * 300 | * The server encountered an unexpected condition that prevented it from fulfilling the request. 301 | */ 302 | INTERNAL_SERVER_ERROR: 500, 303 | /** 304 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.2 305 | * 306 | * 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. 307 | */ 308 | NOT_IMPLEMENTED: 501, 309 | /** 310 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.3 311 | * 312 | * 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. 313 | */ 314 | BAD_GATEWAY: 502, 315 | /** 316 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.4 317 | * 318 | * 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. 319 | */ 320 | SERVICE_UNAVAILABLE: 503, 321 | /** 322 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.5 323 | * 324 | * This error response is given when the server is acting as a gateway and cannot get a response in time. 325 | */ 326 | GATEWAY_TIMEOUT: 504, 327 | /** 328 | * Official Documentation @ https://tools.ietf.org/html/rfc7231#section-6.6.6 329 | * 330 | * The HTTP version used in the request is not supported by the server. 331 | */ 332 | HTTP_VERSION_NOT_SUPPORTED: 505, 333 | /** 334 | * Official Documentation @ https://tools.ietf.org/html/rfc2518#section-10.6 335 | * 336 | * 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. 337 | */ 338 | INSUFFICIENT_STORAGE: 507, 339 | /** 340 | * Official Documentation @ https://tools.ietf.org/html/rfc6585#section-6 341 | * 342 | * The 511 status code indicates that the client needs to authenticate to gain network access. 343 | */ 344 | NETWORK_AUTHENTICATION_REQUIRED: 511, 345 | }; 346 | -------------------------------------------------------------------------------- /service-search-redis/src/cores/error.response.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* IMPORT 4 | const { StatusCodes, ReasonPhrases } = require('../common/utils/httpStatusCode'); 5 | const logger = require('../loggers/winston.log'); 6 | class ErrorResponse extends Error { 7 | constructor(message, status) { 8 | super(message); 9 | this.status = status; 10 | 11 | // Log error 12 | logger.error(`${this.status} = ${this.message}`); 13 | } 14 | } 15 | class BadRequestRequestError extends ErrorResponse { 16 | constructor(message = ReasonPhrases.BAD_REQUEST, statusCode = StatusCodes.BAD_REQUEST) { 17 | super(message, statusCode); 18 | } 19 | } 20 | 21 | class NotFoundError extends ErrorResponse { 22 | constructor(message = ReasonPhrases.NOT_FOUND, statusCode = StatusCodes.NOT_FOUND) { 23 | super(message, statusCode); 24 | } 25 | } 26 | class InternalServerError extends ErrorResponse { 27 | constructor(message = ReasonPhrases.INTERNAL_SERVER_ERROR, statusCode = StatusCodes.INTERNAL_SERVER_ERROR) { 28 | super(message, statusCode); 29 | } 30 | } 31 | module.exports = { 32 | BadRequestRequestError, 33 | InternalServerError, 34 | NotFoundError, 35 | }; 36 | -------------------------------------------------------------------------------- /service-search-redis/src/cores/success.response.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* IMPORT 4 | const { StatusCodes, ReasonPhrases } = require('../common/utils/httpStatusCode'); 5 | 6 | class SuccessResponse { 7 | constructor({ message, statusCode = StatusCodes.OK, reasonStatusCode = ReasonPhrases.OK, metadata = {} }) { 8 | this.message = !message ? reasonStatusCode : message; 9 | this.status = statusCode; 10 | this.metadata = metadata; 11 | } 12 | 13 | send(res, _ = {}) { 14 | return res.status(this.status).json(this); 15 | } 16 | } 17 | 18 | class Ok extends SuccessResponse { 19 | constructor({ message, metadata }) { 20 | super({ message, metadata }); 21 | } 22 | } 23 | 24 | class Created extends SuccessResponse { 25 | constructor({ 26 | option = {}, 27 | message, 28 | statusCode = StatusCodes.CREATED, 29 | reasonStatusCode = ReasonPhrases.CREATED, 30 | metadata = {}, 31 | }) { 32 | super({ message, statusCode, reasonStatusCode, metadata }); 33 | this.option = option; 34 | } 35 | } 36 | module.exports = { 37 | Ok, 38 | Created, 39 | SuccessResponse, 40 | }; 41 | -------------------------------------------------------------------------------- /service-search-redis/src/dbs/client.js: -------------------------------------------------------------------------------- 1 | //* IMPORT 2 | const redisConnection = require('.'); 3 | 4 | const redisClient = redisConnection.getClient(); 5 | 6 | module.exports = redisClient; 7 | -------------------------------------------------------------------------------- /service-search-redis/src/dbs/index.js: -------------------------------------------------------------------------------- 1 | //* LIB 2 | const { Client } = require('redis-om'); 3 | 4 | class RedisConnection { 5 | constructor() { 6 | this.client = null; 7 | } 8 | 9 | async createConnection(url) { 10 | if (!this.client || !this.client.isOpen()) { 11 | this.client = new Client(); 12 | await this.client.open(url); 13 | console.info('Connected to Redis successfully.'); 14 | } 15 | } 16 | 17 | getClient() { 18 | if (!this.client) { 19 | throw new Error('Redis client not initialized. Call createConnection first.'); 20 | } 21 | return this.client; 22 | } 23 | } 24 | 25 | class Singleton { 26 | constructor() { 27 | if (!Singleton.instance) { 28 | Singleton.instance = new RedisConnection(); 29 | } 30 | } 31 | 32 | getInstance() { 33 | return Singleton.instance; 34 | } 35 | } 36 | 37 | // Export Singleton instance của RedisConnection 38 | const redisConnection = new Singleton().getInstance(); 39 | module.exports = redisConnection; 40 | -------------------------------------------------------------------------------- /service-search-redis/src/loggers/winston.log.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | //* LIB 4 | const path = require('path'); 5 | const winston = require('winston'); 6 | 7 | const { combine, timestamp, align, printf } = winston.format; 8 | const logsDirectory = path.join(__dirname, '../logs'); // Use an absolute path 9 | 10 | const logger = winston.createLogger({ 11 | level: process.env.LOG_LEVEL || 'debug', 12 | format: combine( 13 | timestamp({ 14 | format: 'YYYY-MM-DD hh:mm:ss.SSS A', 15 | }), 16 | align(), 17 | printf((info) => `[${info.timestamp}] ${info.level.toUpperCase()}: ${info.message}`), 18 | ), 19 | transports: [ 20 | new winston.transports.Console(), 21 | new winston.transports.File({ dirname: logsDirectory, filename: 'test.log' }), 22 | ], 23 | }); 24 | 25 | module.exports = logger; 26 | -------------------------------------------------------------------------------- /service-search-redis/src/middlewares/rateLimitMiddleware.js: -------------------------------------------------------------------------------- 1 | //* LIB 2 | const rateLimit = require('express-rate-limit'); 3 | 4 | //* IMPORT 5 | const { REQUEST } = require('../common/constants'); 6 | const { ReasonPhrases, StatusCodes } = require('../common/utils/httpStatusCode'); 7 | 8 | module.exports = rateLimit({ 9 | windowMs: REQUEST._WINDOW_MS, 10 | max: REQUEST._MAX, 11 | message: { 12 | status: StatusCodes.TOO_MANY_REQUESTS, 13 | message: ReasonPhrases.TOO_MANY_REQUESTS, 14 | }, 15 | standardHeaders: true, 16 | }); 17 | --------------------------------------------------------------------------------