From caeea38a3df63dd8c0e14449c61749ea6d3bab24 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 21 Jan 2020 17:23:03 +0530 Subject: [PATCH 01/91] feat: Add VS-CODE.md --- VS-CODE.md | 49 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 VS-CODE.md diff --git a/VS-CODE.md b/VS-CODE.md new file mode 100644 index 0000000..9bd34c3 --- /dev/null +++ b/VS-CODE.md @@ -0,0 +1,49 @@ +Features: + +1. Edit, build, and debug with ease + +2. Robust and extensible architecture + +3. Available for macOS, Linux, and Windows + +4. Make it your own (Customize every feature to your liking and install any number of third-party extensions) + +5. Built with love for the Web + (VS Code includes enriched built-in support for Node.js development with JavaScript and TypeScript, powered by the same underlying technologies that drive Visual Studio) + + + +Plugins: + +1. Quokka + +Quokka is a debugging tool that gives live feedback on the code you are writing. It shows you previews of the results of functions and calculated values for variables. The extension is easy to configure and works out of the box with JSX or TypeScript projects. + +2. Faker + +Quickly insert placeholder data using the popular Faker JavaScript library. You can generate random names, addresses, images, phone numbers, or just paragraphs of classic Lorem Ipsum. Each category has various subcategories so you can make the data fit your needs. + +3. Color Info + +Small plugin that gives you various information about the colors you've used in your CSS. By hovering on a color you can see a larger preview of how it looks, as well as info about its translation to all formats (hex, rgb, hsl, and cmyk). + +4. SVG Viewer + +This extension adds a number of utilities for working with SVGs in Visual Studio Code. It makes it possible to render SVG files and see how they look like without having to leave the editor. There are also options for converting to PNG and generating data URI schemes. + +5. TODO Highlight + +This tool marks all TODO comments in your code, making it easier to track down any unfinished business before pushing to production. By default it looks for TODO and FIXME keywords but you can add your custom expressions as well. + +6. Icon Fonts + +Tiny snippets for including icon fonts in your project (from a CDN) and then adding the icons themselves. The extension supports over 20 popular icon sets, including Font Awesome, Ionicons, Glyphicons, and Material Design Icons. + +7. Language and Framework Packs + +VSCode ships with support for a large number of languages. If for some reason your programming language of choice isn't included, you can download an extension pack which will add autocompletion, proper indentation, and other utilities. Some web dev frameworks like react native and vue also offer language packs. + +8. Minify + +Extension for minifying your code. It offers a ton of customization settings and the option to automatically minify on save and export to a .min file. Minify works with JavaScript, CSS, and HTML through uglify-js, clean-css, and html-minifier respectively. + From 7be7cfefd1ee160331585d33ed8bdee90702c86c Mon Sep 17 00:00:00 2001 From: AryanSinghalGit <60099465+AryanSinghalGit@users.noreply.github.com> Date: Tue, 21 Jan 2020 17:42:13 +0530 Subject: [PATCH 02/91] Update VS-CODE.md --- VS-CODE.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/VS-CODE.md b/VS-CODE.md index 9bd34c3..6fc34af 100644 --- a/VS-CODE.md +++ b/VS-CODE.md @@ -47,3 +47,19 @@ VSCode ships with support for a large number of languages. If for some reason yo Extension for minifying your code. It offers a ton of customization settings and the option to automatically minify on save and export to a .min file. Minify works with JavaScript, CSS, and HTML through uglify-js, clean-css, and html-minifier respectively. + +Commands Used: +echo "# javascript-client" >> README.md +git init +git add README.md +git commit -m "first commit" +git remote add origin https://github.com/AryanSinghalGit/javascript-client.git +git push -u origin master +git branch +git checkout -b develop +git push origin develop +git checkout -b feature/39512 +gedit VS-CODE.md +git add VS-CODE.md +git status +git push origin feature/39512 From b08225507da6abb0821aacccf95ae168077f2a97 Mon Sep 17 00:00:00 2001 From: AryanSinghalGit <60099465+AryanSinghalGit@users.noreply.github.com> Date: Tue, 21 Jan 2020 17:43:45 +0530 Subject: [PATCH 03/91] Update VS-CODE.md Added commands used --- VS-CODE.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/VS-CODE.md b/VS-CODE.md index 6fc34af..13c9258 100644 --- a/VS-CODE.md +++ b/VS-CODE.md @@ -49,17 +49,32 @@ Extension for minifying your code. It offers a ton of customization settings and Commands Used: + echo "# javascript-client" >> README.md + git init + git add README.md + git commit -m "first commit" + git remote add origin https://github.com/AryanSinghalGit/javascript-client.git + git push -u origin master + git branch + git checkout -b develop + git push origin develop + git checkout -b feature/39512 + gedit VS-CODE.md + git add VS-CODE.md + git status + git push origin feature/39512 + From 31d58373cd68c56779e82e24bc6b8de2ff44f234 Mon Sep 17 00:00:00 2001 From: AryanSinghalGit <60099465+AryanSinghalGit@users.noreply.github.com> Date: Wed, 22 Jan 2020 09:39:04 +0530 Subject: [PATCH 04/91] Delete VS-CODE.md --- VS-CODE.md | 80 ------------------------------------------------------ 1 file changed, 80 deletions(-) delete mode 100644 VS-CODE.md diff --git a/VS-CODE.md b/VS-CODE.md deleted file mode 100644 index 13c9258..0000000 --- a/VS-CODE.md +++ /dev/null @@ -1,80 +0,0 @@ -Features: - -1. Edit, build, and debug with ease - -2. Robust and extensible architecture - -3. Available for macOS, Linux, and Windows - -4. Make it your own (Customize every feature to your liking and install any number of third-party extensions) - -5. Built with love for the Web - (VS Code includes enriched built-in support for Node.js development with JavaScript and TypeScript, powered by the same underlying technologies that drive Visual Studio) - - - -Plugins: - -1. Quokka - -Quokka is a debugging tool that gives live feedback on the code you are writing. It shows you previews of the results of functions and calculated values for variables. The extension is easy to configure and works out of the box with JSX or TypeScript projects. - -2. Faker - -Quickly insert placeholder data using the popular Faker JavaScript library. You can generate random names, addresses, images, phone numbers, or just paragraphs of classic Lorem Ipsum. Each category has various subcategories so you can make the data fit your needs. - -3. Color Info - -Small plugin that gives you various information about the colors you've used in your CSS. By hovering on a color you can see a larger preview of how it looks, as well as info about its translation to all formats (hex, rgb, hsl, and cmyk). - -4. SVG Viewer - -This extension adds a number of utilities for working with SVGs in Visual Studio Code. It makes it possible to render SVG files and see how they look like without having to leave the editor. There are also options for converting to PNG and generating data URI schemes. - -5. TODO Highlight - -This tool marks all TODO comments in your code, making it easier to track down any unfinished business before pushing to production. By default it looks for TODO and FIXME keywords but you can add your custom expressions as well. - -6. Icon Fonts - -Tiny snippets for including icon fonts in your project (from a CDN) and then adding the icons themselves. The extension supports over 20 popular icon sets, including Font Awesome, Ionicons, Glyphicons, and Material Design Icons. - -7. Language and Framework Packs - -VSCode ships with support for a large number of languages. If for some reason your programming language of choice isn't included, you can download an extension pack which will add autocompletion, proper indentation, and other utilities. Some web dev frameworks like react native and vue also offer language packs. - -8. Minify - -Extension for minifying your code. It offers a ton of customization settings and the option to automatically minify on save and export to a .min file. Minify works with JavaScript, CSS, and HTML through uglify-js, clean-css, and html-minifier respectively. - - -Commands Used: - -echo "# javascript-client" >> README.md - -git init - -git add README.md - -git commit -m "first commit" - -git remote add origin https://github.com/AryanSinghalGit/javascript-client.git - -git push -u origin master - -git branch - -git checkout -b develop - -git push origin develop - -git checkout -b feature/39512 - -gedit VS-CODE.md - -git add VS-CODE.md - -git status - -git push origin feature/39512 - From 2384ec35e8697adca993405d57e5f064ff9f617f Mon Sep 17 00:00:00 2001 From: AryanSinghalGit <60099465+AryanSinghalGit@users.noreply.github.com> Date: Wed, 22 Jan 2020 12:00:57 +0530 Subject: [PATCH 05/91] Update VS-CODE.md --- VS-CODE.md | 66 ++++++++++++++++++++++++++++-------------------------- 1 file changed, 34 insertions(+), 32 deletions(-) diff --git a/VS-CODE.md b/VS-CODE.md index 13c9258..50948ea 100644 --- a/VS-CODE.md +++ b/VS-CODE.md @@ -1,80 +1,82 @@ Features: +========= +**1. Edit, build, and debug with ease** -1. Edit, build, and debug with ease +**2. Robust and extensible architecture** -2. Robust and extensible architecture +**3. Available for macOS, Linux, and Windows** -3. Available for macOS, Linux, and Windows - -4. Make it your own (Customize every feature to your liking and install any number of third-party extensions) - -5. Built with love for the Web - (VS Code includes enriched built-in support for Node.js development with JavaScript and TypeScript, powered by the same underlying technologies that drive Visual Studio) +**4. Make it your own** + Customize every feature to your liking and install any number of third-party extensions +**5. Built with love for the Web** + VS Code includes enriched built-in support for Node.js development with JavaScript and TypeScript, powered by the same underlying technologies that drive Visual Studio +--- Plugins: +======== -1. Quokka - +**1. Quokka** Quokka is a debugging tool that gives live feedback on the code you are writing. It shows you previews of the results of functions and calculated values for variables. The extension is easy to configure and works out of the box with JSX or TypeScript projects. -2. Faker +**2. Faker** Quickly insert placeholder data using the popular Faker JavaScript library. You can generate random names, addresses, images, phone numbers, or just paragraphs of classic Lorem Ipsum. Each category has various subcategories so you can make the data fit your needs. -3. Color Info +**3. Color Info** Small plugin that gives you various information about the colors you've used in your CSS. By hovering on a color you can see a larger preview of how it looks, as well as info about its translation to all formats (hex, rgb, hsl, and cmyk). -4. SVG Viewer +**4. SVG Viewer** This extension adds a number of utilities for working with SVGs in Visual Studio Code. It makes it possible to render SVG files and see how they look like without having to leave the editor. There are also options for converting to PNG and generating data URI schemes. -5. TODO Highlight +**5. TODO Highlight** This tool marks all TODO comments in your code, making it easier to track down any unfinished business before pushing to production. By default it looks for TODO and FIXME keywords but you can add your custom expressions as well. -6. Icon Fonts +**6. Icon Fonts** Tiny snippets for including icon fonts in your project (from a CDN) and then adding the icons themselves. The extension supports over 20 popular icon sets, including Font Awesome, Ionicons, Glyphicons, and Material Design Icons. -7. Language and Framework Packs +**7. Language and Framework Packs** VSCode ships with support for a large number of languages. If for some reason your programming language of choice isn't included, you can download an extension pack which will add autocompletion, proper indentation, and other utilities. Some web dev frameworks like react native and vue also offer language packs. -8. Minify +**8. Minify** Extension for minifying your code. It offers a ton of customization settings and the option to automatically minify on save and export to a .min file. Minify works with JavaScript, CSS, and HTML through uglify-js, clean-css, and html-minifier respectively. +--- Commands Used: +========= +* echo "# javascript-client" >> README.md -echo "# javascript-client" >> README.md - -git init +* git init -git add README.md +* git add README.md -git commit -m "first commit" +* git commit -m "first commit" -git remote add origin https://github.com/AryanSinghalGit/javascript-client.git +* git remote add origin https://github.com/AryanSinghalGit/javascript-client.git -git push -u origin master +* git push -u origin master -git branch +* git branch -git checkout -b develop +* git checkout -b develop -git push origin develop +* git push origin develop -git checkout -b feature/39512 +* git checkout -b feature/39512 -gedit VS-CODE.md +* gedit VS-CODE.md -git add VS-CODE.md +* git add VS-CODE.md -git status +* git status -git push origin feature/39512 +* git push origin feature/39512 From 20f4a921ea3106946996173f5a773ff803323550 Mon Sep 17 00:00:00 2001 From: AryanSinghalGit <60099465+AryanSinghalGit@users.noreply.github.com> Date: Wed, 22 Jan 2020 12:02:39 +0530 Subject: [PATCH 06/91] Update VS-CODE.md change format --- VS-CODE.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/VS-CODE.md b/VS-CODE.md index 50948ea..1a37006 100644 --- a/VS-CODE.md +++ b/VS-CODE.md @@ -7,10 +7,12 @@ Features: **3. Available for macOS, Linux, and Windows** **4. Make it your own** - Customize every feature to your liking and install any number of third-party extensions + + Customize every feature to your liking and install any number of third-party extensions **5. Built with love for the Web** - VS Code includes enriched built-in support for Node.js development with JavaScript and TypeScript, powered by the same underlying technologies that drive Visual Studio + + VS Code includes enriched built-in support for Node.js development with JavaScript and TypeScript, powered by the same underlying technologies that drive Visual Studio --- @@ -18,6 +20,7 @@ Plugins: ======== **1. Quokka** + Quokka is a debugging tool that gives live feedback on the code you are writing. It shows you previews of the results of functions and calculated values for variables. The extension is easy to configure and works out of the box with JSX or TypeScript projects. **2. Faker** From ca5658dd21694745e897adeb894477526eb5156f Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Wed, 22 Jan 2020 14:42:38 +0530 Subject: [PATCH 07/91] feat:Add .editorconfig --- .editorconfig | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 .editorconfig diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..65a5ef4 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,14 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +end_of_line = lf +# editorconfig-tools is unable to ignore longs strings or urls +max_line_length = off + +[CHANGELOG.md] +indent_size = false \ No newline at end of file From a9c6c3341662b52e5f4f7a84013c3036062d85e9 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Wed, 22 Jan 2020 15:07:02 +0530 Subject: [PATCH 08/91] feat : Add MERN-STACK.md --- MERN-STACK.md | 66 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 MERN-STACK.md diff --git a/MERN-STACK.md b/MERN-STACK.md new file mode 100644 index 0000000..2724bcc --- /dev/null +++ b/MERN-STACK.md @@ -0,0 +1,66 @@ +MERN Stack: +== +MERN Stack is a Javascript Stack that is used for easier and faster deployment of full-stack web applications. MERN Stack comprises of 4 technologies namely: MongoDB, Express, React and Node.js. It is designed to make the development process smoother and easier. + +Each of these 4 powerful technologies provides an end-to-end framework for the developers to work in and each of these technologies play a big part in the development of web applications. + +# 1. MongoDB: Cross-platform Document-Oriented Database +--- + +MongoDB is a NoSQL database where each record is a document comprising of key-value pairs that are similar to JSON (JavaScript Object Notation) objects. MongoDB is flexible and allows its users to create schema, databases, tables, etc. Documents that are identifiable by a primary key make up the basic unit of MongoDB. Once MongoDB is installed, users can make use of Mongo shell as well. Mongo shell provides a JavaScript interface through which the users can interact and carry out operations (eg: querying, updating records, deleting records). + +**Why use MongoDB?** +-- + +* Fast – Being a document-oriented database, easy to index documents. Therefore a faster response. +* Scalability – Large data can be handled by dividing it into several machines. +* Use of JavaScript – MongoDB uses JavaScript which is the biggest advantage. +* Schema Less – Any type of data in a separate document. +* Data stored in the form of JSON – +Objects, Object Members, Arrays, Values and Strings +* JSON syntax is very easy to use. +* JSON has a wide range of browser compatibility. + +# 2. Express: Back-End Framework: +--- +Express is a Node.js framework. Rather than writing the code using Node.js and creating loads of Node modules, Express makes it simpler and easier to write the back-end code. Express helps in designing great web applications and APIs. Express supports many middlewares which makes the code shorter and easier to write. + +**Why use Express?** +-- + +* Asynchronous and Single-threaded. +* Effecient, fast & scalable +* Has the biggest community for Node.js +* Express promotes code reusability with its built-in router. +* Robust API + +# 3. React: Front-End Framework +--- +React is a JavaScript library that is used for building user interfaces. React is used for the development of single-page applications and mobile applications because of its ability to handle rapidly changing data. React allows users to code in JavasScript and create UI components. + +**Why use React?** +--- +* **Virtual DOM** – A virtual DOM object is a representation of a DOM object. Virtual DOM is actually a copy of the original DOM. Any modification in the web application causes the entire UI to re-render the virtual DOM. Then the difference between the original DOM and this virtual DOM is compared and the changes are made accordingly to the original DOM. + +* **JSX** – Stands for JavaScript XML. It is an HTML/XML JavaScript Extension which is used in React. Makes it easier and simpler to write React components. + +* **Components** – ReactJS supports Components. Components are the building blocks of UI wherein each component has a logic and contributes to the overall UI. These components also promote code reusability and make the overall web application easier to understand. + +* **High Performance** – Features like Virtual DOM, JSX and Components makes it much faster than the rest of the frameworks out there. + +* **Developing Android/Ios Apps** – With React Native you can easily code Android-based or IOS-Based apps with just the knowledge of JavaScript and ReactJS. + +# 4. Node.js: JS Runtime Environment +--- +Node.js provides a JavaScript Environment which allows the user to run their code on the server (outside the browser). Node pack manager i.e. npm allows the user to choose from thousands of free packages (node modules) to download. + +**Why use Node.JS?** +-- + +* Open source JavaScript Runtime Environemnt +* Single threading – Follows a single threaded model. +* Data Streaming +* Fast – Built on Google Chrome’s JavaScript Engine, Node.js has a fast code execution. +* Highly Scalable + + From 45df94c494adb2cd0160da02a207337653ff322c Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Wed, 22 Jan 2020 15:34:06 +0530 Subject: [PATCH 09/91] feat : Add 12FACTOR-APP.md --- 12FACTOR-APP.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) create mode 100644 12FACTOR-APP.md diff --git a/12FACTOR-APP.md b/12FACTOR-APP.md new file mode 100644 index 0000000..e69de29 From 36f0c6ca089164242661a81b2b008d5150b99dbe Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Wed, 22 Jan 2020 16:05:21 +0530 Subject: [PATCH 10/91] feat: Add CLIENT-SERVER.md --- CLIENT-SERVER.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 CLIENT-SERVER.md diff --git a/CLIENT-SERVER.md b/CLIENT-SERVER.md new file mode 100644 index 0000000..b223f91 --- /dev/null +++ b/CLIENT-SERVER.md @@ -0,0 +1,18 @@ +How a request get served? +== +--- + +Web Server accepts request and responds to Hypertext Transfer Protocol (HTTP) requests. Browsers such as Netscape™ Communicator communicate using several protocols including HTTP and FTP. + +The transfer of resources happens using TCP (Transmission Control Protocol). In viewing this webpage, TCP manages the channels between your browser and the server. TCP is used to manage many types of internet connections in which one computer or device wants to send something to another. HTTP is the command language that the devices on both sides of the connection must follow in order to communicate. + +Once the TCP connection is established, the client sends a HTTP GET request to the server to retrieve the webpage it should display. After the server has sent the response, it closes the TCP connection. If you open the website in your browser again, or if your browser automatically requests something from the server, a new connection is opened which follows the same process described above. + +# _HTTP Basics_ +--- +As a quick summary, the HTTP/1.1 protocol works as follows: + +* The client (usually a browser) opens a connection to the server and sends a request. +* The server processes the request, generates a response, and closes the connection if it finds a Connection: Close header. +* The request consists of a line indicating a method such as GET or POST, a Uniform Resource Identifier (URI) indicating which resource is being requested, and an HTTP protocol version separated by spaces. +* This is normally followed by a number of headers, a blank line indicating the end of the headers, and sometimes body data. Headers may provide various information about the request or the client body data. Headers are typically only sent for POST and PUT methods. From 97fa51622688254394ab818374c0808fd76dc762 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Wed, 22 Jan 2020 16:09:32 +0530 Subject: [PATCH 11/91] feat: Add 12FACTOR-APP.md --- 12FACTOR-APP.md | 66 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/12FACTOR-APP.md b/12FACTOR-APP.md index e69de29..986c0df 100644 --- a/12FACTOR-APP.md +++ b/12FACTOR-APP.md @@ -0,0 +1,66 @@ +The Twelve Factors +=== +# 1. Codebase +**There should be exactly one codebase for a deployed service with the codebase being used for many deployments.** + +There is always a one-to-one correlation between the codebase and the app: +* If there are multiple codebases, it’s not an app – it’s a distributed system. Each component in a distributed system is an app, and each can individually comply with twelve-factor. +* Multiple apps sharing the same code is a violation of twelve-factor. The solution here is to factor shared code into libraries which can be included through the dependency manager. + +# 2. Dependencies +**All dependencies should be declared, with no implicit reliance on system tools or libraries.** +A twelve-factor app never relies on implicit existence of system-wide packages. It declares all dependencies, completely and exactly, via a dependency declaration manifest. Furthermore, it uses a dependency isolation tool during execution to ensure that no implicit dependencies “leak in” from the surrounding system. The full and explicit dependency specification is applied uniformly to both production and development. + +# 3. Config +**Configuration that varies between deployments should be stored in the environment.** +An app’s config is everything that is likely to vary between deploys (staging, production, developer environments, etc). This includes: +* Resource handles to the database, Memcached, and other backing services +* Credentials to external services such as Amazon S3 or Twitter +* Per-deploy values such as the canonical hostname for the deploy + +# 4. Backing services +**All backing services are treated as attached resources and attached and detached by the execution environment.** +A backing service is any service the app consumes over the network as part of its normal operation. Examples include datastores (such as MySQL or CouchDB), messaging/queueing systems (such as RabbitMQ or Beanstalkd), SMTP services for outbound email (such as Postfix), and caching systems (such as Memcached). + +# 5. Build, release, run +**The delivery pipeline should strictly consist of build, release, run.** + +A codebase is transformed into a (non-development) deploy through three stages: + +* The build stage is a transform which converts a code repo into an executable bundle known as a build. Using a version of the code at a commit specified by the deployment process, the build stage fetches vendors dependencies and compiles binaries and assets. +* The release stage takes the build produced by the build stage and combines it with the deploy’s current config. The resulting release contains both the build and the config and is ready for immediate execution in the execution environment. +* The run stage (also known as “runtime”) runs the app in the execution environment, by launching some set of the app’s processes against a selected release. + +# 6. Processes +**Applications should be deployed as one or more stateless processes with persisted data stored on a backing service.** + +In the simplest case, the code is a stand-alone script, the execution environment is a developer’s local laptop with an installed language runtime, and the process is launched via the command line (for example, python my_script.py). On the other end of the spectrum, a production deploy of a sophisticated app may use many process types, instantiated into zero or more running processes. + +# 7. Port binding +**Self-contained services should make themselves available to other services by specified ports.** +The twelve-factor app is completely self-contained and does not rely on runtime injection of a webserver into the execution environment to create a web-facing service. The web app exports HTTP as a service by binding to a port, and listening to requests coming in on that port. + +# 8. Concurrency +**Concurrency is advocated by scaling individual processes.** +Any computer program, once run, is represented by one or more processes. Web apps have taken a variety of process-execution forms. For example, PHP processes run as child processes of Apache, started on demand as needed by request volume. Java processes take the opposite approach, with the JVM providing one massive uberprocess that reserves a large block of system resources (CPU and memory) on startup, with concurrency managed internally via threads. In both cases, the running process(es) are only minimally visible to the developers of the app. + +# 9. Disposability +**Fast startup and shutdown are advocated for a more robust and resilient system.** +Processes should strive to minimize startup time. Ideally, a process takes a few seconds from the time the launch command is executed until the process is up and ready to receive requests or jobs. Short startup time provides more agility for the release process and scaling up; and it aids robustness, because the process manager can more easily move processes to new physical machines when warranted. + +# 10. Dev/Prod parity +**All environments should be as similar as possible.** + +Historically, there have been substantial gaps between development (a developer making live edits to a local deploy of the app) and production (a running deploy of the app accessed by end users). These gaps manifest in three areas: + +* **The time gap:** A developer may work on code that takes days, weeks, or even months to go into production. +* **The personnel gap:** Developers write code, ops engineers deploy it. +* **The tools gap:** Developers may be using a stack like Nginx, SQLite, and OS X, while the production deploy uses Apache, MySQL, and Linux. + +# 11. Logs +**Applications should produce logs as event streams and leave the execution environment to aggregate.** +Logs provide visibility into the behavior of a running app. In server-based environments they are commonly written to a file on disk (a “logfile”); but this is only an output format. + +# 12. Admin Processes +**Any needed admin tasks should be kept in source control and packaged with the application.** +One-off admin processes should be run in an identical environment as the regular long-running processes of the app. They run against a release, using the same codebase and config as any process run against that release. Admin code must ship with application code to avoid synchronization issues. \ No newline at end of file From e4a708ff3da7720fa57195bfbc1375cc66c5b8b2 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Thu, 23 Jan 2020 17:45:31 +0530 Subject: [PATCH 12/91] feat: Add Package extra --- extra/npm-debug.log | 49 +++++++++++++++++++++++++++++++++++ extra/package.json | 14 ++++++++++ extra/patterns/diamond.js | 32 +++++++++++++++++++++++ extra/patterns/equilateral.js | 24 +++++++++++++++++ extra/patterns/npm-debug.log | 49 +++++++++++++++++++++++++++++++++++ 5 files changed, 168 insertions(+) create mode 100644 extra/npm-debug.log create mode 100644 extra/package.json create mode 100644 extra/patterns/diamond.js create mode 100644 extra/patterns/equilateral.js create mode 100644 extra/patterns/npm-debug.log diff --git a/extra/npm-debug.log b/extra/npm-debug.log new file mode 100644 index 0000000..2b29a0b --- /dev/null +++ b/extra/npm-debug.log @@ -0,0 +1,49 @@ +0 info it worked if it ends with ok +1 verbose cli [ '/usr/bin/nodejs', +1 verbose cli '/usr/bin/npm', +1 verbose cli 'run', +1 verbose cli 'pattern:equilateral' ] +2 info using npm@3.5.2 +3 info using node@v4.2.6 +4 verbose run-script [ 'prepattern:equilateral', +4 verbose run-script 'pattern:equilateral', +4 verbose run-script 'postpattern:equilateral' ] +5 info lifecycle extra@1.0.0~prepattern:equilateral: extra@1.0.0 +6 silly lifecycle extra@1.0.0~prepattern:equilateral: no script for prepattern:equilateral, continuing +7 info lifecycle extra@1.0.0~pattern:equilateral: extra@1.0.0 +8 verbose lifecycle extra@1.0.0~pattern:equilateral: unsafe-perm in lifecycle true +9 verbose lifecycle extra@1.0.0~pattern:equilateral: PATH: /usr/share/npm/bin/node-gyp-bin:/home/aryan.singhal/day2/javascript-server/extra/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin +10 verbose lifecycle extra@1.0.0~pattern:equilateral: CWD: /home/aryan.singhal/day2/javascript-server/extra +11 silly lifecycle extra@1.0.0~pattern:equilateral: Args: [ '-c', 'extra/patterns/equilateral.js' ] +12 info lifecycle extra@1.0.0~pattern:equilateral: Failed to exec pattern:equilateral script +13 verbose stack Error: extra@1.0.0 pattern:equilateral: `extra/patterns/equilateral.js` +13 verbose stack spawn ENOENT +13 verbose stack at ChildProcess. (/usr/share/npm/lib/utils/spawn.js:17:16) +13 verbose stack at emitTwo (events.js:87:13) +13 verbose stack at ChildProcess.emit (events.js:172:7) +13 verbose stack at maybeClose (internal/child_process.js:821:16) +13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5) +14 verbose pkgid extra@1.0.0 +15 verbose cwd /home/aryan.singhal/day2/javascript-server/extra +16 error Linux 4.15.0-45-generic +17 error argv "/usr/bin/nodejs" "/usr/bin/npm" "run" "pattern:equilateral" +18 error node v4.2.6 +19 error npm v3.5.2 +20 error file sh +21 error code ELIFECYCLE +22 error errno ENOENT +23 error syscall spawn +24 error extra@1.0.0 pattern:equilateral: `extra/patterns/equilateral.js` +24 error spawn ENOENT +25 error Failed at the extra@1.0.0 pattern:equilateral script 'extra/patterns/equilateral.js'. +25 error Make sure you have the latest version of node.js and npm installed. +25 error If you do, this is most likely a problem with the extra package, +25 error not with npm itself. +25 error Tell the author that this fails on your system: +25 error extra/patterns/equilateral.js +25 error You can get information on how to open an issue for this project with: +25 error npm bugs extra +25 error Or if that isn't available, you can get their info via: +25 error npm owner ls extra +25 error There is likely additional logging output above. +26 verbose exit [ 1, true ] diff --git a/extra/package.json b/extra/package.json new file mode 100644 index 0000000..9b0aef4 --- /dev/null +++ b/extra/package.json @@ -0,0 +1,14 @@ +{ + "name": "extra", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "pattern:diamond":"extra/patterns/diamond.js", + "pattern:equilateral":"extra/patterns/equilateral.js" + + }, + "author": "", + "license": "ISC" +} diff --git a/extra/patterns/diamond.js b/extra/patterns/diamond.js new file mode 100644 index 0000000..195f155 --- /dev/null +++ b/extra/patterns/diamond.js @@ -0,0 +1,32 @@ +let n=process.argv[2] + +diamond(n) +function diamond(n) +{ +for(let i=0;i0;i--) +{ + let str="" + for(let k=0;k (/usr/share/npm/lib/utils/spawn.js:17:16) +13 verbose stack at emitTwo (events.js:87:13) +13 verbose stack at ChildProcess.emit (events.js:172:7) +13 verbose stack at maybeClose (internal/child_process.js:821:16) +13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5) +14 verbose pkgid extra@1.0.0 +15 verbose cwd /home/aryan.singhal/day2/javascript-server/extra/patterns +16 error Linux 4.15.0-45-generic +17 error argv "/usr/bin/nodejs" "/usr/bin/npm" "run" "pattern:equilateral" +18 error node v4.2.6 +19 error npm v3.5.2 +20 error file sh +21 error code ELIFECYCLE +22 error errno ENOENT +23 error syscall spawn +24 error extra@1.0.0 pattern:equilateral: `extra/patterns/equilateral.js` +24 error spawn ENOENT +25 error Failed at the extra@1.0.0 pattern:equilateral script 'extra/patterns/equilateral.js'. +25 error Make sure you have the latest version of node.js and npm installed. +25 error If you do, this is most likely a problem with the extra package, +25 error not with npm itself. +25 error Tell the author that this fails on your system: +25 error extra/patterns/equilateral.js +25 error You can get information on how to open an issue for this project with: +25 error npm bugs extra +25 error Or if that isn't available, you can get their info via: +25 error npm owner ls extra +25 error There is likely additional logging output above. +26 verbose exit [ 1, true ] From 32ee139b30fcc1435e15935226bbbb0cea89eda0 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Thu, 23 Jan 2020 18:17:38 +0530 Subject: [PATCH 13/91] fix: Add package.json --- extra/package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/extra/package.json b/extra/package.json index 9b0aef4..00d2223 100644 --- a/extra/package.json +++ b/extra/package.json @@ -5,8 +5,8 @@ "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1", - "pattern:diamond":"extra/patterns/diamond.js", - "pattern:equilateral":"extra/patterns/equilateral.js" + "pattern:diamond":" node patterns/diamond.js", + "pattern:equilateral":"node patterns/equilateral.js" }, "author": "", From 1535f2419557a6fbfb9f5291b6cdc0f2eb6770af Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Fri, 24 Jan 2020 16:47:57 +0530 Subject: [PATCH 14/91] feat: Add package utils --- extra/utils/validation.js | 90 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 extra/utils/validation.js diff --git a/extra/utils/validation.js b/extra/utils/validation.js new file mode 100644 index 0000000..b7f47de --- /dev/null +++ b/extra/utils/validation.js @@ -0,0 +1,90 @@ +let user=[ + { + traineeEmail: 'trainee1@successive.tech', + reviewerEmail: 'reviewer1@successive.tech' + }, + { + AryanSinghal: 'aryan.singhal@successive.tech', + RahulSadhukhan: 'rahul.sadhukhan@successive.tech' + }, + { + traineeEmail2: 'trainee1@gmail.com', + reviewerEmail2: 'reviewer1@hotmail.com' + }, + { + Aman: 'Aman@successive.tech', + VinayChaudhary: 'vinay.chaudhary@successive.tech' + } +]; +let regex=/[a-z]([[-]*\w+[.]*){1,63}@successive[.]tech$/gmi; +let email; +let temp=[]; +let true_arr=[]; +let false_arr=[]; +validateUser(user); +function validateEmail(email) +{ + if(email.match(regex)) + { + // console.log("true"); + return true; + } + else + { + // console.log("false"); + return false; + } + +} + + +function validateUser(user) +{ + user.forEach(function(value,index) + { + const myobj=Object.values(user[index]); + if(validateEmail(myobj[0])){ + temp=Object.keys(user[index]); + true_arr.push(temp[0]); + } + else + { + temp=Object.keys(user[index]); + false_arr.push(temp[0]); + } + if(validateEmail(myobj[1])){ + temp=Object.keys(user[index]); + true_arr.push(temp[1]); + } + else + { + temp=Object.keys(user[index]); + false_arr.push(temp[1]); + } + + }); + console.log("Valid Users are:\n"); + true_arr.forEach(element => console.log(element)); + console.log("\nNo. of Valid Users: ",true_arr.length); + console.log("-----------------------------------------------------") + console.log("\nInvalid Users are:\n"); + false_arr.forEach(element => console.log(element)); + console.log("\nNo. of Invalid Users: ",false_arr.length); + + +} + + + + + + + + + + +// let boolean = user.map(value,index) => { +// const myobj=Object.values(user[index]) +// if(myobj[0].match(regex)) +// // console.log(); +// }; ///[a-z]([[-]*\w+[.]*){1,63}@successive[.]tech$/gmi \ No newline at end of file From a3187ba88541aa598d1658a42958350fa547c61c Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Fri, 24 Jan 2020 17:13:49 +0530 Subject: [PATCH 15/91] feat: Add package utils --- extra/utils/validation.js | 43 +++++++++++++++++++++------------------ 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/extra/utils/validation.js b/extra/utils/validation.js index b7f47de..ce42d48 100644 --- a/extra/utils/validation.js +++ b/extra/utils/validation.js @@ -4,21 +4,21 @@ let user=[ reviewerEmail: 'reviewer1@successive.tech' }, { - AryanSinghal: 'aryan.singhal@successive.tech', - RahulSadhukhan: 'rahul.sadhukhan@successive.tech' + traineeEmail: 'aryan.singhal@successive.tech', + reviewerEmail: 'rahul.sadhukhan@successive.tech' }, { - traineeEmail2: 'trainee1@gmail.com', - reviewerEmail2: 'reviewer1@hotmail.com' + traineeEmail: 'trainee1@gmail.com', + reviewerEmail: 'reviewer1@hotmail.com' }, { - Aman: 'Aman@successive.tech', - VinayChaudhary: 'vinay.chaudhary@successive.tech' + traineeEmail: 'Aman@successive.tech', + reviewerEmail: 'vinay.chaudhary@successive.tech' } ]; let regex=/[a-z]([[-]*\w+[.]*){1,63}@successive[.]tech$/gmi; let email; -let temp=[]; +//let temp=[]; let true_arr=[]; let false_arr=[]; validateUser(user); @@ -26,12 +26,12 @@ function validateEmail(email) { if(email.match(regex)) { - // console.log("true"); + // console.log("true"); return true; } else { - // console.log("false"); + // console.log("false"); return false; } @@ -42,31 +42,34 @@ function validateUser(user) { user.forEach(function(value,index) { - const myobj=Object.values(user[index]); - if(validateEmail(myobj[0])){ - temp=Object.keys(user[index]); - true_arr.push(temp[0]); + + const {traineeEmail,reviewerEmail}=user[index]; + // console.log(traineeEmail); + //console.log(reviewerEmail); + + if(validateEmail(traineeEmail)){ + true_arr.push(traineeEmail); } else { - temp=Object.keys(user[index]); - false_arr.push(temp[0]); + false_arr.push(traineeEmail); } - if(validateEmail(myobj[1])){ - temp=Object.keys(user[index]); - true_arr.push(temp[1]); + if(validateEmail(reviewerEmail)){ + + true_arr.push(reviewerEmail); } else { - temp=Object.keys(user[index]); - false_arr.push(temp[1]); + false_arr.push(reviewerEmail); } }); + console.log("Valid Users are:\n"); true_arr.forEach(element => console.log(element)); console.log("\nNo. of Valid Users: ",true_arr.length); console.log("-----------------------------------------------------") + console.log("\nInvalid Users are:\n"); false_arr.forEach(element => console.log(element)); console.log("\nNo. of Invalid Users: ",false_arr.length); From 036fa322a1f94d1bb93f5bfe774c9f411d20abc8 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Fri, 24 Jan 2020 18:05:48 +0530 Subject: [PATCH 16/91] feat : Add permissions.js --- extra/utils/permissions.js | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 extra/utils/permissions.js diff --git a/extra/utils/permissions.js b/extra/utils/permissions.js new file mode 100644 index 0000000..2ba6f48 --- /dev/null +++ b/extra/utils/permissions.js @@ -0,0 +1,36 @@ +let permissions={ + 'getUsers': { + all: ['head-trainer'], + read : ['trainee', 'trainer'], + write : ['trainer'], + delete: [], + }, + 'myUsers':{ + all: ['hod'], + read : ['student', 'teacher'], + write : ['teacher'], + delete: ['admin'], + } + }; +console.log(hasPermission("getUsers","trainee","read")); +function hasPermission(moduleName,role,permissionType) +{ + let data=permissions[moduleName]; + let tmp; + if(data[permissionType]===undefined) + return false; + + data[permissionType].forEach(element => { + if(element==role) + { + tmp=true; + } + else + tmp=false; + + }); + return tmp; + + + +} \ No newline at end of file From c090c19e32c9634687885e1596b4d9515238db9c Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Fri, 24 Jan 2020 19:00:59 +0530 Subject: [PATCH 17/91] fix: Add permissions.js --- extra/utils/permissions.js | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/extra/utils/permissions.js b/extra/utils/permissions.js index 2ba6f48..a2f5182 100644 --- a/extra/utils/permissions.js +++ b/extra/utils/permissions.js @@ -16,7 +16,7 @@ console.log(hasPermission("getUsers","trainee","read")); function hasPermission(moduleName,role,permissionType) { let data=permissions[moduleName]; - let tmp; + let tmp=false; if(data[permissionType]===undefined) return false; @@ -24,9 +24,7 @@ function hasPermission(moduleName,role,permissionType) if(element==role) { tmp=true; - } - else - tmp=false; + } }); return tmp; From 16fa13bb7780440e14e775232f54c392d3c2c965 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Mon, 27 Jan 2020 12:24:14 +0530 Subject: [PATCH 18/91] fix: modified conflicts --- extra/utils/permissions.js | 9 ++++----- extra/utils/validation.js | 35 +++++++++++++++-------------------- 2 files changed, 19 insertions(+), 25 deletions(-) diff --git a/extra/utils/permissions.js b/extra/utils/permissions.js index a2f5182..1053795 100644 --- a/extra/utils/permissions.js +++ b/extra/utils/permissions.js @@ -12,9 +12,10 @@ let permissions={ delete: ['admin'], } }; -console.log(hasPermission("getUsers","trainee","read")); + function hasPermission(moduleName,role,permissionType) { + console.log("hasPermission",moduleName,role,permissionType); let data=permissions[moduleName]; let tmp=false; if(data[permissionType]===undefined) @@ -28,7 +29,5 @@ function hasPermission(moduleName,role,permissionType) }); return tmp; - - - -} \ No newline at end of file +} +hasPermission("getUsers","trainee","read"); \ No newline at end of file diff --git a/extra/utils/validation.js b/extra/utils/validation.js index ce42d48..c485fc7 100644 --- a/extra/utils/validation.js +++ b/extra/utils/validation.js @@ -12,16 +12,16 @@ let user=[ reviewerEmail: 'reviewer1@hotmail.com' }, { - traineeEmail: 'Aman@successive.tech', + traineeEmail: 'Aman$2@successive.tech', reviewerEmail: 'vinay.chaudhary@successive.tech' } ]; let regex=/[a-z]([[-]*\w+[.]*){1,63}@successive[.]tech$/gmi; let email; -//let temp=[]; -let true_arr=[]; -let false_arr=[]; -validateUser(user); + +let validEmails=[]; +let invalidEmails=[]; + function validateEmail(email) { if(email.match(regex)) @@ -48,35 +48,35 @@ function validateUser(user) //console.log(reviewerEmail); if(validateEmail(traineeEmail)){ - true_arr.push(traineeEmail); + validEmails.push(traineeEmail); } else { - false_arr.push(traineeEmail); + invalidEmails.push(traineeEmail); } if(validateEmail(reviewerEmail)){ - true_arr.push(reviewerEmail); + validEmails.push(reviewerEmail); } else { - false_arr.push(reviewerEmail); + invalidEmails.push(reviewerEmail); } }); console.log("Valid Users are:\n"); - true_arr.forEach(element => console.log(element)); - console.log("\nNo. of Valid Users: ",true_arr.length); + validEmails.forEach(element => console.log(element)); + console.log("\nNo. of Valid Users: ",validEmails.length); console.log("-----------------------------------------------------") console.log("\nInvalid Users are:\n"); - false_arr.forEach(element => console.log(element)); - console.log("\nNo. of Invalid Users: ",false_arr.length); - - + invalidEmails.forEach(element => console.log(element)); + console.log("\nNo. of Invalid Users: ",invalidEmails.length); } +validateUser(user); + @@ -86,8 +86,3 @@ function validateUser(user) -// let boolean = user.map(value,index) => { -// const myobj=Object.values(user[index]) -// if(myobj[0].match(regex)) -// // console.log(); -// }; ///[a-z]([[-]*\w+[.]*){1,63}@successive[.]tech$/gmi \ No newline at end of file From ad25fb7ffa0a30658f4c245735e7b001d424c3c9 Mon Sep 17 00:00:00 2001 From: AryanSinghalGit <60099465+AryanSinghalGit@users.noreply.github.com> Date: Mon, 27 Jan 2020 17:38:30 +0530 Subject: [PATCH 19/91] "fix: Delete npm-debug.log" --- extra/npm-debug.log | 49 --------------------------------------------- 1 file changed, 49 deletions(-) delete mode 100644 extra/npm-debug.log diff --git a/extra/npm-debug.log b/extra/npm-debug.log deleted file mode 100644 index 2b29a0b..0000000 --- a/extra/npm-debug.log +++ /dev/null @@ -1,49 +0,0 @@ -0 info it worked if it ends with ok -1 verbose cli [ '/usr/bin/nodejs', -1 verbose cli '/usr/bin/npm', -1 verbose cli 'run', -1 verbose cli 'pattern:equilateral' ] -2 info using npm@3.5.2 -3 info using node@v4.2.6 -4 verbose run-script [ 'prepattern:equilateral', -4 verbose run-script 'pattern:equilateral', -4 verbose run-script 'postpattern:equilateral' ] -5 info lifecycle extra@1.0.0~prepattern:equilateral: extra@1.0.0 -6 silly lifecycle extra@1.0.0~prepattern:equilateral: no script for prepattern:equilateral, continuing -7 info lifecycle extra@1.0.0~pattern:equilateral: extra@1.0.0 -8 verbose lifecycle extra@1.0.0~pattern:equilateral: unsafe-perm in lifecycle true -9 verbose lifecycle extra@1.0.0~pattern:equilateral: PATH: /usr/share/npm/bin/node-gyp-bin:/home/aryan.singhal/day2/javascript-server/extra/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin -10 verbose lifecycle extra@1.0.0~pattern:equilateral: CWD: /home/aryan.singhal/day2/javascript-server/extra -11 silly lifecycle extra@1.0.0~pattern:equilateral: Args: [ '-c', 'extra/patterns/equilateral.js' ] -12 info lifecycle extra@1.0.0~pattern:equilateral: Failed to exec pattern:equilateral script -13 verbose stack Error: extra@1.0.0 pattern:equilateral: `extra/patterns/equilateral.js` -13 verbose stack spawn ENOENT -13 verbose stack at ChildProcess. (/usr/share/npm/lib/utils/spawn.js:17:16) -13 verbose stack at emitTwo (events.js:87:13) -13 verbose stack at ChildProcess.emit (events.js:172:7) -13 verbose stack at maybeClose (internal/child_process.js:821:16) -13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5) -14 verbose pkgid extra@1.0.0 -15 verbose cwd /home/aryan.singhal/day2/javascript-server/extra -16 error Linux 4.15.0-45-generic -17 error argv "/usr/bin/nodejs" "/usr/bin/npm" "run" "pattern:equilateral" -18 error node v4.2.6 -19 error npm v3.5.2 -20 error file sh -21 error code ELIFECYCLE -22 error errno ENOENT -23 error syscall spawn -24 error extra@1.0.0 pattern:equilateral: `extra/patterns/equilateral.js` -24 error spawn ENOENT -25 error Failed at the extra@1.0.0 pattern:equilateral script 'extra/patterns/equilateral.js'. -25 error Make sure you have the latest version of node.js and npm installed. -25 error If you do, this is most likely a problem with the extra package, -25 error not with npm itself. -25 error Tell the author that this fails on your system: -25 error extra/patterns/equilateral.js -25 error You can get information on how to open an issue for this project with: -25 error npm bugs extra -25 error Or if that isn't available, you can get their info via: -25 error npm owner ls extra -25 error There is likely additional logging output above. -26 verbose exit [ 1, true ] From 29d066cdb6f50fa613b15a71635547fc2b094d6b Mon Sep 17 00:00:00 2001 From: AryanSinghalGit <60099465+AryanSinghalGit@users.noreply.github.com> Date: Mon, 27 Jan 2020 17:39:04 +0530 Subject: [PATCH 20/91] "feat: Delete npm-debug.log" --- extra/patterns/npm-debug.log | 49 ------------------------------------ 1 file changed, 49 deletions(-) delete mode 100644 extra/patterns/npm-debug.log diff --git a/extra/patterns/npm-debug.log b/extra/patterns/npm-debug.log deleted file mode 100644 index 58adba3..0000000 --- a/extra/patterns/npm-debug.log +++ /dev/null @@ -1,49 +0,0 @@ -0 info it worked if it ends with ok -1 verbose cli [ '/usr/bin/nodejs', -1 verbose cli '/usr/bin/npm', -1 verbose cli 'run', -1 verbose cli 'pattern:equilateral' ] -2 info using npm@3.5.2 -3 info using node@v4.2.6 -4 verbose run-script [ 'prepattern:equilateral', -4 verbose run-script 'pattern:equilateral', -4 verbose run-script 'postpattern:equilateral' ] -5 info lifecycle extra@1.0.0~prepattern:equilateral: extra@1.0.0 -6 silly lifecycle extra@1.0.0~prepattern:equilateral: no script for prepattern:equilateral, continuing -7 info lifecycle extra@1.0.0~pattern:equilateral: extra@1.0.0 -8 verbose lifecycle extra@1.0.0~pattern:equilateral: unsafe-perm in lifecycle true -9 verbose lifecycle extra@1.0.0~pattern:equilateral: PATH: /usr/share/npm/bin/node-gyp-bin:/home/aryan.singhal/day2/javascript-server/extra/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin -10 verbose lifecycle extra@1.0.0~pattern:equilateral: CWD: /home/aryan.singhal/day2/javascript-server/extra -11 silly lifecycle extra@1.0.0~pattern:equilateral: Args: [ '-c', 'extra/patterns/equilateral.js' ] -12 info lifecycle extra@1.0.0~pattern:equilateral: Failed to exec pattern:equilateral script -13 verbose stack Error: extra@1.0.0 pattern:equilateral: `extra/patterns/equilateral.js` -13 verbose stack spawn ENOENT -13 verbose stack at ChildProcess. (/usr/share/npm/lib/utils/spawn.js:17:16) -13 verbose stack at emitTwo (events.js:87:13) -13 verbose stack at ChildProcess.emit (events.js:172:7) -13 verbose stack at maybeClose (internal/child_process.js:821:16) -13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5) -14 verbose pkgid extra@1.0.0 -15 verbose cwd /home/aryan.singhal/day2/javascript-server/extra/patterns -16 error Linux 4.15.0-45-generic -17 error argv "/usr/bin/nodejs" "/usr/bin/npm" "run" "pattern:equilateral" -18 error node v4.2.6 -19 error npm v3.5.2 -20 error file sh -21 error code ELIFECYCLE -22 error errno ENOENT -23 error syscall spawn -24 error extra@1.0.0 pattern:equilateral: `extra/patterns/equilateral.js` -24 error spawn ENOENT -25 error Failed at the extra@1.0.0 pattern:equilateral script 'extra/patterns/equilateral.js'. -25 error Make sure you have the latest version of node.js and npm installed. -25 error If you do, this is most likely a problem with the extra package, -25 error not with npm itself. -25 error Tell the author that this fails on your system: -25 error extra/patterns/equilateral.js -25 error You can get information on how to open an issue for this project with: -25 error npm bugs extra -25 error Or if that isn't available, you can get their info via: -25 error npm owner ls extra -25 error There is likely additional logging output above. -26 verbose exit [ 1, true ] From c25a9140639bb0c61f46371820e2b51fe60e33a4 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Mon, 27 Jan 2020 18:10:42 +0530 Subject: [PATCH 21/91] feat: Add all --- .babelrc | 3 +++ .gitignore | 6 +++++ .vscode/settings.json | 3 +++ extra/constant.js | 17 ++++++++++++ extra/index.js | 31 ++++++++++++++++++++++ extra/npm-debug.log | 49 ----------------------------------- extra/package.json | 14 ---------- extra/patterns/diamond.js | 22 +++++++--------- extra/patterns/equilateral.js | 12 ++++----- extra/patterns/index.js | 4 +++ extra/patterns/npm-debug.log | 49 ----------------------------------- extra/utils/helper.js | 16 ++++++++++++ extra/utils/index.js | 5 ++++ extra/utils/permissions.js | 22 ++++------------ extra/utils/validation.js | 43 +++++------------------------- package.json | 20 ++++++++++++++ 16 files changed, 131 insertions(+), 185 deletions(-) create mode 100644 .babelrc create mode 100644 .gitignore create mode 100644 .vscode/settings.json create mode 100644 extra/constant.js create mode 100644 extra/index.js delete mode 100644 extra/npm-debug.log delete mode 100644 extra/package.json create mode 100644 extra/patterns/index.js delete mode 100644 extra/patterns/npm-debug.log create mode 100644 extra/utils/helper.js create mode 100644 extra/utils/index.js create mode 100644 package.json diff --git a/.babelrc b/.babelrc new file mode 100644 index 0000000..ff3059c --- /dev/null +++ b/.babelrc @@ -0,0 +1,3 @@ +{ + "presets": ["@babel/preset-env"] +} \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1de99a9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ + +#node_modules +node_modules + +#package-lock.json +package-lock.json diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 0000000..3b66410 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,3 @@ +{ + "git.ignoreLimitWarning": true +} \ No newline at end of file diff --git a/extra/constant.js b/extra/constant.js new file mode 100644 index 0000000..830ad48 --- /dev/null +++ b/extra/constant.js @@ -0,0 +1,17 @@ +const permissions={ + 'getUsers': { + all: ['head-trainer'], + read : ['trainee', 'trainer'], + write : ['trainer'], + delete: [], + }, + 'myUsers':{ + all: ['hod'], + read : ['student', 'teacher'], + write : ['teacher'], + delete: ['admin'], + } + }; +export {permissions}; + + diff --git a/extra/index.js b/extra/index.js new file mode 100644 index 0000000..34d9c96 --- /dev/null +++ b/extra/index.js @@ -0,0 +1,31 @@ +import {diamond} from './patterns/index.js'; +import {equilateral} from './patterns/index.js'; +import {hasPermission, validateUser} from './utils/index.js'; +diamond(10); +equilateral(8); +hasPermission("getUsers","trainer","write"); + + +const user=[ + { + traineeEmail: 'trainee1@successive.tech', + reviewerEmail: 'reviewer1@successive.tech' + }, + { + traineeEmail: 'aryan.singhal@successive.tech', + reviewerEmail: 'rahul.sadhukhan@successive.tech' + }, + { + traineeEmail: 'trainee1@gmail.com', + reviewerEmail: 'reviewer1@hotmail.com' + }, + { + traineeEmail: 'Aman$2@successive.tech', + reviewerEmail: 'vinay.chaudhary@successive.tech' + } +]; +validateUser(user); + + + + diff --git a/extra/npm-debug.log b/extra/npm-debug.log deleted file mode 100644 index 2b29a0b..0000000 --- a/extra/npm-debug.log +++ /dev/null @@ -1,49 +0,0 @@ -0 info it worked if it ends with ok -1 verbose cli [ '/usr/bin/nodejs', -1 verbose cli '/usr/bin/npm', -1 verbose cli 'run', -1 verbose cli 'pattern:equilateral' ] -2 info using npm@3.5.2 -3 info using node@v4.2.6 -4 verbose run-script [ 'prepattern:equilateral', -4 verbose run-script 'pattern:equilateral', -4 verbose run-script 'postpattern:equilateral' ] -5 info lifecycle extra@1.0.0~prepattern:equilateral: extra@1.0.0 -6 silly lifecycle extra@1.0.0~prepattern:equilateral: no script for prepattern:equilateral, continuing -7 info lifecycle extra@1.0.0~pattern:equilateral: extra@1.0.0 -8 verbose lifecycle extra@1.0.0~pattern:equilateral: unsafe-perm in lifecycle true -9 verbose lifecycle extra@1.0.0~pattern:equilateral: PATH: /usr/share/npm/bin/node-gyp-bin:/home/aryan.singhal/day2/javascript-server/extra/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin -10 verbose lifecycle extra@1.0.0~pattern:equilateral: CWD: /home/aryan.singhal/day2/javascript-server/extra -11 silly lifecycle extra@1.0.0~pattern:equilateral: Args: [ '-c', 'extra/patterns/equilateral.js' ] -12 info lifecycle extra@1.0.0~pattern:equilateral: Failed to exec pattern:equilateral script -13 verbose stack Error: extra@1.0.0 pattern:equilateral: `extra/patterns/equilateral.js` -13 verbose stack spawn ENOENT -13 verbose stack at ChildProcess. (/usr/share/npm/lib/utils/spawn.js:17:16) -13 verbose stack at emitTwo (events.js:87:13) -13 verbose stack at ChildProcess.emit (events.js:172:7) -13 verbose stack at maybeClose (internal/child_process.js:821:16) -13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5) -14 verbose pkgid extra@1.0.0 -15 verbose cwd /home/aryan.singhal/day2/javascript-server/extra -16 error Linux 4.15.0-45-generic -17 error argv "/usr/bin/nodejs" "/usr/bin/npm" "run" "pattern:equilateral" -18 error node v4.2.6 -19 error npm v3.5.2 -20 error file sh -21 error code ELIFECYCLE -22 error errno ENOENT -23 error syscall spawn -24 error extra@1.0.0 pattern:equilateral: `extra/patterns/equilateral.js` -24 error spawn ENOENT -25 error Failed at the extra@1.0.0 pattern:equilateral script 'extra/patterns/equilateral.js'. -25 error Make sure you have the latest version of node.js and npm installed. -25 error If you do, this is most likely a problem with the extra package, -25 error not with npm itself. -25 error Tell the author that this fails on your system: -25 error extra/patterns/equilateral.js -25 error You can get information on how to open an issue for this project with: -25 error npm bugs extra -25 error Or if that isn't available, you can get their info via: -25 error npm owner ls extra -25 error There is likely additional logging output above. -26 verbose exit [ 1, true ] diff --git a/extra/package.json b/extra/package.json deleted file mode 100644 index 00d2223..0000000 --- a/extra/package.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "name": "extra", - "version": "1.0.0", - "description": "", - "main": "index.js", - "scripts": { - "test": "echo \"Error: no test specified\" && exit 1", - "pattern:diamond":" node patterns/diamond.js", - "pattern:equilateral":"node patterns/equilateral.js" - - }, - "author": "", - "license": "ISC" -} diff --git a/extra/patterns/diamond.js b/extra/patterns/diamond.js index 195f155..3a47bac 100644 --- a/extra/patterns/diamond.js +++ b/extra/patterns/diamond.js @@ -1,32 +1,30 @@ -let n=process.argv[2] - -diamond(n) function diamond(n) { for(let i=0;i0;i--) { - let str="" + let str=""; for(let k=0;k (/usr/share/npm/lib/utils/spawn.js:17:16) -13 verbose stack at emitTwo (events.js:87:13) -13 verbose stack at ChildProcess.emit (events.js:172:7) -13 verbose stack at maybeClose (internal/child_process.js:821:16) -13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5) -14 verbose pkgid extra@1.0.0 -15 verbose cwd /home/aryan.singhal/day2/javascript-server/extra/patterns -16 error Linux 4.15.0-45-generic -17 error argv "/usr/bin/nodejs" "/usr/bin/npm" "run" "pattern:equilateral" -18 error node v4.2.6 -19 error npm v3.5.2 -20 error file sh -21 error code ELIFECYCLE -22 error errno ENOENT -23 error syscall spawn -24 error extra@1.0.0 pattern:equilateral: `extra/patterns/equilateral.js` -24 error spawn ENOENT -25 error Failed at the extra@1.0.0 pattern:equilateral script 'extra/patterns/equilateral.js'. -25 error Make sure you have the latest version of node.js and npm installed. -25 error If you do, this is most likely a problem with the extra package, -25 error not with npm itself. -25 error Tell the author that this fails on your system: -25 error extra/patterns/equilateral.js -25 error You can get information on how to open an issue for this project with: -25 error npm bugs extra -25 error Or if that isn't available, you can get their info via: -25 error npm owner ls extra -25 error There is likely additional logging output above. -26 verbose exit [ 1, true ] diff --git a/extra/utils/helper.js b/extra/utils/helper.js new file mode 100644 index 0000000..3d6b650 --- /dev/null +++ b/extra/utils/helper.js @@ -0,0 +1,16 @@ + +export function validateEmail(email) +{ + const regex=/[a-z]([[-]*\w+[.]*){1,63}@successive[.]tech$/gmi; + if(email.match(regex)) + { + // console.log("true"); + return true; + } + else + { + // console.log("false"); + return false; + } + +} \ No newline at end of file diff --git a/extra/utils/index.js b/extra/utils/index.js new file mode 100644 index 0000000..0d367da --- /dev/null +++ b/extra/utils/index.js @@ -0,0 +1,5 @@ +import hasPermission from './permissions.js'; +export {hasPermission}; + +import validateUser from './validation.js'; +export {validateUser}; diff --git a/extra/utils/permissions.js b/extra/utils/permissions.js index 1053795..674648a 100644 --- a/extra/utils/permissions.js +++ b/extra/utils/permissions.js @@ -1,21 +1,10 @@ -let permissions={ - 'getUsers': { - all: ['head-trainer'], - read : ['trainee', 'trainer'], - write : ['trainer'], - delete: [], - }, - 'myUsers':{ - all: ['hod'], - read : ['student', 'teacher'], - write : ['teacher'], - delete: ['admin'], - } - }; +import {permissions} from '../constant.js'; -function hasPermission(moduleName,role,permissionType) +export default function hasPermission(moduleName,role,permissionType) { console.log("hasPermission",moduleName,role,permissionType); + if(permissions[moduleName]===undefined) + return false; let data=permissions[moduleName]; let tmp=false; if(data[permissionType]===undefined) @@ -29,5 +18,4 @@ function hasPermission(moduleName,role,permissionType) }); return tmp; -} -hasPermission("getUsers","trainee","read"); \ No newline at end of file +} \ No newline at end of file diff --git a/extra/utils/validation.js b/extra/utils/validation.js index c485fc7..ba70590 100644 --- a/extra/utils/validation.js +++ b/extra/utils/validation.js @@ -1,45 +1,14 @@ -let user=[ - { - traineeEmail: 'trainee1@successive.tech', - reviewerEmail: 'reviewer1@successive.tech' - }, - { - traineeEmail: 'aryan.singhal@successive.tech', - reviewerEmail: 'rahul.sadhukhan@successive.tech' - }, - { - traineeEmail: 'trainee1@gmail.com', - reviewerEmail: 'reviewer1@hotmail.com' - }, - { - traineeEmail: 'Aman$2@successive.tech', - reviewerEmail: 'vinay.chaudhary@successive.tech' - } -]; -let regex=/[a-z]([[-]*\w+[.]*){1,63}@successive[.]tech$/gmi; -let email; -let validEmails=[]; -let invalidEmails=[]; +let email; -function validateEmail(email) -{ - if(email.match(regex)) - { - // console.log("true"); - return true; - } - else - { - // console.log("false"); - return false; - } -} +import {validateEmail} from './helper.js'; -function validateUser(user) +export default function validateUser(user) { + let validEmails=[]; + let invalidEmails=[]; user.forEach(function(value,index) { @@ -75,7 +44,7 @@ function validateUser(user) console.log("\nNo. of Invalid Users: ",invalidEmails.length); } -validateUser(user); +//validateUser(user); diff --git a/package.json b/package.json new file mode 100644 index 0000000..bcad8c6 --- /dev/null +++ b/package.json @@ -0,0 +1,20 @@ +{ + "name": "extra", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1", + "pattern:diamond": " node extra/patterns/diamond.js", + "pattern:equilateral": "node extra/patterns/equilateral.js", + "file:index":" extra/index.js" + }, + "type": "module", + "author": "", + "license": "ISC", + "devDependencies": { + "@babel/core": "7.8.3", + "@babel/node": "7.8.3", + "@babel/preset-env": "7.8.3" + } +} From 3230ef35cff54ce86dfc99ee01f2ea518a1ce697 Mon Sep 17 00:00:00 2001 From: AryanSinghalGit <60099465+AryanSinghalGit@users.noreply.github.com> Date: Mon, 27 Jan 2020 18:14:55 +0530 Subject: [PATCH 22/91] Update validation.js --- extra/utils/validation.js | 5 ----- 1 file changed, 5 deletions(-) diff --git a/extra/utils/validation.js b/extra/utils/validation.js index ba70590..8943eb0 100644 --- a/extra/utils/validation.js +++ b/extra/utils/validation.js @@ -1,8 +1,3 @@ - -let email; - - - import {validateEmail} from './helper.js'; export default function validateUser(user) From 8eb6976d671f6eb61701d4868458aab2ea8ac2b2 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Mon, 27 Jan 2020 18:24:10 +0530 Subject: [PATCH 23/91] fix : validation.js --- extra/utils/validation.js | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/extra/utils/validation.js b/extra/utils/validation.js index c485fc7..127f691 100644 --- a/extra/utils/validation.js +++ b/extra/utils/validation.js @@ -16,14 +16,10 @@ let user=[ reviewerEmail: 'vinay.chaudhary@successive.tech' } ]; -let regex=/[a-z]([[-]*\w+[.]*){1,63}@successive[.]tech$/gmi; -let email; - -let validEmails=[]; -let invalidEmails=[]; function validateEmail(email) -{ +{ + let regex=/[a-z]([[-]*\w+[.]*){1,63}@successive[.]tech$/gmi; if(email.match(regex)) { // console.log("true"); @@ -40,6 +36,8 @@ function validateEmail(email) function validateUser(user) { + let validEmails=[]; + let invalidEmails=[]; user.forEach(function(value,index) { From 8cf6cb9906c9cb94895211d734616b62ee853ee5 Mon Sep 17 00:00:00 2001 From: AryanSinghalGit <60099465+AryanSinghalGit@users.noreply.github.com> Date: Mon, 27 Jan 2020 19:15:27 +0530 Subject: [PATCH 24/91] Delete npm-debug.log --- extra/npm-debug.log | 49 --------------------------------------------- 1 file changed, 49 deletions(-) delete mode 100644 extra/npm-debug.log diff --git a/extra/npm-debug.log b/extra/npm-debug.log deleted file mode 100644 index 2b29a0b..0000000 --- a/extra/npm-debug.log +++ /dev/null @@ -1,49 +0,0 @@ -0 info it worked if it ends with ok -1 verbose cli [ '/usr/bin/nodejs', -1 verbose cli '/usr/bin/npm', -1 verbose cli 'run', -1 verbose cli 'pattern:equilateral' ] -2 info using npm@3.5.2 -3 info using node@v4.2.6 -4 verbose run-script [ 'prepattern:equilateral', -4 verbose run-script 'pattern:equilateral', -4 verbose run-script 'postpattern:equilateral' ] -5 info lifecycle extra@1.0.0~prepattern:equilateral: extra@1.0.0 -6 silly lifecycle extra@1.0.0~prepattern:equilateral: no script for prepattern:equilateral, continuing -7 info lifecycle extra@1.0.0~pattern:equilateral: extra@1.0.0 -8 verbose lifecycle extra@1.0.0~pattern:equilateral: unsafe-perm in lifecycle true -9 verbose lifecycle extra@1.0.0~pattern:equilateral: PATH: /usr/share/npm/bin/node-gyp-bin:/home/aryan.singhal/day2/javascript-server/extra/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin -10 verbose lifecycle extra@1.0.0~pattern:equilateral: CWD: /home/aryan.singhal/day2/javascript-server/extra -11 silly lifecycle extra@1.0.0~pattern:equilateral: Args: [ '-c', 'extra/patterns/equilateral.js' ] -12 info lifecycle extra@1.0.0~pattern:equilateral: Failed to exec pattern:equilateral script -13 verbose stack Error: extra@1.0.0 pattern:equilateral: `extra/patterns/equilateral.js` -13 verbose stack spawn ENOENT -13 verbose stack at ChildProcess. (/usr/share/npm/lib/utils/spawn.js:17:16) -13 verbose stack at emitTwo (events.js:87:13) -13 verbose stack at ChildProcess.emit (events.js:172:7) -13 verbose stack at maybeClose (internal/child_process.js:821:16) -13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5) -14 verbose pkgid extra@1.0.0 -15 verbose cwd /home/aryan.singhal/day2/javascript-server/extra -16 error Linux 4.15.0-45-generic -17 error argv "/usr/bin/nodejs" "/usr/bin/npm" "run" "pattern:equilateral" -18 error node v4.2.6 -19 error npm v3.5.2 -20 error file sh -21 error code ELIFECYCLE -22 error errno ENOENT -23 error syscall spawn -24 error extra@1.0.0 pattern:equilateral: `extra/patterns/equilateral.js` -24 error spawn ENOENT -25 error Failed at the extra@1.0.0 pattern:equilateral script 'extra/patterns/equilateral.js'. -25 error Make sure you have the latest version of node.js and npm installed. -25 error If you do, this is most likely a problem with the extra package, -25 error not with npm itself. -25 error Tell the author that this fails on your system: -25 error extra/patterns/equilateral.js -25 error You can get information on how to open an issue for this project with: -25 error npm bugs extra -25 error Or if that isn't available, you can get their info via: -25 error npm owner ls extra -25 error There is likely additional logging output above. -26 verbose exit [ 1, true ] From d79daf3c5606d6e4f0d3ff0574936e69360745d1 Mon Sep 17 00:00:00 2001 From: AryanSinghalGit <60099465+AryanSinghalGit@users.noreply.github.com> Date: Mon, 27 Jan 2020 19:15:37 +0530 Subject: [PATCH 25/91] Delete npm-debug.log --- extra/patterns/npm-debug.log | 49 ------------------------------------ 1 file changed, 49 deletions(-) delete mode 100644 extra/patterns/npm-debug.log diff --git a/extra/patterns/npm-debug.log b/extra/patterns/npm-debug.log deleted file mode 100644 index 58adba3..0000000 --- a/extra/patterns/npm-debug.log +++ /dev/null @@ -1,49 +0,0 @@ -0 info it worked if it ends with ok -1 verbose cli [ '/usr/bin/nodejs', -1 verbose cli '/usr/bin/npm', -1 verbose cli 'run', -1 verbose cli 'pattern:equilateral' ] -2 info using npm@3.5.2 -3 info using node@v4.2.6 -4 verbose run-script [ 'prepattern:equilateral', -4 verbose run-script 'pattern:equilateral', -4 verbose run-script 'postpattern:equilateral' ] -5 info lifecycle extra@1.0.0~prepattern:equilateral: extra@1.0.0 -6 silly lifecycle extra@1.0.0~prepattern:equilateral: no script for prepattern:equilateral, continuing -7 info lifecycle extra@1.0.0~pattern:equilateral: extra@1.0.0 -8 verbose lifecycle extra@1.0.0~pattern:equilateral: unsafe-perm in lifecycle true -9 verbose lifecycle extra@1.0.0~pattern:equilateral: PATH: /usr/share/npm/bin/node-gyp-bin:/home/aryan.singhal/day2/javascript-server/extra/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin -10 verbose lifecycle extra@1.0.0~pattern:equilateral: CWD: /home/aryan.singhal/day2/javascript-server/extra -11 silly lifecycle extra@1.0.0~pattern:equilateral: Args: [ '-c', 'extra/patterns/equilateral.js' ] -12 info lifecycle extra@1.0.0~pattern:equilateral: Failed to exec pattern:equilateral script -13 verbose stack Error: extra@1.0.0 pattern:equilateral: `extra/patterns/equilateral.js` -13 verbose stack spawn ENOENT -13 verbose stack at ChildProcess. (/usr/share/npm/lib/utils/spawn.js:17:16) -13 verbose stack at emitTwo (events.js:87:13) -13 verbose stack at ChildProcess.emit (events.js:172:7) -13 verbose stack at maybeClose (internal/child_process.js:821:16) -13 verbose stack at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5) -14 verbose pkgid extra@1.0.0 -15 verbose cwd /home/aryan.singhal/day2/javascript-server/extra/patterns -16 error Linux 4.15.0-45-generic -17 error argv "/usr/bin/nodejs" "/usr/bin/npm" "run" "pattern:equilateral" -18 error node v4.2.6 -19 error npm v3.5.2 -20 error file sh -21 error code ELIFECYCLE -22 error errno ENOENT -23 error syscall spawn -24 error extra@1.0.0 pattern:equilateral: `extra/patterns/equilateral.js` -24 error spawn ENOENT -25 error Failed at the extra@1.0.0 pattern:equilateral script 'extra/patterns/equilateral.js'. -25 error Make sure you have the latest version of node.js and npm installed. -25 error If you do, this is most likely a problem with the extra package, -25 error not with npm itself. -25 error Tell the author that this fails on your system: -25 error extra/patterns/equilateral.js -25 error You can get information on how to open an issue for this project with: -25 error npm bugs extra -25 error Or if that isn't available, you can get their info via: -25 error npm owner ls extra -25 error There is likely additional logging output above. -26 verbose exit [ 1, true ] From fac02379323c8a2ab660782513719acdf0ddfa77 Mon Sep 17 00:00:00 2001 From: AryanSinghalGit <60099465+AryanSinghalGit@users.noreply.github.com> Date: Mon, 27 Jan 2020 19:16:10 +0530 Subject: [PATCH 26/91] Update validation.js --- extra/utils/validation.js | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/extra/utils/validation.js b/extra/utils/validation.js index 127f691..7357c34 100644 --- a/extra/utils/validation.js +++ b/extra/utils/validation.js @@ -74,13 +74,3 @@ function validateUser(user) } validateUser(user); - - - - - - - - - - From 86cd0ef53596d90eae56a7e41eb0fa9d1ac350fb Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 28 Jan 2020 09:42:21 +0530 Subject: [PATCH 27/91] Add all --- extra/.gitignore | 3 +++ extra/constant.js | 4 +--- extra/index.js | 8 +------- extra/patterns/diamond.js | 2 +- extra/patterns/equilateral.js | 4 +--- extra/patterns/index.js | 1 - extra/utils/helper.js | 2 -- extra/utils/index.js | 2 +- extra/utils/validation.js | 19 +------------------ 9 files changed, 9 insertions(+), 36 deletions(-) create mode 100644 extra/.gitignore diff --git a/extra/.gitignore b/extra/.gitignore new file mode 100644 index 0000000..91e82af --- /dev/null +++ b/extra/.gitignore @@ -0,0 +1,3 @@ +package-lock.json + +node_modules/ \ No newline at end of file diff --git a/extra/constant.js b/extra/constant.js index 830ad48..f8d24eb 100644 --- a/extra/constant.js +++ b/extra/constant.js @@ -12,6 +12,4 @@ const permissions={ delete: ['admin'], } }; -export {permissions}; - - +export {permissions}; \ No newline at end of file diff --git a/extra/index.js b/extra/index.js index 34d9c96..2494a65 100644 --- a/extra/index.js +++ b/extra/index.js @@ -4,8 +4,6 @@ import {hasPermission, validateUser} from './utils/index.js'; diamond(10); equilateral(8); hasPermission("getUsers","trainer","write"); - - const user=[ { traineeEmail: 'trainee1@successive.tech', @@ -24,8 +22,4 @@ const user=[ reviewerEmail: 'vinay.chaudhary@successive.tech' } ]; -validateUser(user); - - - - +validateUser(user); \ No newline at end of file diff --git a/extra/patterns/diamond.js b/extra/patterns/diamond.js index 3a47bac..30ceed4 100644 --- a/extra/patterns/diamond.js +++ b/extra/patterns/diamond.js @@ -27,4 +27,4 @@ for(let i=n;i>0;i--) console.log(str); } } -export default diamond; +export default diamond; \ No newline at end of file diff --git a/extra/patterns/equilateral.js b/extra/patterns/equilateral.js index ff80751..3329b5e 100644 --- a/extra/patterns/equilateral.js +++ b/extra/patterns/equilateral.js @@ -1,7 +1,5 @@ function equilateral(n) { - - for(let i=0;i console.log(element)); console.log("\nNo. of Invalid Users: ",invalidEmails.length); -} - -//validateUser(user); - - - - - - - - - - +} \ No newline at end of file From a136b466dd332ecff572464b13908f9a4c7f72f1 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 28 Jan 2020 09:47:16 +0530 Subject: [PATCH 28/91] fix:conflicts --- extra/utils/validation.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/extra/utils/validation.js b/extra/utils/validation.js index 6737aa5..13228e6 100644 --- a/extra/utils/validation.js +++ b/extra/utils/validation.js @@ -1,6 +1,6 @@ import {validateEmail} from './helper.js'; -export default function validateUser(user) +function validateUser(user) { let validEmails=[]; let invalidEmails=[]; @@ -37,4 +37,5 @@ export default function validateUser(user) console.log("\nInvalid Users are:\n"); invalidEmails.forEach(element => console.log(element)); console.log("\nNo. of Invalid Users: ",invalidEmails.length); -} \ No newline at end of file +} +export default validateUser; \ No newline at end of file From 24b6bdea25f4ccd9d041c1ec326c6125ae979184 Mon Sep 17 00:00:00 2001 From: AryanSinghalGit <60099465+AryanSinghalGit@users.noreply.github.com> Date: Tue, 28 Jan 2020 09:54:13 +0530 Subject: [PATCH 29/91] Update validation.js --- extra/utils/validation.js | 15 ++------------- 1 file changed, 2 insertions(+), 13 deletions(-) diff --git a/extra/utils/validation.js b/extra/utils/validation.js index 8943eb0..c316248 100644 --- a/extra/utils/validation.js +++ b/extra/utils/validation.js @@ -1,6 +1,6 @@ import {validateEmail} from './helper.js'; -export default function validateUser(user) +function validateUser(user) { let validEmails=[]; let invalidEmails=[]; @@ -38,15 +38,4 @@ export default function validateUser(user) invalidEmails.forEach(element => console.log(element)); console.log("\nNo. of Invalid Users: ",invalidEmails.length); } - -//validateUser(user); - - - - - - - - - - +export default validateUser; From 8eeeb7ad5adc28426352695cba2793961dc91856 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 28 Jan 2020 11:36:01 +0530 Subject: [PATCH 30/91] fix : Add package.json --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index bcad8c6..55e8fb7 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "test": "echo \"Error: no test specified\" && exit 1", "pattern:diamond": " node extra/patterns/diamond.js", "pattern:equilateral": "node extra/patterns/equilateral.js", - "file:index":" extra/index.js" + "file:index":"npx babel-node extra" }, "type": "module", "author": "", From 30d94b1b76144625e94dae4b12cd43365f335a0b Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 28 Jan 2020 11:56:11 +0530 Subject: [PATCH 31/91] fix : Add all --- extra/utils/permissions.js | 1 - extra/utils/validation.js | 4 ---- 2 files changed, 5 deletions(-) diff --git a/extra/utils/permissions.js b/extra/utils/permissions.js index 674648a..64b505f 100644 --- a/extra/utils/permissions.js +++ b/extra/utils/permissions.js @@ -1,5 +1,4 @@ import {permissions} from '../constant.js'; - export default function hasPermission(moduleName,role,permissionType) { console.log("hasPermission",moduleName,role,permissionType); diff --git a/extra/utils/validation.js b/extra/utils/validation.js index e8af886..6709acb 100644 --- a/extra/utils/validation.js +++ b/extra/utils/validation.js @@ -5,11 +5,7 @@ function validateUser(user) let invalidEmails=[]; user.forEach(function(value,index) { - const {traineeEmail,reviewerEmail}=user[index]; - // console.log(traineeEmail); - //console.log(reviewerEmail); - if(validateEmail(traineeEmail)){ validEmails.push(traineeEmail); } From c2eb5c995f10fe0ba7b7be780da0f5ea64f849d5 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 28 Jan 2020 20:00:09 +0530 Subject: [PATCH 32/91] feat : Add all --- .babelrc | 5 ++- .gitignore | 4 +- extraTs/constant.ts | 17 ++++++++ extraTs/index.ts | 26 ++++++++++++ extraTs/interface.ts | 15 +++++++ extraTs/patterns/diamond.ts | 23 +++++++++++ extraTs/patterns/equilateral.ts | 14 +++++++ extraTs/patterns/index.ts | 3 ++ extraTs/utils/helper.ts | 9 +++++ extraTs/utils/index.ts | 5 +++ extraTs/utils/permissions.ts | 18 +++++++++ extraTs/utils/validation.ts | 32 +++++++++++++++ package.json | 29 +++++++++++--- tsconfig.json | 31 +++++++++++++++ tslint.json | 70 +++++++++++++++++++++++++++++++++ 15 files changed, 293 insertions(+), 8 deletions(-) create mode 100644 extraTs/constant.ts create mode 100644 extraTs/index.ts create mode 100644 extraTs/interface.ts create mode 100644 extraTs/patterns/diamond.ts create mode 100644 extraTs/patterns/equilateral.ts create mode 100644 extraTs/patterns/index.ts create mode 100644 extraTs/utils/helper.ts create mode 100644 extraTs/utils/index.ts create mode 100644 extraTs/utils/permissions.ts create mode 100644 extraTs/utils/validation.ts create mode 100644 tsconfig.json create mode 100644 tslint.json diff --git a/.babelrc b/.babelrc index ff3059c..f90c71b 100644 --- a/.babelrc +++ b/.babelrc @@ -1,3 +1,6 @@ { - "presets": ["@babel/preset-env"] + "presets": ["@babel/preset-env"], + "plugins": [ + "@babel/plugin-transform-modules-commonjs", + ] } \ No newline at end of file diff --git a/.gitignore b/.gitignore index 1de99a9..06f3657 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,8 @@ - #node_modules node_modules #package-lock.json package-lock.json + +#Package dist +dist \ No newline at end of file diff --git a/extraTs/constant.ts b/extraTs/constant.ts new file mode 100644 index 0000000..016e30f --- /dev/null +++ b/extraTs/constant.ts @@ -0,0 +1,17 @@ +import { Ipermission } from './interface'; + +const permissions: Ipermission = { + 'getUsers': { + all: ['head-trainer'], + read: ['trainee', 'trainer'], + write: ['trainer'], + delete: [], + }, + 'myUsers': { + all: ['hod'], + read: ['student', 'teacher'], + write: ['teacher'], + delete: ['admin'], + } +}; +export { permissions }; \ No newline at end of file diff --git a/extraTs/index.ts b/extraTs/index.ts new file mode 100644 index 0000000..7c19650 --- /dev/null +++ b/extraTs/index.ts @@ -0,0 +1,26 @@ +import { diamond } from './patterns/index'; +import { equilateral } from './patterns/index'; +import { hasPermission, validateUser } from './utils/index'; +import { Iuser } from './interface'; +diamond(10); +equilateral(8); +hasPermission('getUsers', 'trainer', 'write'); +const user: Iuser[] = [ + { + traineeEmail: 'trainee1@successive.tech', + reviewerEmail: 'reviewer1@successive.tech' + }, + { + traineeEmail: 'aryan.singhal@successive.tech', + reviewerEmail: 'rahul.sadhukhan@successive.tech' + }, + { + traineeEmail: 'trainee1@gmail.com', + reviewerEmail: 'reviewer1@hotmail.com' + }, + { + traineeEmail: 'Aman$2@successive.tech', + reviewerEmail: 'vinay.chaudhary@successive.tech' + } +]; +validateUser(user); \ No newline at end of file diff --git a/extraTs/interface.ts b/extraTs/interface.ts new file mode 100644 index 0000000..c46d3da --- /dev/null +++ b/extraTs/interface.ts @@ -0,0 +1,15 @@ +interface Iuser { + traineeEmail: string; + reviewerEmail: string; +} +export { Iuser }; +interface Iauthority { + all: string[]; + read: string[]; + write: string[]; + delete: string[]; +} +interface Ipermission { + [key: string]: Iauthority; +} +export { Ipermission }; \ No newline at end of file diff --git a/extraTs/patterns/diamond.ts b/extraTs/patterns/diamond.ts new file mode 100644 index 0000000..e24f38c --- /dev/null +++ b/extraTs/patterns/diamond.ts @@ -0,0 +1,23 @@ +function diamond(n: number): void { + for (let i: number = 0; i < n; i++) { + let str: string = ''; + for (let k: number = 0; k < n - i - 1; k++) { + str = str + ' '; + } + for (let j: number = 0; j <= i; j++) { + str = str + '* '; + } + console.log(str); + } + for (let i: number = n; i > 0; i--) { + let str: string = ''; + for (let k: number = 0; k < n - i; k++) { + str = str + ' '; + } + for (let j: number = 0; j < i; j++) { + str = str + '* '; + } + console.log(str); + } +} +export default diamond; \ No newline at end of file diff --git a/extraTs/patterns/equilateral.ts b/extraTs/patterns/equilateral.ts new file mode 100644 index 0000000..da4c54d --- /dev/null +++ b/extraTs/patterns/equilateral.ts @@ -0,0 +1,14 @@ +function equilateral(n: number): void { + for (let i: number = 0; i < n; i++) { + let str: string = ''; + for (let k: number = 0; k < n - i - 1; k++) { + str = str + ' '; + } + for (let j: number = 0; j <= i; j++) { + + str = str + '* '; + } + console.log(str); + } +} +export default equilateral; \ No newline at end of file diff --git a/extraTs/patterns/index.ts b/extraTs/patterns/index.ts new file mode 100644 index 0000000..642f75e --- /dev/null +++ b/extraTs/patterns/index.ts @@ -0,0 +1,3 @@ +import diamond from './diamond.js'; +import equilateral from './equilateral.js'; +export { diamond, equilateral }; \ No newline at end of file diff --git a/extraTs/utils/helper.ts b/extraTs/utils/helper.ts new file mode 100644 index 0000000..f46b60c --- /dev/null +++ b/extraTs/utils/helper.ts @@ -0,0 +1,9 @@ +export function validateEmail(email: string): boolean { + const regex: RegExp = /[a-z]([[-]*\w+[.]*){1,63}@successive[.]tech$/gmi; + if (email.match(regex)) { + return true; + } + else { + return false; + } +} \ No newline at end of file diff --git a/extraTs/utils/index.ts b/extraTs/utils/index.ts new file mode 100644 index 0000000..adada6d --- /dev/null +++ b/extraTs/utils/index.ts @@ -0,0 +1,5 @@ +import hasPermission from './permissions.js'; +export { hasPermission }; + +import validateUser from './validation.js'; +export { validateUser }; \ No newline at end of file diff --git a/extraTs/utils/permissions.ts b/extraTs/utils/permissions.ts new file mode 100644 index 0000000..26eaa38 --- /dev/null +++ b/extraTs/utils/permissions.ts @@ -0,0 +1,18 @@ +import { permissions } from '../constant.js'; +export default function hasPermission(moduleName: string, role: string, permissionType: string): boolean { + console.log('hasPermission', moduleName, role, permissionType); + if (permissions[moduleName] === undefined) + return false; + const data = permissions[moduleName]; + let tmp: boolean = false; + if (data[permissionType] === undefined) + return false; + + data[permissionType].forEach(element => { + if (element === role) { + tmp = true; + } + + }); + return tmp; +} \ No newline at end of file diff --git a/extraTs/utils/validation.ts b/extraTs/utils/validation.ts new file mode 100644 index 0000000..760c15c --- /dev/null +++ b/extraTs/utils/validation.ts @@ -0,0 +1,32 @@ +import { validateEmail } from './helper'; +import { Iuser } from '../interface'; +function validateUser(user: Iuser[]): void { + const validEmails: string[] = []; + const invalidEmails: string[] = []; + user.forEach((value: Iuser, index: number) => { + const { traineeEmail, reviewerEmail } = user[index]; + if (validateEmail(traineeEmail)) { + validEmails.push(traineeEmail); + } + else { + invalidEmails.push(traineeEmail); + } + if (validateEmail(reviewerEmail)) { + + validEmails.push(reviewerEmail); + } + else { + invalidEmails.push(reviewerEmail); + } + + }); + console.log('Valid Users are:\n'); + validEmails.forEach(element => console.log(element)); + console.log('\nNo. of Valid Users: ', validEmails.length); + console.log('-----------------------------------------------------'); + + console.log('\nInvalid Users are:\n'); + invalidEmails.forEach(element => console.log(element)); + console.log('\nNo. of Invalid Users: ', invalidEmails.length); +} +export default validateUser; \ No newline at end of file diff --git a/package.json b/package.json index 14a5702..a148519 100644 --- a/package.json +++ b/package.json @@ -1,5 +1,5 @@ { - "name": "extra", + "name": "javascript-server", "version": "1.0.0", "description": "", "main": "index.js", @@ -7,14 +7,31 @@ "test": "echo \"Error: no test specified\" && exit 1", "pattern:diamond": " node extra/patterns/diamond.js", "pattern:equilateral": "node extra/patterns/equilateral.js", - "file:index":"npx babel-node extra" + "file:index":"npx babel-node extra", + "start:extra": "babel-node extra", + "start:extraTs": "tsc-watch --project . --onSuccess \"npm run nodemon\"", + "nodemon": "nodemon ./dist/index.js", + "lint": "./node_modules/tslint/bin/tslint -c tslint.json -p tsconfig.json --exclude 'node_modules/**/*.{j,t}s'", + "lint:fix": "npm run lint --fix" }, - "type": "module", "author": "", "license": "ISC", + "dependencies": { + "@babel/core": "^7.8.3", + "@babel/node": "^7.8.3", + "@babel/preset-env": "^7.8.3", + "@types/node": "^13.5.0", + "babel": "^6.23.0", + "babel-node": "0.0.1-security", + "commitizen": "^4.0.3", + "husky": "^4.2.1", + "nodemon": "^2.0.2", + "pre-commit": "^1.2.2", + "pre-push": "^0.1.1", + "tslint": "^6.0.0" + }, "devDependencies": { - "@babel/core": "7.8.3", - "@babel/node": "7.8.3", - "@babel/preset-env": "7.8.3" + "tsc-watch": "^4.1.0", + "typescript": "^3.7.5" } } \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..d13bb67 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "module": "commonjs", + "target": "es6", + "noImplicitAny": false, + "moduleResolution": "node", + "allowSyntheticDefaultImports": true, + "resolveJsonModule": true, + "esModuleInterop": false, + "allowJs": true /* Allow javascript files to be compiled. */, + "checkJs": false /* Report errors in .js files. */, + "sourceMap": true, + "outDir": "./dist", + "baseUrl": ".", + "paths": { + "*": [ + "node_modules/*", + "src/types/*" + ] + }, + }, + "exclude": [ + "dist" + ], + "include": [ + "extraTs" + ], + "types": [ + "src/types" + ] +} \ No newline at end of file diff --git a/tslint.json b/tslint.json new file mode 100644 index 0000000..8627218 --- /dev/null +++ b/tslint.json @@ -0,0 +1,70 @@ +{ + "defaultSeverity": "error", + "extends": [ + "tslint:recommended" + ], + "jsRules": {}, + "rules": { + "class-name": true, + "comment-format": [ + true, + "check-space" + ], + "indent": [ + true, + "spaces", + 2 + ], + "one-line": [ + true, + "check-open-brace", + "check-whitespace" + ], + "no-var-keyword": true, + "quotemark": [ + true, + "single", + "avoid-escape" + ], + "semicolon": [ + true, + "always", + "ignore-bound-class-methods" + ], + "whitespace": [ + true, + "check-branch", + "check-decl", + "check-operator", + "check-module", + "check-separator", + "check-type" + ], + "typedef-whitespace": [ + true, + { + "call-signature": "nospace", + "index-signature": "nospace", + "parameter": "nospace", + "property-declaration": "nospace", + "variable-declaration": "nospace" + }, + { + "call-signature": "onespace", + "index-signature": "onespace", + "parameter": "onespace", + "property-declaration": "onespace", + "variable-declaration": "onespace" + } + ], + "no-internal-module": true, + "no-trailing-whitespace": true, + "no-null-keyword": true, + "prefer-const": true, + "jsdoc-format": true, + "no-console": [ + false + ] + }, + "rulesDirectory": [] +} \ No newline at end of file From d55a0b33a793efe476755fefe8669bbec4fa57e0 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 28 Jan 2020 20:04:24 +0530 Subject: [PATCH 33/91] feat : Add all --- package.json | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/package.json b/package.json index a148519..7f5c586 100644 --- a/package.json +++ b/package.json @@ -14,6 +14,11 @@ "lint": "./node_modules/tslint/bin/tslint -c tslint.json -p tsconfig.json --exclude 'node_modules/**/*.{j,t}s'", "lint:fix": "npm run lint --fix" }, + "husky": { + "hooks": { + "pre-commit": "npm test", + "pre-push": "npm test", + } , "author": "", "license": "ISC", "dependencies": { From 8ba62be0d4dad26cb866e75c5d5aed24f7c05c55 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 28 Jan 2020 20:07:06 +0530 Subject: [PATCH 34/91] feat : Add all --- package.json | 54 ++++++++++++++++++++++++++-------------------------- 1 file changed, 27 insertions(+), 27 deletions(-) diff --git a/package.json b/package.json index 7f5c586..2be4222 100644 --- a/package.json +++ b/package.json @@ -7,36 +7,36 @@ "test": "echo \"Error: no test specified\" && exit 1", "pattern:diamond": " node extra/patterns/diamond.js", "pattern:equilateral": "node extra/patterns/equilateral.js", - "file:index":"npx babel-node extra", + "file:index": "npx babel-node extra", "start:extra": "babel-node extra", "start:extraTs": "tsc-watch --project . --onSuccess \"npm run nodemon\"", "nodemon": "nodemon ./dist/index.js", "lint": "./node_modules/tslint/bin/tslint -c tslint.json -p tsconfig.json --exclude 'node_modules/**/*.{j,t}s'", "lint:fix": "npm run lint --fix" }, - "husky": { - "hooks": { - "pre-commit": "npm test", - "pre-push": "npm test", - } , - "author": "", - "license": "ISC", - "dependencies": { - "@babel/core": "^7.8.3", - "@babel/node": "^7.8.3", - "@babel/preset-env": "^7.8.3", - "@types/node": "^13.5.0", - "babel": "^6.23.0", - "babel-node": "0.0.1-security", - "commitizen": "^4.0.3", - "husky": "^4.2.1", - "nodemon": "^2.0.2", - "pre-commit": "^1.2.2", - "pre-push": "^0.1.1", - "tslint": "^6.0.0" - }, - "devDependencies": { - "tsc-watch": "^4.1.0", - "typescript": "^3.7.5" - } -} \ No newline at end of file + "husky": { + "hooks": { + "pre-commit": "npm test && npm run lint ", + "pre-push": "npm test && npm run lint", + }, + "author": "", + "license": "ISC", + "dependencies": { + "@babel/core": "^7.8.3", + "@babel/node": "^7.8.3", + "@babel/preset-env": "^7.8.3", + "@types/node": "^13.5.0", + "babel": "^6.23.0", + "babel-node": "0.0.1-security", + "commitizen": "^4.0.3", + "husky": "^4.2.1", + "nodemon": "^2.0.2", + "pre-commit": "^1.2.2", + "pre-push": "^0.1.1", + "tslint": "^6.0.0" + }, + "devDependencies": { + "tsc-watch": "^4.1.0", + "typescript": "^3.7.5" + } + } \ No newline at end of file From 6fee54481b8d4bcd0336fda4b0ef20b69d02b7f7 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 28 Jan 2020 20:08:46 +0530 Subject: [PATCH 35/91] feat : Add all --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 2be4222..b25cebd 100644 --- a/package.json +++ b/package.json @@ -17,7 +17,7 @@ "husky": { "hooks": { "pre-commit": "npm test && npm run lint ", - "pre-push": "npm test && npm run lint", + "pre-push": "npm test && npm run lint " }, "author": "", "license": "ISC", From eb6c5c650aef583c045d89ad8bf65ebe5573576a Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 28 Jan 2020 20:10:47 +0530 Subject: [PATCH 36/91] feat : Add all --- package.json | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index b25cebd..2b428b6 100644 --- a/package.json +++ b/package.json @@ -12,13 +12,10 @@ "start:extraTs": "tsc-watch --project . --onSuccess \"npm run nodemon\"", "nodemon": "nodemon ./dist/index.js", "lint": "./node_modules/tslint/bin/tslint -c tslint.json -p tsconfig.json --exclude 'node_modules/**/*.{j,t}s'", - "lint:fix": "npm run lint --fix" + "lint:fix": "npm run lint --fix", + "pre-commit": "npm test && npm run lint ", + "pre-push": "npm test && npm run lint " }, - "husky": { - "hooks": { - "pre-commit": "npm test && npm run lint ", - "pre-push": "npm test && npm run lint " - }, "author": "", "license": "ISC", "dependencies": { @@ -39,4 +36,4 @@ "tsc-watch": "^4.1.0", "typescript": "^3.7.5" } - } \ No newline at end of file +} \ No newline at end of file From 8900817b66d753580556634240c6974f49da6fdf Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Wed, 29 Jan 2020 14:34:38 +0530 Subject: [PATCH 37/91] fix: package.json --- package.json | 44 +++++++++++++++++++++++--------------------- 1 file changed, 23 insertions(+), 21 deletions(-) diff --git a/package.json b/package.json index 2b428b6..b58422e 100644 --- a/package.json +++ b/package.json @@ -16,24 +16,26 @@ "pre-commit": "npm test && npm run lint ", "pre-push": "npm test && npm run lint " }, - "author": "", - "license": "ISC", - "dependencies": { - "@babel/core": "^7.8.3", - "@babel/node": "^7.8.3", - "@babel/preset-env": "^7.8.3", - "@types/node": "^13.5.0", - "babel": "^6.23.0", - "babel-node": "0.0.1-security", - "commitizen": "^4.0.3", - "husky": "^4.2.1", - "nodemon": "^2.0.2", - "pre-commit": "^1.2.2", - "pre-push": "^0.1.1", - "tslint": "^6.0.0" - }, - "devDependencies": { - "tsc-watch": "^4.1.0", - "typescript": "^3.7.5" - } -} \ No newline at end of file + "author": "", + "license": "ISC", + "dependencies": { + "@babel/core": "^7.8.3", + "@babel/node": "^7.8.3", + "@babel/preset-env": "^7.8.3", + "@types/node": "^13.5.0", + "babel": "^6.23.0", + "babel-node": "0.0.1-security", + "commitizen": "^4.0.3", + "dotenv": "^8.2.0", + "express": "^4.17.1", + "husky": "^4.2.1", + "nodemon": "^2.0.2", + "pre-commit": "^1.2.2", + "pre-push": "^0.1.1", + "tslint": "^6.0.0" + }, + "devDependencies": { + "tsc-watch": "^4.1.0", + "typescript": "^3.7.5" + } +} From c09e703ebc5067b68b232fa114aea6edce5f8f79 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Wed, 29 Jan 2020 14:36:27 +0530 Subject: [PATCH 38/91] fix: Add package.json --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 14a5702..a8ab480 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,7 @@ "test": "echo \"Error: no test specified\" && exit 1", "pattern:diamond": " node extra/patterns/diamond.js", "pattern:equilateral": "node extra/patterns/equilateral.js", - "file:index":"npx babel-node extra" + "start:extra":"npx babel-node extra" }, "type": "module", "author": "", From 28506cadb9162c5b8b045c1de52076db6c7c50ca Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Wed, 29 Jan 2020 14:42:54 +0530 Subject: [PATCH 39/91] fix: Add package.json --- package.json | 1 - 1 file changed, 1 deletion(-) diff --git a/package.json b/package.json index b58422e..e96acee 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,6 @@ "test": "echo \"Error: no test specified\" && exit 1", "pattern:diamond": " node extra/patterns/diamond.js", "pattern:equilateral": "node extra/patterns/equilateral.js", - "file:index": "npx babel-node extra", "start:extra": "babel-node extra", "start:extraTs": "tsc-watch --project . --onSuccess \"npm run nodemon\"", "nodemon": "nodemon ./dist/index.js", From f919b5f3cc25317f406a993d4ba1d4b7aaf360ce Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Wed, 29 Jan 2020 17:00:00 +0530 Subject: [PATCH 40/91] feat : Add all --- .babelrc | 4 +--- .env | 2 ++ package.json | 45 ++++++++++++++++++++----------------- src/Server.ts | 27 ++++++++++++++++++++++ src/config/IConfig.ts | 4 ++++ src/config/configuration.ts | 12 ++++++++++ src/index.ts | 5 +++++ tsconfig.json | 2 +- 8 files changed, 76 insertions(+), 25 deletions(-) create mode 100644 .env create mode 100644 src/Server.ts create mode 100644 src/config/IConfig.ts create mode 100644 src/config/configuration.ts create mode 100644 src/index.ts diff --git a/.babelrc b/.babelrc index f90c71b..4ee296f 100644 --- a/.babelrc +++ b/.babelrc @@ -1,6 +1,4 @@ { "presets": ["@babel/preset-env"], - "plugins": [ - "@babel/plugin-transform-modules-commonjs", - ] + "plugins": ["@babel/plugin-transform-modules-commonjs"] } \ No newline at end of file diff --git a/.env b/.env new file mode 100644 index 0000000..78fb9cd --- /dev/null +++ b/.env @@ -0,0 +1,2 @@ +PORT=9000 +NODE_ENV=dev \ No newline at end of file diff --git a/package.json b/package.json index 2b428b6..635615b 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "pattern:equilateral": "node extra/patterns/equilateral.js", "file:index": "npx babel-node extra", "start:extra": "babel-node extra", + "start:src": "tsc-watch --project . --onSuccess \"npm run nodemon\"", "start:extraTs": "tsc-watch --project . --onSuccess \"npm run nodemon\"", "nodemon": "nodemon ./dist/index.js", "lint": "./node_modules/tslint/bin/tslint -c tslint.json -p tsconfig.json --exclude 'node_modules/**/*.{j,t}s'", @@ -16,24 +17,26 @@ "pre-commit": "npm test && npm run lint ", "pre-push": "npm test && npm run lint " }, - "author": "", - "license": "ISC", - "dependencies": { - "@babel/core": "^7.8.3", - "@babel/node": "^7.8.3", - "@babel/preset-env": "^7.8.3", - "@types/node": "^13.5.0", - "babel": "^6.23.0", - "babel-node": "0.0.1-security", - "commitizen": "^4.0.3", - "husky": "^4.2.1", - "nodemon": "^2.0.2", - "pre-commit": "^1.2.2", - "pre-push": "^0.1.1", - "tslint": "^6.0.0" - }, - "devDependencies": { - "tsc-watch": "^4.1.0", - "typescript": "^3.7.5" - } -} \ No newline at end of file + "author": "", + "license": "ISC", + "dependencies": { + "@babel/core": "^7.8.3", + "@babel/node": "^7.8.3", + "@babel/preset-env": "^7.8.3", + "@types/node": "^13.5.1", + "babel": "^6.23.0", + "babel-node": "0.0.1-security", + "commitizen": "^4.0.3", + "dotenv": "^8.2.0", + "express": "^4.17.1", + "husky": "^4.2.1", + "nodemon": "^2.0.2", + "pre-commit": "^1.2.2", + "pre-push": "^0.1.1", + "tslint": "^6.0.0" + }, + "devDependencies": { + "tsc-watch": "^4.1.0", + "typescript": "^3.7.5" + } +} diff --git a/src/Server.ts b/src/Server.ts new file mode 100644 index 0000000..6b99369 --- /dev/null +++ b/src/Server.ts @@ -0,0 +1,27 @@ +import * as express from 'express'; +export class Server { + private app; + constructor(protected config) { + this.app = express(); + } + public bootstrap = () => { + this.setupRoutes(); + } + public run = () => { + const {app , config: { Port } } = this; + + app.listen(Port, (err) => { + if (err) { + console.log(err); + } + else { + console.log(`Express app Successfully started on port : ${Port} `); + } + }); + return this; + } + public setupRoutes = () => { + const { app } = this; + this.app.get('/health-check', (req, res) => res.send('I am OK')); + } +} \ No newline at end of file diff --git a/src/config/IConfig.ts b/src/config/IConfig.ts new file mode 100644 index 0000000..232f521 --- /dev/null +++ b/src/config/IConfig.ts @@ -0,0 +1,4 @@ +export interface IConfig { + Port: string; + NODE_ENV: string; +} \ No newline at end of file diff --git a/src/config/configuration.ts b/src/config/configuration.ts new file mode 100644 index 0000000..c2cea54 --- /dev/null +++ b/src/config/configuration.ts @@ -0,0 +1,12 @@ +import { IConfig } from './IConfig'; +import { config } from 'dotenv'; + +config(); + +const configuration: IConfig = { + Port : process.env.PORT, + NODE_ENV : process.env.NODE_ENV +}; +Object.freeze(configuration); + +export default configuration; \ No newline at end of file diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..55eb21d --- /dev/null +++ b/src/index.ts @@ -0,0 +1,5 @@ +import { Server } from './Server'; +import config from './config/configuration'; +const server = new Server(config); +server.bootstrap(); +server.run(); \ No newline at end of file diff --git a/tsconfig.json b/tsconfig.json index d13bb67..2845fea 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -23,7 +23,7 @@ "dist" ], "include": [ - "extraTs" + "src" ], "types": [ "src/types" From 01251f2a1373cfc40df468b1a8a919c7575217e3 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Wed, 29 Jan 2020 18:20:23 +0530 Subject: [PATCH 41/91] feat : Add all --- package.json | 1 + src/Server.ts | 13 +++++++------ src/index.ts | 2 +- 3 files changed, 9 insertions(+), 7 deletions(-) diff --git a/package.json b/package.json index 635615b..a5b6e7d 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "@babel/core": "^7.8.3", "@babel/node": "^7.8.3", "@babel/preset-env": "^7.8.3", + "@types/express": "^4.17.2", "@types/node": "^13.5.1", "babel": "^6.23.0", "babel-node": "0.0.1-security", diff --git a/src/Server.ts b/src/Server.ts index 6b99369..6caec93 100644 --- a/src/Server.ts +++ b/src/Server.ts @@ -1,14 +1,15 @@ import * as express from 'express'; export class Server { - private app; + private app: express.Express; constructor(protected config) { this.app = express(); } - public bootstrap = () => { + public bootstrap = (): Server => { this.setupRoutes(); + return this; } - public run = () => { - const {app , config: { Port } } = this; + public run = (): Server => { + const {app , config: { Port } }: Server = this; app.listen(Port, (err) => { if (err) { @@ -20,8 +21,8 @@ export class Server { }); return this; } - public setupRoutes = () => { - const { app } = this; + public setupRoutes = (): void => { + const { app }: Server = this; this.app.get('/health-check', (req, res) => res.send('I am OK')); } } \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index 55eb21d..481013e 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,5 +1,5 @@ import { Server } from './Server'; import config from './config/configuration'; -const server = new Server(config); +const server: Server = new Server(config); server.bootstrap(); server.run(); \ No newline at end of file From 5133925c17be649ca87e8b33b3e5bce7686b845e Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Thu, 30 Jan 2020 15:38:21 +0530 Subject: [PATCH 42/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Add=20body-parser?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 39522 --- package.json | 4 +++- src/Server.ts | 16 +++++++++++++--- src/libs/routes/errorHandler.ts | 8 ++++++++ src/libs/routes/notFoundRoute.ts | 6 ++++++ 4 files changed, 30 insertions(+), 4 deletions(-) create mode 100644 src/libs/routes/errorHandler.ts create mode 100644 src/libs/routes/notFoundRoute.ts diff --git a/package.json b/package.json index bd85e7e..c692547 100644 --- a/package.json +++ b/package.json @@ -14,7 +14,8 @@ "lint": "./node_modules/tslint/bin/tslint -c tslint.json -p tsconfig.json --exclude 'node_modules/**/*.{j,t}s'", "lint:fix": "npm run lint --fix", "pre-commit": "npm test && npm run lint ", - "pre-push": "npm test && npm run lint " + "pre-push": "npm test && npm run lint ", + "commit": "npx git-cz" }, "author": "", "license": "ISC", @@ -26,6 +27,7 @@ "@types/node": "^13.5.1", "babel": "^6.23.0", "babel-node": "0.0.1-security", + "body-parser": "^1.19.0", "commitizen": "^4.0.3", "dotenv": "^8.2.0", "express": "^4.17.1", diff --git a/src/Server.ts b/src/Server.ts index 6caec93..f11e673 100644 --- a/src/Server.ts +++ b/src/Server.ts @@ -1,4 +1,7 @@ import * as express from 'express'; +import * as bodyParser from 'body-parser'; +import notFoundRoute from './libs/routes/notFoundRoute'; +import errorHandler from './libs/routes/errorHandler'; export class Server { private app: express.Express; constructor(protected config) { @@ -6,11 +9,11 @@ export class Server { } public bootstrap = (): Server => { this.setupRoutes(); + this.initBodyParser(); return this; } public run = (): Server => { - const {app , config: { Port } }: Server = this; - + const { app, config: { Port } }: Server = this; app.listen(Port, (err) => { if (err) { console.log(err); @@ -21,8 +24,15 @@ export class Server { }); return this; } + public initBodyParser = () => { + const { app } = this; + app.use(bodyParser.urlencoded({ extended: false })); + app.use(bodyParser.json()); + } public setupRoutes = (): void => { const { app }: Server = this; - this.app.get('/health-check', (req, res) => res.send('I am OK')); + app.get('/health-check', (req: express.Request, res: express.Response) => res.send('I am OK')); + app.use(notFoundRoute); + app.use(errorHandler); } } \ No newline at end of file diff --git a/src/libs/routes/errorHandler.ts b/src/libs/routes/errorHandler.ts new file mode 100644 index 0000000..d162736 --- /dev/null +++ b/src/libs/routes/errorHandler.ts @@ -0,0 +1,8 @@ +import * as express from 'express'; +const errorHandler = (err: express.ErrorRequestHandler, req: express.Request, res: express.Response, next: express.NextFunction): void => { + res.send({ + error: 'Not Found', message: 'error', status: 500, timestamp: new Date() + }); + res.end('ok'); +}; +export default errorHandler; \ No newline at end of file diff --git a/src/libs/routes/notFoundRoute.ts b/src/libs/routes/notFoundRoute.ts new file mode 100644 index 0000000..89d4547 --- /dev/null +++ b/src/libs/routes/notFoundRoute.ts @@ -0,0 +1,6 @@ +import * as express from 'express'; +const notFoundRoute = (req: express.Request, res: express.Response, next): express.ErrorRequestHandler => { + const err = new Error('Not Found'); + return next(err); +}; +export default notFoundRoute; \ No newline at end of file From b3da5222cd53743566a224f7a73e10a3666078a8 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Thu, 30 Jan 2020 15:40:18 +0530 Subject: [PATCH 43/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Add=20body-parser?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 ++ 1 file changed, 2 insertions(+) diff --git a/package.json b/package.json index c692547..b439121 100644 --- a/package.json +++ b/package.json @@ -29,8 +29,10 @@ "babel-node": "0.0.1-security", "body-parser": "^1.19.0", "commitizen": "^4.0.3", + "cz-conventional-changelog": "^3.1.0", "dotenv": "^8.2.0", "express": "^4.17.1", + "git-cz": "^4.2.0", "husky": "^4.2.1", "nodemon": "^2.0.2", "pre-commit": "^1.2.2", From 798b65c1df178708ee846b613c3a3a2be56abfb9 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Thu, 30 Jan 2020 15:49:13 +0530 Subject: [PATCH 44/91] =?UTF-8?q?refactor:=20=F0=9F=92=A1=20Define=20type?= =?UTF-8?q?=20of=20req=20and=20res?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 39521 --- package.json | 1 + src/Server.ts | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index bd85e7e..8fbb2fc 100644 --- a/package.json +++ b/package.json @@ -29,6 +29,7 @@ "commitizen": "^4.0.3", "dotenv": "^8.2.0", "express": "^4.17.1", + "git-cz": "^4.2.0", "husky": "^4.2.1", "nodemon": "^2.0.2", "pre-commit": "^1.2.2", diff --git a/src/Server.ts b/src/Server.ts index 6caec93..6ff5236 100644 --- a/src/Server.ts +++ b/src/Server.ts @@ -23,6 +23,6 @@ export class Server { } public setupRoutes = (): void => { const { app }: Server = this; - this.app.get('/health-check', (req, res) => res.send('I am OK')); + this.app.get('/health-check', (req: express.Request, res: express.Response) => res.send('I am OK')); } } \ No newline at end of file From 11399699eb30354d4826dffe236e3981fda7a7cf Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Thu, 30 Jan 2020 16:51:28 +0530 Subject: [PATCH 45/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Add=20body-parser?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 39522 --- src/Server.ts | 3 +-- src/libs/routes/index.ts | 2 ++ 2 files changed, 3 insertions(+), 2 deletions(-) create mode 100644 src/libs/routes/index.ts diff --git a/src/Server.ts b/src/Server.ts index f11e673..b4784c5 100644 --- a/src/Server.ts +++ b/src/Server.ts @@ -1,7 +1,6 @@ import * as express from 'express'; import * as bodyParser from 'body-parser'; -import notFoundRoute from './libs/routes/notFoundRoute'; -import errorHandler from './libs/routes/errorHandler'; +import { notFoundRoute , errorHandler } from './libs/routes'; export class Server { private app: express.Express; constructor(protected config) { diff --git a/src/libs/routes/index.ts b/src/libs/routes/index.ts new file mode 100644 index 0000000..04bbfc3 --- /dev/null +++ b/src/libs/routes/index.ts @@ -0,0 +1,2 @@ +export { default as errorHandler } from './errorHandler'; +export { default as notFoundRoute }from './notFoundRoute'; \ No newline at end of file From 2fc9cf18e8be728b0e4c38cdb7b98d88db528fe5 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Fri, 31 Jan 2020 16:08:57 +0530 Subject: [PATCH 46/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Add=20Controller?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 39523 --- src/Controllers/index.ts | 1 + src/Controllers/trainee/Controller.ts | 69 +++++++++++++++++++++++++++ src/Controllers/trainee/index.ts | 2 + src/Controllers/trainee/routes.ts | 10 ++++ src/Controllers/user/Controller.ts | 0 src/Controllers/user/index.ts | 0 src/Controllers/user/routes.ts | 0 src/Server.ts | 2 + src/router.ts | 5 ++ 9 files changed, 89 insertions(+) create mode 100644 src/Controllers/index.ts create mode 100644 src/Controllers/trainee/Controller.ts create mode 100644 src/Controllers/trainee/index.ts create mode 100644 src/Controllers/trainee/routes.ts create mode 100644 src/Controllers/user/Controller.ts create mode 100644 src/Controllers/user/index.ts create mode 100644 src/Controllers/user/routes.ts create mode 100644 src/router.ts diff --git a/src/Controllers/index.ts b/src/Controllers/index.ts new file mode 100644 index 0000000..8bcca84 --- /dev/null +++ b/src/Controllers/index.ts @@ -0,0 +1 @@ +export { traineeRouter, TraineeControllerInstance } from './trainee'; \ No newline at end of file diff --git a/src/Controllers/trainee/Controller.ts b/src/Controllers/trainee/Controller.ts new file mode 100644 index 0000000..dcc3018 --- /dev/null +++ b/src/Controllers/trainee/Controller.ts @@ -0,0 +1,69 @@ +class Controller { + static instance: Controller; + static getInstance = () => { + if (Controller.instance) { + return Controller.instance; + } + else { + Controller.instance = new Controller(); + return Controller.instance; + } + } + create = (req, res) => { + console.log('----------Create Trainee----------'); + res.send({ + status: 'ok', + message: 'Trainee added successfully', + data: { + id: 241, + name: 'Aman', + address: 'Ghaziabad' + } + }); + }; + list = (req, res) => { + console.log('----------Trainee List----------'); + res.send({ + status: 'ok', + message: 'Trainee List', + data: [{ + id: 241, + name: 'Aman', + address: 'Ghaziabad' + }, + { + id: 242, + name: 'Aryan', + address: 'Noida' + }, + { + id: 243, + name: 'Neeraj', + address: 'Delhi' + }] + } + ); + }; + update = (req, res) => { + console.log('----------Update Trainee----------'); + res.send({ + status: 'ok', + message: 'Trainee Data successfully Updated', + data: { + id: 241, + name: 'Divyam', + address: 'Gurugram' + } + }); + }; + delete = (req, res) => { + console.log('----------Delete Trainee----------'); + res.send( + { + status: 'ok', + message: 'Trainee Data Successfully Deleted' + } + ); + }; +} +export default Controller.getInstance(); \ No newline at end of file diff --git a/src/Controllers/trainee/index.ts b/src/Controllers/trainee/index.ts new file mode 100644 index 0000000..2905a31 --- /dev/null +++ b/src/Controllers/trainee/index.ts @@ -0,0 +1,2 @@ +export { default as traineeRouter } from './routes'; +export { default as TraineeControllerInstance } from './Controller'; \ No newline at end of file diff --git a/src/Controllers/trainee/routes.ts b/src/Controllers/trainee/routes.ts new file mode 100644 index 0000000..6d1e31c --- /dev/null +++ b/src/Controllers/trainee/routes.ts @@ -0,0 +1,10 @@ +import { Router } from 'express'; +import Controller from './Controller'; +const traineeRouter = Router(); +traineeRouter.route('/') + .get(Controller.create) + .post(Controller.list); +traineeRouter.route('/:id') + .delete(Controller.delete) + .put(Controller.update); +export default traineeRouter; \ No newline at end of file diff --git a/src/Controllers/user/Controller.ts b/src/Controllers/user/Controller.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/Controllers/user/index.ts b/src/Controllers/user/index.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/Controllers/user/routes.ts b/src/Controllers/user/routes.ts new file mode 100644 index 0000000..e69de29 diff --git a/src/Server.ts b/src/Server.ts index b4784c5..e5884bd 100644 --- a/src/Server.ts +++ b/src/Server.ts @@ -1,6 +1,7 @@ import * as express from 'express'; import * as bodyParser from 'body-parser'; import { notFoundRoute , errorHandler } from './libs/routes'; +import { default as mainRouter } from './router'; export class Server { private app: express.Express; constructor(protected config) { @@ -31,6 +32,7 @@ export class Server { public setupRoutes = (): void => { const { app }: Server = this; app.get('/health-check', (req: express.Request, res: express.Response) => res.send('I am OK')); + app.use('/api', mainRouter); app.use(notFoundRoute); app.use(errorHandler); } diff --git a/src/router.ts b/src/router.ts new file mode 100644 index 0000000..d258949 --- /dev/null +++ b/src/router.ts @@ -0,0 +1,5 @@ +import { Router } from 'express'; +import { traineeRouter } from './Controllers/trainee'; +const mainRouter = Router(); +mainRouter.use('/user', traineeRouter); +export default mainRouter; From 25ff0e954af955a0bcc3e7f7ceb80932f660ec34 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Fri, 31 Jan 2020 16:31:04 +0530 Subject: [PATCH 47/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Add=20Controller?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 39523 --- src/Controllers/trainee/Controller.ts | 9 +++++---- src/Controllers/trainee/routes.ts | 2 +- src/router.ts | 2 +- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/Controllers/trainee/Controller.ts b/src/Controllers/trainee/Controller.ts index dcc3018..1fecdeb 100644 --- a/src/Controllers/trainee/Controller.ts +++ b/src/Controllers/trainee/Controller.ts @@ -1,3 +1,4 @@ +import { Request, Response } from 'express'; class Controller { static instance: Controller; static getInstance = () => { @@ -9,7 +10,7 @@ class Controller { return Controller.instance; } } - create = (req, res) => { + create = (req: Request, res: Response) => { console.log('----------Create Trainee----------'); res.send({ status: 'ok', @@ -21,7 +22,7 @@ class Controller { } }); }; - list = (req, res) => { + list = (req: Request, res: Response) => { console.log('----------Trainee List----------'); res.send({ status: 'ok', @@ -44,7 +45,7 @@ class Controller { } ); }; - update = (req, res) => { + update = (req: Request, res: Response) => { console.log('----------Update Trainee----------'); res.send({ status: 'ok', @@ -56,7 +57,7 @@ class Controller { } }); }; - delete = (req, res) => { + delete = (req: Request, res: Response) => { console.log('----------Delete Trainee----------'); res.send( { diff --git a/src/Controllers/trainee/routes.ts b/src/Controllers/trainee/routes.ts index 6d1e31c..3e10df3 100644 --- a/src/Controllers/trainee/routes.ts +++ b/src/Controllers/trainee/routes.ts @@ -1,6 +1,6 @@ import { Router } from 'express'; import Controller from './Controller'; -const traineeRouter = Router(); +const traineeRouter: Router = Router(); traineeRouter.route('/') .get(Controller.create) .post(Controller.list); diff --git a/src/router.ts b/src/router.ts index d258949..2285973 100644 --- a/src/router.ts +++ b/src/router.ts @@ -1,5 +1,5 @@ import { Router } from 'express'; import { traineeRouter } from './Controllers/trainee'; -const mainRouter = Router(); +const mainRouter: Router = Router(); mainRouter.use('/user', traineeRouter); export default mainRouter; From 12f1bac82baf82352b9a417997fe67b66ac8daae Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Mon, 3 Feb 2020 18:34:32 +0530 Subject: [PATCH 48/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Add=20Generic=20Ro?= =?UTF-8?q?utes=20Validations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 39524 --- src/Controllers/trainee/Controller.ts | 4 +- src/Controllers/trainee/index.ts | 3 +- src/Controllers/trainee/routes.ts | 10 ++-- src/Controllers/trainee/validation.ts | 81 +++++++++++++++++++++++++++ src/Server.ts | 2 +- src/libs/routes/errorHandler.ts | 4 +- src/libs/routes/index.ts | 3 +- src/libs/routes/notFoundRoute.ts | 2 +- src/libs/routes/validationHandler.ts | 27 +++++++++ 9 files changed, 124 insertions(+), 12 deletions(-) create mode 100644 src/Controllers/trainee/validation.ts create mode 100644 src/libs/routes/validationHandler.ts diff --git a/src/Controllers/trainee/Controller.ts b/src/Controllers/trainee/Controller.ts index 1fecdeb..5c17275 100644 --- a/src/Controllers/trainee/Controller.ts +++ b/src/Controllers/trainee/Controller.ts @@ -46,8 +46,8 @@ class Controller { ); }; update = (req: Request, res: Response) => { - console.log('----------Update Trainee----------'); - res.send({ + console.log('----------Update Trainee----------', req.params.id); + res.send({ status: 'ok', message: 'Trainee Data successfully Updated', data: { diff --git a/src/Controllers/trainee/index.ts b/src/Controllers/trainee/index.ts index 2905a31..0645919 100644 --- a/src/Controllers/trainee/index.ts +++ b/src/Controllers/trainee/index.ts @@ -1,2 +1,3 @@ export { default as traineeRouter } from './routes'; -export { default as TraineeControllerInstance } from './Controller'; \ No newline at end of file +export { default as TraineeControllerInstance } from './Controller'; +export { default as validation } from './validation' ; \ No newline at end of file diff --git a/src/Controllers/trainee/routes.ts b/src/Controllers/trainee/routes.ts index 3e10df3..5cb7a0f 100644 --- a/src/Controllers/trainee/routes.ts +++ b/src/Controllers/trainee/routes.ts @@ -1,10 +1,12 @@ import { Router } from 'express'; import Controller from './Controller'; +import { validationHandler } from '../../libs/routes' ; +import { default as validation } from './validation' ; const traineeRouter: Router = Router(); traineeRouter.route('/') - .get(Controller.create) - .post(Controller.list); + .get(validationHandler(validation.get), Controller.create) + .post(validationHandler(validation.create), Controller.list); traineeRouter.route('/:id') - .delete(Controller.delete) - .put(Controller.update); + .delete(validationHandler(validation.delete), Controller.delete) + .put(validationHandler(validation.update), Controller.update); export default traineeRouter; \ No newline at end of file diff --git a/src/Controllers/trainee/validation.ts b/src/Controllers/trainee/validation.ts new file mode 100644 index 0000000..b2c8042 --- /dev/null +++ b/src/Controllers/trainee/validation.ts @@ -0,0 +1,81 @@ +const validation = { + create: { + id: { + required: true, + string: true, + regex: /[\w]+/gmi, + in: ['body'], + errorMessage: 'Id is required' + }, + name: + { + required: true, + regex: /^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/gmi, + in: ['body'], + errorMessage: 'Name is required', + } + }, + delete: + { + id: + { + required: true, + errorMessage: 'Id is required', + in: ['params'] + } + }, + get: + { + skip: + { + required: false, + default: 0, + number: true, + regex: /[0-9]+/gmi , + in: ['query'], + errorMessage: 'Skip is invalid', + custom: (req, res, next): void => { + if ( req['body']['limit'] === undefined ) { + req['body']['limit'] = '0'; + } + } + }, + limit: + { + required: false, + default: 10, + number: true, + regex: /[0-9]+/gmi , + in: ['query'], + errorMessage: 'Limit is invalid', + custom: (req, res, next): void => { + if ( req['body']['limit'] === undefined ) { + req['body']['limit'] = '10'; + } + } + } + }, + update: + { + id: + { + required: true, + string: true, + regex: /[\w]+/gmi, + in: ['body'] + }, + dataToUpdate: + { + in: ['body'], + required: true, + isObject: true, + custom: (req, res, next): void => { + if (typeof req['body'] !== 'object' || req['body'].constructor !== Object ) { + next({ error: 'Error Occured', message: 'Not an Object' + }); + } + } + } + } +}; +export default validation ; \ No newline at end of file diff --git a/src/Server.ts b/src/Server.ts index e5884bd..0805abb 100644 --- a/src/Server.ts +++ b/src/Server.ts @@ -8,8 +8,8 @@ export class Server { this.app = express(); } public bootstrap = (): Server => { - this.setupRoutes(); this.initBodyParser(); + this.setupRoutes(); return this; } public run = (): Server => { diff --git a/src/libs/routes/errorHandler.ts b/src/libs/routes/errorHandler.ts index d162736..5620939 100644 --- a/src/libs/routes/errorHandler.ts +++ b/src/libs/routes/errorHandler.ts @@ -1,7 +1,7 @@ import * as express from 'express'; -const errorHandler = (err: express.ErrorRequestHandler, req: express.Request, res: express.Response, next: express.NextFunction): void => { +const errorHandler = (err, req: express.Request, res: express.Response, next: express.NextFunction): void => { res.send({ - error: 'Not Found', message: 'error', status: 500, timestamp: new Date() + error: err.error, message: err.message, status: 500, timestamp: new Date() }); res.end('ok'); }; diff --git a/src/libs/routes/index.ts b/src/libs/routes/index.ts index 04bbfc3..45dcdae 100644 --- a/src/libs/routes/index.ts +++ b/src/libs/routes/index.ts @@ -1,2 +1,3 @@ export { default as errorHandler } from './errorHandler'; -export { default as notFoundRoute }from './notFoundRoute'; \ No newline at end of file +export { default as notFoundRoute }from './notFoundRoute'; +export { default as validationHandler } from './validationHandler' ; \ No newline at end of file diff --git a/src/libs/routes/notFoundRoute.ts b/src/libs/routes/notFoundRoute.ts index 89d4547..fa2adf4 100644 --- a/src/libs/routes/notFoundRoute.ts +++ b/src/libs/routes/notFoundRoute.ts @@ -1,6 +1,6 @@ import * as express from 'express'; const notFoundRoute = (req: express.Request, res: express.Response, next): express.ErrorRequestHandler => { - const err = new Error('Not Found'); + const err = {error: 'Not Found' , message: 'error'}; return next(err); }; export default notFoundRoute; \ No newline at end of file diff --git a/src/libs/routes/validationHandler.ts b/src/libs/routes/validationHandler.ts new file mode 100644 index 0000000..3f5c185 --- /dev/null +++ b/src/libs/routes/validationHandler.ts @@ -0,0 +1,27 @@ +export default (config) => { + return (req, res, next ) => { + console.log('---------Validation Handler---------'); + console.log('The config is ', config); + console.log(req.body); + Object.keys(config).forEach(key => { + console.log(`----${ key }----`); + const { in: any } = config[key]; + const keyValue = req[ in ][key]; + if ( config[key].required === true ) { + if ( keyValue === undefined ) { + next({ error: 'Error Occured', message: `${ config[key].errorMessage }` }); + } + } + if (config[key].regex !== undefined) { + const { regex } = config[key]; + if (!keyValue.match(regex)) { + console.log(`${ key }`); + next({ error: 'Error Occured', message: `${ config[key].errorMessage }` }); + } + } + if (config[key] !== undefined ) + config[key].custom(req, res, next ); + + }); + } ; +}; \ No newline at end of file From 6d773369d745bb8ed901d16d93c2952850ac488e Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Mon, 3 Feb 2020 19:09:07 +0530 Subject: [PATCH 49/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Add=20Generic=20Ro?= =?UTF-8?q?utes=20Validations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 39524 --- src/Controllers/trainee/validation.ts | 19 +++++++++---------- src/libs/routes/validationHandler.ts | 11 ++++++----- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/Controllers/trainee/validation.ts b/src/Controllers/trainee/validation.ts index b2c8042..de86f41 100644 --- a/src/Controllers/trainee/validation.ts +++ b/src/Controllers/trainee/validation.ts @@ -34,9 +34,9 @@ const validation = { regex: /[0-9]+/gmi , in: ['query'], errorMessage: 'Skip is invalid', - custom: (req, res, next): void => { - if ( req['body']['limit'] === undefined ) { - req['body']['limit'] = '0'; + custom: (reqMethod, req, res, next): void => { + if ( req[reqMethod]['limit'] === undefined ) { + req[reqMethod]['limit'] = '0'; } } }, @@ -48,9 +48,9 @@ const validation = { regex: /[0-9]+/gmi , in: ['query'], errorMessage: 'Limit is invalid', - custom: (req, res, next): void => { - if ( req['body']['limit'] === undefined ) { - req['body']['limit'] = '10'; + custom: (reqMethod, req, res, next): void => { + if ( req[reqMethod]['limit'] === undefined ) { + req[reqMethod]['limit'] = '10'; } } } @@ -69,10 +69,9 @@ const validation = { in: ['body'], required: true, isObject: true, - custom: (req, res, next): void => { - if (typeof req['body'] !== 'object' || req['body'].constructor !== Object ) { - next({ error: 'Error Occured', message: 'Not an Object' - }); + custom: (reqMethod, req, res, next): void => { + if (typeof req[reqMethod] !== 'object' || req[reqMethod].constructor !== Object ) { + next({ error: 'Error Occured', message: 'Not an Object'}); } } } diff --git a/src/libs/routes/validationHandler.ts b/src/libs/routes/validationHandler.ts index 3f5c185..29649fa 100644 --- a/src/libs/routes/validationHandler.ts +++ b/src/libs/routes/validationHandler.ts @@ -4,9 +4,10 @@ export default (config) => { console.log('The config is ', config); console.log(req.body); Object.keys(config).forEach(key => { - console.log(`----${ key }----`); - const { in: any } = config[key]; - const keyValue = req[ in ][key]; + console.log(`---------${ key }---------`); + const { in: reqType } = config[key]; + reqType.forEach(reqMethod => { + const keyValue = req[reqMethod][key]; if ( config[key].required === true ) { if ( keyValue === undefined ) { next({ error: 'Error Occured', message: `${ config[key].errorMessage }` }); @@ -20,8 +21,8 @@ export default (config) => { } } if (config[key] !== undefined ) - config[key].custom(req, res, next ); - + config[key].custom(reqMethod, req, res, next ); + }); }); } ; }; \ No newline at end of file From accf5d30e7e800b7eff36cbe0d98b8ca0861c45f Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Mon, 3 Feb 2020 19:19:57 +0530 Subject: [PATCH 50/91] =?UTF-8?q?fix:=20=F0=9F=90=9B=20error?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 39523 --- src/Server.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Server.ts b/src/Server.ts index e5884bd..0805abb 100644 --- a/src/Server.ts +++ b/src/Server.ts @@ -8,8 +8,8 @@ export class Server { this.app = express(); } public bootstrap = (): Server => { - this.setupRoutes(); this.initBodyParser(); + this.setupRoutes(); return this; } public run = (): Server => { From f11e0eb507cac49826122f04ab8aca5b51b4e008 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 4 Feb 2020 13:54:02 +0530 Subject: [PATCH 51/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Generic=20Routes?= =?UTF-8?q?=20Validations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 39524 --- src/Controllers/trainee/Controller.ts | 3 ++- src/Controllers/trainee/validation.ts | 26 ++++++++++++++++---------- src/libs/routes/validationHandler.ts | 24 ++++++++++++++---------- 3 files changed, 32 insertions(+), 21 deletions(-) diff --git a/src/Controllers/trainee/Controller.ts b/src/Controllers/trainee/Controller.ts index 5c17275..f012e1a 100644 --- a/src/Controllers/trainee/Controller.ts +++ b/src/Controllers/trainee/Controller.ts @@ -12,6 +12,7 @@ class Controller { } create = (req: Request, res: Response) => { console.log('----------Create Trainee----------'); + console.log(`req.query.skip = ${req.query.skip},req.query.limit = ${req.query.limit}`); res.send({ status: 'ok', message: 'Trainee added successfully', @@ -46,7 +47,7 @@ class Controller { ); }; update = (req: Request, res: Response) => { - console.log('----------Update Trainee----------', req.params.id); + console.log('----------Update Trainee----------'); res.send({ status: 'ok', message: 'Trainee Data successfully Updated', diff --git a/src/Controllers/trainee/validation.ts b/src/Controllers/trainee/validation.ts index de86f41..d92ede0 100644 --- a/src/Controllers/trainee/validation.ts +++ b/src/Controllers/trainee/validation.ts @@ -3,14 +3,14 @@ const validation = { id: { required: true, string: true, - regex: /[\w]+/gmi, + regex: /[\w]+/, in: ['body'], errorMessage: 'Id is required' }, name: { required: true, - regex: /^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/gmi, + regex: /^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/, in: ['body'], errorMessage: 'Name is required', } @@ -31,12 +31,14 @@ const validation = { required: false, default: 0, number: true, - regex: /[0-9]+/gmi , + regex: /[0-9]+/, in: ['query'], errorMessage: 'Skip is invalid', custom: (reqMethod, req, res, next): void => { - if ( req[reqMethod]['limit'] === undefined ) { - req[reqMethod]['limit'] = '0'; + console.log('inside custom before if'); // + if ( req[reqMethod]['skip'] === undefined ) { + console.log('inside custom'); // + req[reqMethod]['skip'] = '0'; } } }, @@ -45,11 +47,13 @@ const validation = { required: false, default: 10, number: true, - regex: /[0-9]+/gmi , + regex: /[0-9]+/, in: ['query'], errorMessage: 'Limit is invalid', custom: (reqMethod, req, res, next): void => { + console.log('inside custom before if'); // if ( req[reqMethod]['limit'] === undefined ) { + console.log('inside custom'); // req[reqMethod]['limit'] = '10'; } } @@ -61,17 +65,19 @@ const validation = { { required: true, string: true, - regex: /[\w]+/gmi, - in: ['body'] + regex: /[\w]+/, + in: ['body'] , + errorMessage: 'Id is required' }, dataToUpdate: { in: ['body'], required: true, isObject: true, + errorMessage: 'Data is required', custom: (reqMethod, req, res, next): void => { - if (typeof req[reqMethod] !== 'object' || req[reqMethod].constructor !== Object ) { - next({ error: 'Error Occured', message: 'Not an Object'}); + if (typeof req[reqMethod] !== 'object' ) { + return next({ error: 'Error Occured', message: 'Not an Object'}); } } } diff --git a/src/libs/routes/validationHandler.ts b/src/libs/routes/validationHandler.ts index 29649fa..67e4dbe 100644 --- a/src/libs/routes/validationHandler.ts +++ b/src/libs/routes/validationHandler.ts @@ -4,25 +4,29 @@ export default (config) => { console.log('The config is ', config); console.log(req.body); Object.keys(config).forEach(key => { - console.log(`---------${ key }---------`); + console.log(`---------${ key }---------`); // + const { errorMessage } = config[key]; const { in: reqType } = config[key]; reqType.forEach(reqMethod => { const keyValue = req[reqMethod][key]; if ( config[key].required === true ) { - if ( keyValue === undefined ) { - next({ error: 'Error Occured', message: `${ config[key].errorMessage }` }); + if ( keyValue === undefined || keyValue === null ) { + console.log('----inside required key is blank----', errorMessage); + return next({ error: 'Error Occured', message: `${ errorMessage }` }); } - } - if (config[key].regex !== undefined) { - const { regex } = config[key]; - if (!keyValue.match(regex)) { - console.log(`${ key }`); - next({ error: 'Error Occured', message: `${ config[key].errorMessage }` }); + if (config[key].regex !== undefined) { + const { regex } = config[key]; + console.log('----outside regex----', regex, keyValue); + if (!regex.test(keyValue)) { + console.log('----inside regex----', errorMessage, regex, keyValue); + return next({ error: 'Error Occured', message: `${ key } is invalid` }); + } } } - if (config[key] !== undefined ) + if (config[key].custom !== undefined ) config[key].custom(reqMethod, req, res, next ); }); }); + return next(); } ; }; \ No newline at end of file From 809a356d231dc338b2ca4707490316a1494f0b7d Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 4 Feb 2020 15:32:24 +0530 Subject: [PATCH 52/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Authentication=20a?= =?UTF-8?q?nd=20Authorization?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40009 --- .env | 3 ++- package.json | 1 + src/Controllers/trainee/routes.ts | 4 ++-- src/Controllers/trainee/validation.ts | 4 ---- src/config/IConfig.ts | 1 + src/config/configuration.ts | 6 ++---- src/libs/routes/authMiddleWare.ts | 8 ++++++++ src/libs/routes/errorHandler.ts | 5 ++++- src/libs/routes/index.ts | 3 ++- src/libs/routes/validationHandler.ts | 5 +---- 10 files changed, 23 insertions(+), 17 deletions(-) create mode 100644 src/libs/routes/authMiddleWare.ts diff --git a/.env b/.env index 78fb9cd..e83ff40 100644 --- a/.env +++ b/.env @@ -1,2 +1,3 @@ PORT=9000 -NODE_ENV=dev \ No newline at end of file +NODE_ENV=dev +SECRET_KEY=qwertyuiopasdfghjklzxcvbnm123456 \ No newline at end of file diff --git a/package.json b/package.json index b439121..2839218 100644 --- a/package.json +++ b/package.json @@ -34,6 +34,7 @@ "express": "^4.17.1", "git-cz": "^4.2.0", "husky": "^4.2.1", + "jsonwebtoken": "^8.5.1", "nodemon": "^2.0.2", "pre-commit": "^1.2.2", "pre-push": "^0.1.1", diff --git a/src/Controllers/trainee/routes.ts b/src/Controllers/trainee/routes.ts index 5cb7a0f..3e198b6 100644 --- a/src/Controllers/trainee/routes.ts +++ b/src/Controllers/trainee/routes.ts @@ -1,10 +1,10 @@ import { Router } from 'express'; import Controller from './Controller'; -import { validationHandler } from '../../libs/routes' ; +import { validationHandler, authMiddleWare } from '../../libs/routes' ; import { default as validation } from './validation' ; const traineeRouter: Router = Router(); traineeRouter.route('/') - .get(validationHandler(validation.get), Controller.create) + .get(authMiddleWare('getUser', 'read'), validationHandler(validation.get), Controller.create) .post(validationHandler(validation.create), Controller.list); traineeRouter.route('/:id') .delete(validationHandler(validation.delete), Controller.delete) diff --git a/src/Controllers/trainee/validation.ts b/src/Controllers/trainee/validation.ts index d92ede0..4e52828 100644 --- a/src/Controllers/trainee/validation.ts +++ b/src/Controllers/trainee/validation.ts @@ -35,9 +35,7 @@ const validation = { in: ['query'], errorMessage: 'Skip is invalid', custom: (reqMethod, req, res, next): void => { - console.log('inside custom before if'); // if ( req[reqMethod]['skip'] === undefined ) { - console.log('inside custom'); // req[reqMethod]['skip'] = '0'; } } @@ -51,9 +49,7 @@ const validation = { in: ['query'], errorMessage: 'Limit is invalid', custom: (reqMethod, req, res, next): void => { - console.log('inside custom before if'); // if ( req[reqMethod]['limit'] === undefined ) { - console.log('inside custom'); // req[reqMethod]['limit'] = '10'; } } diff --git a/src/config/IConfig.ts b/src/config/IConfig.ts index 232f521..38ed33e 100644 --- a/src/config/IConfig.ts +++ b/src/config/IConfig.ts @@ -1,4 +1,5 @@ export interface IConfig { Port: string; NODE_ENV: string; + Key: string; } \ No newline at end of file diff --git a/src/config/configuration.ts b/src/config/configuration.ts index c2cea54..f782403 100644 --- a/src/config/configuration.ts +++ b/src/config/configuration.ts @@ -1,12 +1,10 @@ import { IConfig } from './IConfig'; import { config } from 'dotenv'; - config(); - const configuration: IConfig = { Port : process.env.PORT, - NODE_ENV : process.env.NODE_ENV + NODE_ENV : process.env.NODE_ENV, + Key : process.env.SECRET_KEY }; Object.freeze(configuration); - export default configuration; \ No newline at end of file diff --git a/src/libs/routes/authMiddleWare.ts b/src/libs/routes/authMiddleWare.ts new file mode 100644 index 0000000..81a4ae7 --- /dev/null +++ b/src/libs/routes/authMiddleWare.ts @@ -0,0 +1,8 @@ +import * as jwt from 'jsonwebtoken'; +export default (module, permissionType) => (req, res, next) => { + const token = req.body.token; + const decodedUser = jwt.verify(token, key); + if(!decodedUser){ + return next({}); + } +} \ No newline at end of file diff --git a/src/libs/routes/errorHandler.ts b/src/libs/routes/errorHandler.ts index 5620939..16dcb6b 100644 --- a/src/libs/routes/errorHandler.ts +++ b/src/libs/routes/errorHandler.ts @@ -1,7 +1,10 @@ import * as express from 'express'; const errorHandler = (err, req: express.Request, res: express.Response, next: express.NextFunction): void => { res.send({ - error: err.error, message: err.message, status: 500, timestamp: new Date() + error: err.error || 'Error Occurred', + message: err.message || err.error || 'Error Occurred', + status: err.status || 500, + timestamp: new Date() }); res.end('ok'); }; diff --git a/src/libs/routes/index.ts b/src/libs/routes/index.ts index 45dcdae..bb7135c 100644 --- a/src/libs/routes/index.ts +++ b/src/libs/routes/index.ts @@ -1,3 +1,4 @@ export { default as errorHandler } from './errorHandler'; export { default as notFoundRoute }from './notFoundRoute'; -export { default as validationHandler } from './validationHandler' ; \ No newline at end of file +export { default as validationHandler } from './validationHandler' ; +export { default as authMiddleWare } from './authMiddleWare' ; \ No newline at end of file diff --git a/src/libs/routes/validationHandler.ts b/src/libs/routes/validationHandler.ts index 67e4dbe..8836f7c 100644 --- a/src/libs/routes/validationHandler.ts +++ b/src/libs/routes/validationHandler.ts @@ -4,21 +4,18 @@ export default (config) => { console.log('The config is ', config); console.log(req.body); Object.keys(config).forEach(key => { - console.log(`---------${ key }---------`); // + console.log(`---------${ key }---------`); const { errorMessage } = config[key]; const { in: reqType } = config[key]; reqType.forEach(reqMethod => { const keyValue = req[reqMethod][key]; if ( config[key].required === true ) { if ( keyValue === undefined || keyValue === null ) { - console.log('----inside required key is blank----', errorMessage); return next({ error: 'Error Occured', message: `${ errorMessage }` }); } if (config[key].regex !== undefined) { const { regex } = config[key]; - console.log('----outside regex----', regex, keyValue); if (!regex.test(keyValue)) { - console.log('----inside regex----', errorMessage, regex, keyValue); return next({ error: 'Error Occured', message: `${ key } is invalid` }); } } From a773e2d4da1f029b1387cacdad12ec89eb8085b2 Mon Sep 17 00:00:00 2001 From: AryanSinghalGit <60099465+AryanSinghalGit@users.noreply.github.com> Date: Tue, 4 Feb 2020 15:35:14 +0530 Subject: [PATCH 53/91] Update validationHandler.ts --- src/libs/routes/validationHandler.ts | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/libs/routes/validationHandler.ts b/src/libs/routes/validationHandler.ts index 67e4dbe..d000f04 100644 --- a/src/libs/routes/validationHandler.ts +++ b/src/libs/routes/validationHandler.ts @@ -1,24 +1,21 @@ export default (config) => { return (req, res, next ) => { console.log('---------Validation Handler---------'); - console.log('The config is ', config); + console.log(config); console.log(req.body); Object.keys(config).forEach(key => { - console.log(`---------${ key }---------`); // + console.log(`---------${ key }---------`); const { errorMessage } = config[key]; const { in: reqType } = config[key]; reqType.forEach(reqMethod => { const keyValue = req[reqMethod][key]; if ( config[key].required === true ) { if ( keyValue === undefined || keyValue === null ) { - console.log('----inside required key is blank----', errorMessage); return next({ error: 'Error Occured', message: `${ errorMessage }` }); } if (config[key].regex !== undefined) { const { regex } = config[key]; - console.log('----outside regex----', regex, keyValue); if (!regex.test(keyValue)) { - console.log('----inside regex----', errorMessage, regex, keyValue); return next({ error: 'Error Occured', message: `${ key } is invalid` }); } } @@ -29,4 +26,4 @@ export default (config) => { }); return next(); } ; -}; \ No newline at end of file +}; From 641e0b69221ce9de402cf8eaaed6146e3147372c Mon Sep 17 00:00:00 2001 From: AryanSinghalGit <60099465+AryanSinghalGit@users.noreply.github.com> Date: Tue, 4 Feb 2020 15:36:39 +0530 Subject: [PATCH 54/91] Update validation.ts --- src/Controllers/trainee/validation.ts | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/src/Controllers/trainee/validation.ts b/src/Controllers/trainee/validation.ts index d92ede0..abf54c0 100644 --- a/src/Controllers/trainee/validation.ts +++ b/src/Controllers/trainee/validation.ts @@ -35,9 +35,7 @@ const validation = { in: ['query'], errorMessage: 'Skip is invalid', custom: (reqMethod, req, res, next): void => { - console.log('inside custom before if'); // if ( req[reqMethod]['skip'] === undefined ) { - console.log('inside custom'); // req[reqMethod]['skip'] = '0'; } } @@ -51,9 +49,7 @@ const validation = { in: ['query'], errorMessage: 'Limit is invalid', custom: (reqMethod, req, res, next): void => { - console.log('inside custom before if'); // if ( req[reqMethod]['limit'] === undefined ) { - console.log('inside custom'); // req[reqMethod]['limit'] = '10'; } } @@ -83,4 +79,4 @@ const validation = { } } }; -export default validation ; \ No newline at end of file +export default validation ; From 982b1327897d9fead6476119498872f03b83358a Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 4 Feb 2020 15:40:39 +0530 Subject: [PATCH 55/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Generic=20Routes?= =?UTF-8?q?=20Validations?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 39524 --- src/Controllers/trainee/validation.ts | 4 ---- src/libs/routes/validationHandler.ts | 8 +++----- 2 files changed, 3 insertions(+), 9 deletions(-) diff --git a/src/Controllers/trainee/validation.ts b/src/Controllers/trainee/validation.ts index d92ede0..4e52828 100644 --- a/src/Controllers/trainee/validation.ts +++ b/src/Controllers/trainee/validation.ts @@ -35,9 +35,7 @@ const validation = { in: ['query'], errorMessage: 'Skip is invalid', custom: (reqMethod, req, res, next): void => { - console.log('inside custom before if'); // if ( req[reqMethod]['skip'] === undefined ) { - console.log('inside custom'); // req[reqMethod]['skip'] = '0'; } } @@ -51,9 +49,7 @@ const validation = { in: ['query'], errorMessage: 'Limit is invalid', custom: (reqMethod, req, res, next): void => { - console.log('inside custom before if'); // if ( req[reqMethod]['limit'] === undefined ) { - console.log('inside custom'); // req[reqMethod]['limit'] = '10'; } } diff --git a/src/libs/routes/validationHandler.ts b/src/libs/routes/validationHandler.ts index 67e4dbe..4417139 100644 --- a/src/libs/routes/validationHandler.ts +++ b/src/libs/routes/validationHandler.ts @@ -1,24 +1,22 @@ +import { Request, Response, NextFunction } from 'express'; export default (config) => { - return (req, res, next ) => { + return (req: Request, res: Response, next: NextFunction) => { console.log('---------Validation Handler---------'); console.log('The config is ', config); console.log(req.body); Object.keys(config).forEach(key => { - console.log(`---------${ key }---------`); // + console.log(`---------${ key }---------`); const { errorMessage } = config[key]; const { in: reqType } = config[key]; reqType.forEach(reqMethod => { const keyValue = req[reqMethod][key]; if ( config[key].required === true ) { if ( keyValue === undefined || keyValue === null ) { - console.log('----inside required key is blank----', errorMessage); return next({ error: 'Error Occured', message: `${ errorMessage }` }); } if (config[key].regex !== undefined) { const { regex } = config[key]; - console.log('----outside regex----', regex, keyValue); if (!regex.test(keyValue)) { - console.log('----inside regex----', errorMessage, regex, keyValue); return next({ error: 'Error Occured', message: `${ key } is invalid` }); } } From 496bbb6e22a720ae88a66417e90a482df32e437a Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 4 Feb 2020 17:34:11 +0530 Subject: [PATCH 56/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Authentication=20a?= =?UTF-8?q?nd=20Authorization?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40009 --- src/Controllers/trainee/routes.ts | 4 ++-- src/libs/constant.ts | 22 +++++++++++++++++++ src/libs/hasPermission.ts | 18 ++++++++++++++++ src/libs/interface.ts | 10 +++++++++ src/libs/routes/authMiddleWare.ts | 36 ++++++++++++++++++++++++++----- 5 files changed, 83 insertions(+), 7 deletions(-) create mode 100644 src/libs/constant.ts create mode 100644 src/libs/hasPermission.ts create mode 100644 src/libs/interface.ts diff --git a/src/Controllers/trainee/routes.ts b/src/Controllers/trainee/routes.ts index 3e198b6..06995ad 100644 --- a/src/Controllers/trainee/routes.ts +++ b/src/Controllers/trainee/routes.ts @@ -4,8 +4,8 @@ import { validationHandler, authMiddleWare } from '../../libs/routes' ; import { default as validation } from './validation' ; const traineeRouter: Router = Router(); traineeRouter.route('/') - .get(authMiddleWare('getUser', 'read'), validationHandler(validation.get), Controller.create) - .post(validationHandler(validation.create), Controller.list); + .get(validationHandler(validation.get), Controller.create) + .post(authMiddleWare('traineeModule', 'read'), validationHandler(validation.create), Controller.list); traineeRouter.route('/:id') .delete(validationHandler(validation.delete), Controller.delete) .put(validationHandler(validation.update), Controller.update); diff --git a/src/libs/constant.ts b/src/libs/constant.ts new file mode 100644 index 0000000..b23a074 --- /dev/null +++ b/src/libs/constant.ts @@ -0,0 +1,22 @@ +import { Ipermission } from './interface'; +const permissions: Ipermission = { + 'getUsers': { + all: ['head-trainer'], + read: ['trainee', 'trainer'], + write: ['trainer'], + delete: [], + }, + 'traineeModule': { + all: ['head-trainer'], + read: ['trainee', 'trainer'], + write: ['trainer'], + delete: [], + }, + 'myUsers': { + all: ['hod'], + read: ['student', 'teacher'], + write: ['teacher'], + delete: ['admin'], + } +}; +export { permissions }; \ No newline at end of file diff --git a/src/libs/hasPermission.ts b/src/libs/hasPermission.ts new file mode 100644 index 0000000..08d17c5 --- /dev/null +++ b/src/libs/hasPermission.ts @@ -0,0 +1,18 @@ +import { permissions } from './constant'; +export default function hasPermission(moduleName: string, role: string, permissionType: string): boolean { + console.log('hasPermission', moduleName, role, permissionType); + if (permissions[moduleName] === undefined) + return false; + const data = permissions[moduleName]; + let tmp: boolean = false; + if (data[permissionType] === undefined) + return false; + + data[permissionType].forEach(element => { + if (element === role) { + tmp = true; + } + + }); + return tmp; +} \ No newline at end of file diff --git a/src/libs/interface.ts b/src/libs/interface.ts new file mode 100644 index 0000000..137c4d3 --- /dev/null +++ b/src/libs/interface.ts @@ -0,0 +1,10 @@ +interface Iauthority { + all: string[]; + read: string[]; + write: string[]; + delete: string[]; +} +interface Ipermission { + [key: string]: Iauthority; +} +export { Ipermission }; \ No newline at end of file diff --git a/src/libs/routes/authMiddleWare.ts b/src/libs/routes/authMiddleWare.ts index 81a4ae7..83c3068 100644 --- a/src/libs/routes/authMiddleWare.ts +++ b/src/libs/routes/authMiddleWare.ts @@ -1,8 +1,34 @@ import * as jwt from 'jsonwebtoken'; +import { default as config } from '../../config/configuration'; +import hasPermission from '../hasPermission'; export default (module, permissionType) => (req, res, next) => { - const token = req.body.token; - const decodedUser = jwt.verify(token, key); - if(!decodedUser){ - return next({}); + console.log('------------AUTHMIDDLEWARE------------', module, permissionType); + try { + const token = req.body.Authorization; + const { Key } = config; + const decodedUser = jwt.verify(token, Key); + if (!decodedUser) { + return next({ + staus: 403, + error: 'Unauthorized Access', + message: 'Unauthorized Access' + }); + } + const role = decodedUser.role; + if (!hasPermission(module, role, permissionType)) { + return next({ + staus: 403, + error: 'Unauthorized Access', + message: 'Unauthorized Access' + }); + } + next(); } -} \ No newline at end of file + catch (error) { + return next({ + staus: 403, + error: 'Unauthorized Access', + message: error.message + }); + } +}; \ No newline at end of file From b9a3acd71ae32f5869db34a6a07d455ec5904e4a Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 4 Feb 2020 17:42:51 +0530 Subject: [PATCH 57/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Authentication=20a?= =?UTF-8?q?nd=20Authorization?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40009 --- src/Controllers/trainee/validation.ts | 8 ++++---- src/libs/routes/authMiddleWare.ts | 7 ++++--- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/src/Controllers/trainee/validation.ts b/src/Controllers/trainee/validation.ts index 4e52828..0fb4bd4 100644 --- a/src/Controllers/trainee/validation.ts +++ b/src/Controllers/trainee/validation.ts @@ -35,8 +35,8 @@ const validation = { in: ['query'], errorMessage: 'Skip is invalid', custom: (reqMethod, req, res, next): void => { - if ( req[reqMethod]['skip'] === undefined ) { - req[reqMethod]['skip'] = '0'; + if ( req[reqMethod].skip === undefined ) { + req[reqMethod].skip = '0'; } } }, @@ -49,8 +49,8 @@ const validation = { in: ['query'], errorMessage: 'Limit is invalid', custom: (reqMethod, req, res, next): void => { - if ( req[reqMethod]['limit'] === undefined ) { - req[reqMethod]['limit'] = '10'; + if ( req[reqMethod].limit === undefined ) { + req[reqMethod].limit = '10'; } } } diff --git a/src/libs/routes/authMiddleWare.ts b/src/libs/routes/authMiddleWare.ts index 83c3068..42b934d 100644 --- a/src/libs/routes/authMiddleWare.ts +++ b/src/libs/routes/authMiddleWare.ts @@ -1,10 +1,11 @@ import * as jwt from 'jsonwebtoken'; import { default as config } from '../../config/configuration'; import hasPermission from '../hasPermission'; -export default (module, permissionType) => (req, res, next) => { +import { Request, Response, NextFunction } from 'express'; +export default (module, permissionType) => (req: Request, res: Response, next: NextFunction) => { console.log('------------AUTHMIDDLEWARE------------', module, permissionType); try { - const token = req.body.Authorization; + const token: string = req.body.Authorization; const { Key } = config; const decodedUser = jwt.verify(token, Key); if (!decodedUser) { @@ -14,7 +15,7 @@ export default (module, permissionType) => (req, res, next) => { message: 'Unauthorized Access' }); } - const role = decodedUser.role; + const role: string = decodedUser.role; if (!hasPermission(module, role, permissionType)) { return next({ staus: 403, From 185517fb207d1b9cae929c78d25b381d90966b84 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 4 Feb 2020 18:26:25 +0530 Subject: [PATCH 58/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Authentication=20a?= =?UTF-8?q?nd=20Authorization?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40009 --- src/Controllers/trainee/routes.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Controllers/trainee/routes.ts b/src/Controllers/trainee/routes.ts index 06995ad..38b2e55 100644 --- a/src/Controllers/trainee/routes.ts +++ b/src/Controllers/trainee/routes.ts @@ -4,9 +4,9 @@ import { validationHandler, authMiddleWare } from '../../libs/routes' ; import { default as validation } from './validation' ; const traineeRouter: Router = Router(); traineeRouter.route('/') - .get(validationHandler(validation.get), Controller.create) + .get(authMiddleWare('traineeModule', 'read'), validationHandler(validation.get), Controller.create) .post(authMiddleWare('traineeModule', 'read'), validationHandler(validation.create), Controller.list); traineeRouter.route('/:id') - .delete(validationHandler(validation.delete), Controller.delete) - .put(validationHandler(validation.update), Controller.update); + .delete(authMiddleWare('traineeModule', 'read'), validationHandler(validation.delete), Controller.delete) + .put(authMiddleWare('traineeModule', 'read'), validationHandler(validation.update), Controller.update); export default traineeRouter; \ No newline at end of file From 31877bb62d658d7260f4f6c6984926948db061cc Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 4 Feb 2020 18:53:03 +0530 Subject: [PATCH 59/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Add=20Authenticati?= =?UTF-8?q?on=20and=20Authorization?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40009 --- src/libs/routes/authMiddleWare.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/libs/routes/authMiddleWare.ts b/src/libs/routes/authMiddleWare.ts index 42b934d..6d654de 100644 --- a/src/libs/routes/authMiddleWare.ts +++ b/src/libs/routes/authMiddleWare.ts @@ -5,7 +5,8 @@ import { Request, Response, NextFunction } from 'express'; export default (module, permissionType) => (req: Request, res: Response, next: NextFunction) => { console.log('------------AUTHMIDDLEWARE------------', module, permissionType); try { - const token: string = req.body.Authorization; + const token: string = req.headers.authorization; + console.log(token); const { Key } = config; const decodedUser = jwt.verify(token, Key); if (!decodedUser) { From d920c5bd4dff845cf82aea8706fd504b37819082 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Wed, 5 Feb 2020 16:47:50 +0530 Subject: [PATCH 60/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Add=20Mongoose=20a?= =?UTF-8?q?nd=20promises?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40010 --- .env | 3 ++- package.json | 42 +++++++++++++++++++------------------ src/Server.ts | 27 ++++++++++++++++-------- src/config/IConfig.ts | 1 + src/config/configuration.ts | 3 ++- src/libs/Database.ts | 20 ++++++++++++++++++ 6 files changed, 65 insertions(+), 31 deletions(-) create mode 100644 src/libs/Database.ts diff --git a/.env b/.env index e83ff40..6f151cc 100644 --- a/.env +++ b/.env @@ -1,3 +1,4 @@ PORT=9000 NODE_ENV=dev -SECRET_KEY=qwertyuiopasdfghjklzxcvbnm123456 \ No newline at end of file +SECRET_KEY=qwertyuiopasdfghjklzxcvbnm123456 +MONGO_URL=mongodb://localhost:27017/express-training \ No newline at end of file diff --git a/package.json b/package.json index 2839218..a87624d 100644 --- a/package.json +++ b/package.json @@ -20,28 +20,30 @@ "author": "", "license": "ISC", "dependencies": { - "@babel/core": "^7.8.3", - "@babel/node": "^7.8.3", - "@babel/preset-env": "^7.8.3", - "@types/express": "^4.17.2", - "@types/node": "^13.5.1", - "babel": "^6.23.0", + "@babel/core": "7.8.3", + "@babel/node": "7.8.3", + "@babel/preset-env": "7.8.3", + "@types/express": "4.17.2", + "@types/mongoose": "5.7.0", + "@types/node": "13.5.1", + "babel": "6.23.0", "babel-node": "0.0.1-security", - "body-parser": "^1.19.0", - "commitizen": "^4.0.3", - "cz-conventional-changelog": "^3.1.0", - "dotenv": "^8.2.0", - "express": "^4.17.1", - "git-cz": "^4.2.0", - "husky": "^4.2.1", - "jsonwebtoken": "^8.5.1", - "nodemon": "^2.0.2", - "pre-commit": "^1.2.2", - "pre-push": "^0.1.1", - "tslint": "^6.0.0" + "body-parser": "1.19.0", + "commitizen": "4.0.3", + "cz-conventional-changelog": "3.1.0", + "dotenv": "8.2.0", + "express": "4.17.1", + "git-cz": "4.2.0", + "husky": "4.2.1", + "jsonwebtoken": "8.5.1", + "mongoose": "5.8.11", + "nodemon": "2.0.2", + "pre-commit": "1.2.2", + "pre-push": "0.1.1", + "tslint": "6.0.0" }, "devDependencies": { - "tsc-watch": "^4.1.0", - "typescript": "^3.7.5" + "tsc-watch": "4.1.0", + "typescript": "3.7.5" } } diff --git a/src/Server.ts b/src/Server.ts index 0805abb..2946601 100644 --- a/src/Server.ts +++ b/src/Server.ts @@ -2,6 +2,7 @@ import * as express from 'express'; import * as bodyParser from 'body-parser'; import { notFoundRoute , errorHandler } from './libs/routes'; import { default as mainRouter } from './router'; +import Database from './libs/Database'; export class Server { private app: express.Express; constructor(protected config) { @@ -13,15 +14,23 @@ export class Server { return this; } public run = (): Server => { - const { app, config: { Port } }: Server = this; - app.listen(Port, (err) => { - if (err) { - console.log(err); - } - else { - console.log(`Express app Successfully started on port : ${Port} `); - } - }); + const { app, config: { Port, MongoURL} }: Server = this; + Database.open(MongoURL) + .then(() => { + app.listen(Port, (err) => { + if (err) { + console.log(err); + } + else { + console.log(`Express app Successfully started on port : ${Port} `); + Database.disconnect(); + } + }); + }) + .catch((err) => { + console.log(err); + } + ); return this; } public initBodyParser = () => { diff --git a/src/config/IConfig.ts b/src/config/IConfig.ts index 38ed33e..3dff2f4 100644 --- a/src/config/IConfig.ts +++ b/src/config/IConfig.ts @@ -2,4 +2,5 @@ export interface IConfig { Port: string; NODE_ENV: string; Key: string; + MongoURL: string; } \ No newline at end of file diff --git a/src/config/configuration.ts b/src/config/configuration.ts index f782403..68a64fe 100644 --- a/src/config/configuration.ts +++ b/src/config/configuration.ts @@ -4,7 +4,8 @@ config(); const configuration: IConfig = { Port : process.env.PORT, NODE_ENV : process.env.NODE_ENV, - Key : process.env.SECRET_KEY + Key : process.env.SECRET_KEY, + MongoURL: process.env.MONGO_URL, }; Object.freeze(configuration); export default configuration; \ No newline at end of file diff --git a/src/libs/Database.ts b/src/libs/Database.ts new file mode 100644 index 0000000..8705ba6 --- /dev/null +++ b/src/libs/Database.ts @@ -0,0 +1,20 @@ +import * as mongoose from 'mongoose'; +export default class Database { + static open = (mongoURL) => { + const promise = new Promise(( resolve, reject ) => { + mongoose.connect(mongoURL, { useNewUrlParser: true, useUnifiedTopology: true }, (err) => { + if (err) { + reject(err); + } + console.log('Database Connected at :', mongoURL); + resolve(); + }); + }); + return promise; + } + static disconnect = () => { + mongoose.connection.close(); + console.log('Database disconnected'); + } ; + +} \ No newline at end of file From 0d0393e93c8c90d460f4ee03b79461769b6b4faf Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Wed, 5 Feb 2020 19:16:07 +0530 Subject: [PATCH 61/91] =?UTF-8?q?fix:=20=F0=9F=90=9B=20Add=20changes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 39524 --- src/Controllers/trainee/Controller.ts | 2 +- src/Controllers/trainee/routes.ts | 4 ++-- src/Controllers/trainee/validation.ts | 12 ++++++------ src/libs/routes/errorHandler.ts | 24 +++++++++++++++++++++--- src/libs/routes/validationHandler.ts | 26 +++++++++++++++++++++----- 5 files changed, 51 insertions(+), 17 deletions(-) diff --git a/src/Controllers/trainee/Controller.ts b/src/Controllers/trainee/Controller.ts index f012e1a..a5fad40 100644 --- a/src/Controllers/trainee/Controller.ts +++ b/src/Controllers/trainee/Controller.ts @@ -12,7 +12,6 @@ class Controller { } create = (req: Request, res: Response) => { console.log('----------Create Trainee----------'); - console.log(`req.query.skip = ${req.query.skip},req.query.limit = ${req.query.limit}`); res.send({ status: 'ok', message: 'Trainee added successfully', @@ -25,6 +24,7 @@ class Controller { }; list = (req: Request, res: Response) => { console.log('----------Trainee List----------'); + console.log(`req.query.skip = ${req.query.skip},req.query.limit = ${req.query.limit}`); res.send({ status: 'ok', message: 'Trainee List', diff --git a/src/Controllers/trainee/routes.ts b/src/Controllers/trainee/routes.ts index 5cb7a0f..b5e20a0 100644 --- a/src/Controllers/trainee/routes.ts +++ b/src/Controllers/trainee/routes.ts @@ -4,8 +4,8 @@ import { validationHandler } from '../../libs/routes' ; import { default as validation } from './validation' ; const traineeRouter: Router = Router(); traineeRouter.route('/') - .get(validationHandler(validation.get), Controller.create) - .post(validationHandler(validation.create), Controller.list); + .get(validationHandler(validation.get), Controller.list) + .post(validationHandler(validation.create), Controller.create); traineeRouter.route('/:id') .delete(validationHandler(validation.delete), Controller.delete) .put(validationHandler(validation.update), Controller.update); diff --git a/src/Controllers/trainee/validation.ts b/src/Controllers/trainee/validation.ts index abf54c0..c5638da 100644 --- a/src/Controllers/trainee/validation.ts +++ b/src/Controllers/trainee/validation.ts @@ -35,8 +35,8 @@ const validation = { in: ['query'], errorMessage: 'Skip is invalid', custom: (reqMethod, req, res, next): void => { - if ( req[reqMethod]['skip'] === undefined ) { - req[reqMethod]['skip'] = '0'; + if ( req[reqMethod].skip === undefined ) { + req[reqMethod].skip = '0'; } } }, @@ -49,8 +49,8 @@ const validation = { in: ['query'], errorMessage: 'Limit is invalid', custom: (reqMethod, req, res, next): void => { - if ( req[reqMethod]['limit'] === undefined ) { - req[reqMethod]['limit'] = '10'; + if ( req[reqMethod].limit === undefined ) { + req[reqMethod].limit = '10'; } } } @@ -71,9 +71,9 @@ const validation = { required: true, isObject: true, errorMessage: 'Data is required', - custom: (reqMethod, req, res, next): void => { + custom: (reqMethod, req, res, next) => { if (typeof req[reqMethod] !== 'object' ) { - return next({ error: 'Error Occured', message: 'Not an Object'}); + return { error: 'Error Occured', message: 'Not an Object'}; } } } diff --git a/src/libs/routes/errorHandler.ts b/src/libs/routes/errorHandler.ts index 5620939..a787b96 100644 --- a/src/libs/routes/errorHandler.ts +++ b/src/libs/routes/errorHandler.ts @@ -1,8 +1,26 @@ import * as express from 'express'; const errorHandler = (err, req: express.Request, res: express.Response, next: express.NextFunction): void => { - res.send({ - error: err.error, message: err.message, status: 500, timestamp: new Date() - }); + let resp; + if ( Array.isArray(err)) { + resp = []; + err.forEach(element => { + resp.push( + { + error: 'Error Occurred ', + message: element , + status: 500, + timestamp: new Date() + }); + }); + } + else + resp = { + error: err.error || 'Error Occurred ', + message: err.message || err , + status: 500, + timestamp: new Date() + }; + res.send(resp); res.end('ok'); }; export default errorHandler; \ No newline at end of file diff --git a/src/libs/routes/validationHandler.ts b/src/libs/routes/validationHandler.ts index 93d539e..2505d6c 100644 --- a/src/libs/routes/validationHandler.ts +++ b/src/libs/routes/validationHandler.ts @@ -4,6 +4,7 @@ export default (config) => { console.log('---------Validation Handler---------'); console.log(config); console.log(req.body); + const err = []; Object.keys(config).forEach(key => { console.log(`---------${ key }---------`); const { errorMessage } = config[key]; @@ -12,19 +13,34 @@ export default (config) => { const keyValue = req[reqMethod][key]; if ( config[key].required === true ) { if ( keyValue === undefined || keyValue === null ) { - return next({ error: 'Error Occured', message: `${ errorMessage }` }); + err.push(`${ errorMessage }`); } if (config[key].regex !== undefined) { const { regex } = config[key]; if (!regex.test(keyValue)) { - return next({ error: 'Error Occured', message: `${ key } is invalid` }); + err.push(`${ key } is invalid`); + } + } + } + else { + if (config[key].regex !== undefined && keyValue !== undefined ) { + console.log('inside regex'); + const { regex } = config[key]; + if (!regex.test(keyValue)) { + err.push(`${ key } is invalid`); } } } if (config[key].custom !== undefined ) - config[key].custom(reqMethod, req, res, next ); + if (config[key].custom(reqMethod, req, res, next )) { + err.push(config[key].custom(reqMethod, req, res, next )); + } }); }); - return next(); + console.log(err); + if (err.length === 0) + return next(); + else + return next(err); } ; -}; +}; \ No newline at end of file From 0f806fd5537bac882820533dec2c4ae7fec3d1fd Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Wed, 5 Feb 2020 20:38:45 +0530 Subject: [PATCH 62/91] =?UTF-8?q?fix:=20=F0=9F=90=9B=20Add=20changes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/libs/routes/errorHandler.ts | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/libs/routes/errorHandler.ts b/src/libs/routes/errorHandler.ts index a787b96..94cf409 100644 --- a/src/libs/routes/errorHandler.ts +++ b/src/libs/routes/errorHandler.ts @@ -3,15 +3,13 @@ const errorHandler = (err, req: express.Request, res: express.Response, next: ex let resp; if ( Array.isArray(err)) { resp = []; - err.forEach(element => { resp.push( { error: 'Error Occurred ', - message: element , + data: err, status: 500, timestamp: new Date() }); - }); } else resp = { @@ -20,7 +18,7 @@ const errorHandler = (err, req: express.Request, res: express.Response, next: ex status: 500, timestamp: new Date() }; - res.send(resp); + res.status(500).send(resp); res.end('ok'); }; export default errorHandler; \ No newline at end of file From 813b53a80eaf432de0d0b43f23b91ffd8d0a5574 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Thu, 6 Feb 2020 14:29:03 +0530 Subject: [PATCH 63/91] =?UTF-8?q?fix:=20=F0=9F=90=9B=20Add=20changes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 39524 --- src/libs/routes/errorHandler.ts | 20 +++-------- src/libs/routes/validationHandler.ts | 54 ++++++++++++++++++++++++---- src/router.ts | 2 +- 3 files changed, 52 insertions(+), 24 deletions(-) diff --git a/src/libs/routes/errorHandler.ts b/src/libs/routes/errorHandler.ts index 94cf409..5b5a309 100644 --- a/src/libs/routes/errorHandler.ts +++ b/src/libs/routes/errorHandler.ts @@ -1,24 +1,12 @@ import * as express from 'express'; const errorHandler = (err, req: express.Request, res: express.Response, next: express.NextFunction): void => { - let resp; - if ( Array.isArray(err)) { - resp = []; - resp.push( - { - error: 'Error Occurred ', - data: err, - status: 500, - timestamp: new Date() - }); - } - else - resp = { - error: err.error || 'Error Occurred ', + const resp = { message: err.message || err , - status: 500, + status: err.status || 500, + error: err.error || 'Error Occurred ', timestamp: new Date() }; - res.status(500).send(resp); + res.status(err.status).send(resp); res.end('ok'); }; export default errorHandler; \ No newline at end of file diff --git a/src/libs/routes/validationHandler.ts b/src/libs/routes/validationHandler.ts index 2505d6c..f82f271 100644 --- a/src/libs/routes/validationHandler.ts +++ b/src/libs/routes/validationHandler.ts @@ -5,6 +5,8 @@ export default (config) => { console.log(config); console.log(req.body); const err = []; + const params = new Set(); + const values = new Set(); Object.keys(config).forEach(key => { console.log(`---------${ key }---------`); const { errorMessage } = config[key]; @@ -13,12 +15,28 @@ export default (config) => { const keyValue = req[reqMethod][key]; if ( config[key].required === true ) { if ( keyValue === undefined || keyValue === null ) { - err.push(`${ errorMessage }`); + const obj = { + location: `${ reqMethod}`, + msg: `${ errorMessage }`, + param: `${ key }` , + value: `${keyValue}` + }; + obj[reqMethod] = obj.param; + delete obj.param; + err.push(obj); } if (config[key].regex !== undefined) { const { regex } = config[key]; if (!regex.test(keyValue)) { - err.push(`${ key } is invalid`); + const obj = { + location: `${ reqMethod}`, + msg: `${ errorMessage }`, + param: `${ key }` , + value: `${keyValue}` + }; + obj[reqMethod] = obj.param; + delete obj.param; + err.push(obj); } } } @@ -27,20 +45,42 @@ export default (config) => { console.log('inside regex'); const { regex } = config[key]; if (!regex.test(keyValue)) { - err.push(`${ key } is invalid`); + const obj = { + location: `${ reqMethod}`, + msg: `${ errorMessage }`, + param: `${ key }` , + value: `${keyValue}` + }; + obj[reqMethod] = obj.param; + delete obj.param; + err.push(obj); } } } if (config[key].custom !== undefined ) if (config[key].custom(reqMethod, req, res, next )) { - err.push(config[key].custom(reqMethod, req, res, next )); + const obj = { + location: `${ reqMethod}`, + msg: `${ errorMessage }`, + param: `${ key }` , + value: `${keyValue}` + }; + obj[reqMethod] = obj.param; + delete obj.param; + err.push(obj); } }); }); - console.log(err); if (err.length === 0) return next(); - else - return next(err); + else { + const error = { + message: 'Error Occurred', + status: 400 , + error: err, + }; + console.log(error); + return next(error); + } } ; }; \ No newline at end of file diff --git a/src/router.ts b/src/router.ts index 2285973..e4a4ceb 100644 --- a/src/router.ts +++ b/src/router.ts @@ -1,5 +1,5 @@ import { Router } from 'express'; import { traineeRouter } from './Controllers/trainee'; const mainRouter: Router = Router(); -mainRouter.use('/user', traineeRouter); +mainRouter.use('/trainee', traineeRouter); export default mainRouter; From 256847bf3a582a6ef8f4a9df9a16f74cb76a13f6 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Thu, 6 Feb 2020 15:00:17 +0530 Subject: [PATCH 64/91] =?UTF-8?q?fix:=20=F0=9F=90=9B=20Resolve=20conflits?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40010 --- src/Server.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Server.ts b/src/Server.ts index 2946601..08523ec 100644 --- a/src/Server.ts +++ b/src/Server.ts @@ -23,7 +23,6 @@ export class Server { } else { console.log(`Express app Successfully started on port : ${Port} `); - Database.disconnect(); } }); }) From a9d39869735aec6a4c70541b3d5eaafbf6fce8b6 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Thu, 6 Feb 2020 18:57:19 +0530 Subject: [PATCH 65/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Add=20Models=20set?= =?UTF-8?q?up=20with=20initial=20Seed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40011 --- src/Controllers/index.ts | 3 +- src/Controllers/user/Controller.ts | 71 +++++++++++++++++++++ src/Controllers/user/index.ts | 3 + src/Controllers/user/routes.ts | 12 ++++ src/Controllers/user/validation.ts | 82 +++++++++++++++++++++++++ src/libs/Database.ts | 2 + src/libs/seedData.ts | 24 ++++++++ src/repositories/user/IUserModel.ts | 10 +++ src/repositories/user/UserModel.ts | 8 +++ src/repositories/user/UserRepository.ts | 25 ++++++++ src/repositories/user/UserSchema.ts | 16 +++++ src/router.ts | 5 +- 12 files changed, 258 insertions(+), 3 deletions(-) create mode 100644 src/Controllers/user/validation.ts create mode 100644 src/libs/seedData.ts create mode 100644 src/repositories/user/IUserModel.ts create mode 100644 src/repositories/user/UserModel.ts create mode 100644 src/repositories/user/UserRepository.ts create mode 100644 src/repositories/user/UserSchema.ts diff --git a/src/Controllers/index.ts b/src/Controllers/index.ts index 8bcca84..3c96a5b 100644 --- a/src/Controllers/index.ts +++ b/src/Controllers/index.ts @@ -1 +1,2 @@ -export { traineeRouter, TraineeControllerInstance } from './trainee'; \ No newline at end of file +export { traineeRouter, TraineeControllerInstance } from './trainee'; +export { default as userRouter } from './user/routes'; \ No newline at end of file diff --git a/src/Controllers/user/Controller.ts b/src/Controllers/user/Controller.ts index e69de29..a5fad40 100644 --- a/src/Controllers/user/Controller.ts +++ b/src/Controllers/user/Controller.ts @@ -0,0 +1,71 @@ +import { Request, Response } from 'express'; +class Controller { + static instance: Controller; + static getInstance = () => { + if (Controller.instance) { + return Controller.instance; + } + else { + Controller.instance = new Controller(); + return Controller.instance; + } + } + create = (req: Request, res: Response) => { + console.log('----------Create Trainee----------'); + res.send({ + status: 'ok', + message: 'Trainee added successfully', + data: { + id: 241, + name: 'Aman', + address: 'Ghaziabad' + } + }); + }; + list = (req: Request, res: Response) => { + console.log('----------Trainee List----------'); + console.log(`req.query.skip = ${req.query.skip},req.query.limit = ${req.query.limit}`); + res.send({ + status: 'ok', + message: 'Trainee List', + data: [{ + id: 241, + name: 'Aman', + address: 'Ghaziabad' + }, + { + id: 242, + name: 'Aryan', + address: 'Noida' + }, + { + id: 243, + name: 'Neeraj', + address: 'Delhi' + }] + } + ); + }; + update = (req: Request, res: Response) => { + console.log('----------Update Trainee----------'); + res.send({ + status: 'ok', + message: 'Trainee Data successfully Updated', + data: { + id: 241, + name: 'Divyam', + address: 'Gurugram' + } + }); + }; + delete = (req: Request, res: Response) => { + console.log('----------Delete Trainee----------'); + res.send( + { + status: 'ok', + message: 'Trainee Data Successfully Deleted' + } + ); + }; +} +export default Controller.getInstance(); \ No newline at end of file diff --git a/src/Controllers/user/index.ts b/src/Controllers/user/index.ts index e69de29..8f12f04 100644 --- a/src/Controllers/user/index.ts +++ b/src/Controllers/user/index.ts @@ -0,0 +1,3 @@ +export { default as userRouter } from './routes'; +export { default as TraineeControllerInstance } from './Controller'; +export { default as validation } from './validation' ; \ No newline at end of file diff --git a/src/Controllers/user/routes.ts b/src/Controllers/user/routes.ts index e69de29..c3d4e6c 100644 --- a/src/Controllers/user/routes.ts +++ b/src/Controllers/user/routes.ts @@ -0,0 +1,12 @@ +import { Router } from 'express'; +import Controller from './Controller'; +import { validationHandler, authMiddleWare } from '../../libs/routes' ; +import { default as validation } from './validation' ; +const userRouter: Router = Router(); +userRouter.route('/') + .get(authMiddleWare('traineeModule', 'read'), validationHandler(validation.get), Controller.list) + .post(authMiddleWare('traineeModule', 'read'), validationHandler(validation.create), Controller.create); +userRouter.route('/:id') + .delete(authMiddleWare('traineeModule', 'read'), validationHandler(validation.delete), Controller.delete) + .put(authMiddleWare('traineeModule', 'read'), validationHandler(validation.update), Controller.update); +export default userRouter; \ No newline at end of file diff --git a/src/Controllers/user/validation.ts b/src/Controllers/user/validation.ts new file mode 100644 index 0000000..c5638da --- /dev/null +++ b/src/Controllers/user/validation.ts @@ -0,0 +1,82 @@ +const validation = { + create: { + id: { + required: true, + string: true, + regex: /[\w]+/, + in: ['body'], + errorMessage: 'Id is required' + }, + name: + { + required: true, + regex: /^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/, + in: ['body'], + errorMessage: 'Name is required', + } + }, + delete: + { + id: + { + required: true, + errorMessage: 'Id is required', + in: ['params'] + } + }, + get: + { + skip: + { + required: false, + default: 0, + number: true, + regex: /[0-9]+/, + in: ['query'], + errorMessage: 'Skip is invalid', + custom: (reqMethod, req, res, next): void => { + if ( req[reqMethod].skip === undefined ) { + req[reqMethod].skip = '0'; + } + } + }, + limit: + { + required: false, + default: 10, + number: true, + regex: /[0-9]+/, + in: ['query'], + errorMessage: 'Limit is invalid', + custom: (reqMethod, req, res, next): void => { + if ( req[reqMethod].limit === undefined ) { + req[reqMethod].limit = '10'; + } + } + } + }, + update: + { + id: + { + required: true, + string: true, + regex: /[\w]+/, + in: ['body'] , + errorMessage: 'Id is required' + }, + dataToUpdate: + { + in: ['body'], + required: true, + isObject: true, + errorMessage: 'Data is required', + custom: (reqMethod, req, res, next) => { + if (typeof req[reqMethod] !== 'object' ) { + return { error: 'Error Occured', message: 'Not an Object'}; + } + } + } + } +}; +export default validation ; diff --git a/src/libs/Database.ts b/src/libs/Database.ts index 8705ba6..551cad8 100644 --- a/src/libs/Database.ts +++ b/src/libs/Database.ts @@ -1,4 +1,5 @@ import * as mongoose from 'mongoose'; +import seedData from './seedData'; export default class Database { static open = (mongoURL) => { const promise = new Promise(( resolve, reject ) => { @@ -7,6 +8,7 @@ export default class Database { reject(err); } console.log('Database Connected at :', mongoURL); + seedData(); resolve(); }); }); diff --git a/src/libs/seedData.ts b/src/libs/seedData.ts new file mode 100644 index 0000000..a021a9f --- /dev/null +++ b/src/libs/seedData.ts @@ -0,0 +1,24 @@ +import UserRepository from '../repositories/user/UserRepository'; + +const user = { + name: 'Aryan Singhal', + address: 'Ghaziabad', + email: 'aryan.singhal@successive.tech', + dob: '07/25/1998', + mob: 7789839178, + hobbies: ['watching movies', 'reading books'] , +}; +const seedData = () => { + UserRepository.count().then((count) => { + if (count === 0) + UserRepository.create(user).then(() => console.log('Data seeded')); + else { + console.log(`${ count } Data is already present`); + } + }) + .catch((err) => { + console.log(err); + }); + +}; +export default seedData; \ No newline at end of file diff --git a/src/repositories/user/IUserModel.ts b/src/repositories/user/IUserModel.ts new file mode 100644 index 0000000..a204d3f --- /dev/null +++ b/src/repositories/user/IUserModel.ts @@ -0,0 +1,10 @@ +import * as mongoose from 'mongoose'; +export default interface IUserModel extends mongoose.Document { + id: string ; + name: string ; + address: string ; + email: string ; + dob: Date ; + mob: number; + hobbies: string[] ; +} \ No newline at end of file diff --git a/src/repositories/user/UserModel.ts b/src/repositories/user/UserModel.ts new file mode 100644 index 0000000..9e3002d --- /dev/null +++ b/src/repositories/user/UserModel.ts @@ -0,0 +1,8 @@ +import UserSchema from './UserSchema'; +import * as mongoose from 'mongoose'; +import IUserModel from './IUserModel'; + +export const userSchema = new UserSchema({ + collection: 'Users' +}); +export const userModel: mongoose.Model = mongoose.model('User', userSchema, 'Users', true); \ No newline at end of file diff --git a/src/repositories/user/UserRepository.ts b/src/repositories/user/UserRepository.ts new file mode 100644 index 0000000..64b76d2 --- /dev/null +++ b/src/repositories/user/UserRepository.ts @@ -0,0 +1,25 @@ +import * as mongoose from 'mongoose'; +import IUserModel from './IUserModel'; +import { userModel } from './UserModel'; +class UserRepository { + private userModel: mongoose.Model; + constructor() { + this.userModel = userModel; + } + create = (data) => { + return this.userModel.create(data); + } + count = () => { + return this.userModel.countDocuments(); + } + delete = (data) => { + // return this.userModel.create(data); + } + update = (data) => { + // return this.userModel.create(data); + } + list = (data) => { + // return this.userModel.create(data); + } +} +export default new UserRepository(); \ No newline at end of file diff --git a/src/repositories/user/UserSchema.ts b/src/repositories/user/UserSchema.ts new file mode 100644 index 0000000..0719d8e --- /dev/null +++ b/src/repositories/user/UserSchema.ts @@ -0,0 +1,16 @@ +import * as mongoose from 'mongoose'; +class UserSchema extends mongoose.Schema { + constructor(options) { + const userSchema = { + id: String , + name: String , + address: String , + email: String , + dob: Date , + mob: Number, + hobbies: [String], + }; + super(userSchema, options); + } +} +export default UserSchema; \ No newline at end of file diff --git a/src/router.ts b/src/router.ts index e4a4ceb..5d4cf90 100644 --- a/src/router.ts +++ b/src/router.ts @@ -1,5 +1,6 @@ import { Router } from 'express'; -import { traineeRouter } from './Controllers/trainee'; +import { traineeRouter, userRouter } from './Controllers'; const mainRouter: Router = Router(); mainRouter.use('/trainee', traineeRouter); -export default mainRouter; +mainRouter.use('/user', userRouter); +export default mainRouter; \ No newline at end of file From 2adccd70c157657943b285fe180dc9b2e66e219a Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Fri, 7 Feb 2020 16:03:41 +0530 Subject: [PATCH 66/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Add=20Models=20set?= =?UTF-8?q?up=20with=20initial=20Seed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40011 --- src/Controllers/user/Controller.ts | 16 ++++---- src/Controllers/user/routes.ts | 2 +- src/Controllers/user/validation.ts | 55 +++++++++++++++++++++++++--- src/libs/routes/notFoundRoute.ts | 2 +- src/libs/routes/validationHandler.ts | 1 + src/libs/seedData.ts | 8 ++-- src/repositories/user/index.ts | 4 ++ 7 files changed, 68 insertions(+), 20 deletions(-) create mode 100644 src/repositories/user/index.ts diff --git a/src/Controllers/user/Controller.ts b/src/Controllers/user/Controller.ts index a5fad40..dcdf24b 100644 --- a/src/Controllers/user/Controller.ts +++ b/src/Controllers/user/Controller.ts @@ -1,4 +1,5 @@ import { Request, Response } from 'express'; +import { UserRepository } from '../../repositories/user'; class Controller { static instance: Controller; static getInstance = () => { @@ -12,14 +13,13 @@ class Controller { } create = (req: Request, res: Response) => { console.log('----------Create Trainee----------'); - res.send({ - status: 'ok', - message: 'Trainee added successfully', - data: { - id: 241, - name: 'Aman', - address: 'Ghaziabad' - } + const { name, address, email, dob, mob, hobbies } = req.body; + UserRepository.create({ name, address, email, dob, mob, hobbies }).then((userData) => { + res.send({ + status: 'ok', + message: 'Trainee added successfully', + data: userData + }); }); }; list = (req: Request, res: Response) => { diff --git a/src/Controllers/user/routes.ts b/src/Controllers/user/routes.ts index c3d4e6c..dcdcee8 100644 --- a/src/Controllers/user/routes.ts +++ b/src/Controllers/user/routes.ts @@ -5,7 +5,7 @@ import { default as validation } from './validation' ; const userRouter: Router = Router(); userRouter.route('/') .get(authMiddleWare('traineeModule', 'read'), validationHandler(validation.get), Controller.list) - .post(authMiddleWare('traineeModule', 'read'), validationHandler(validation.create), Controller.create); + .post(validationHandler(validation.create), Controller.create); // =============== userRouter.route('/:id') .delete(authMiddleWare('traineeModule', 'read'), validationHandler(validation.delete), Controller.delete) .put(authMiddleWare('traineeModule', 'read'), validationHandler(validation.update), Controller.update); diff --git a/src/Controllers/user/validation.ts b/src/Controllers/user/validation.ts index c5638da..468f0b2 100644 --- a/src/Controllers/user/validation.ts +++ b/src/Controllers/user/validation.ts @@ -1,18 +1,61 @@ const validation = { - create: { - id: { + create: + { + name: + { + required: true, + regex: /^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/, + in: ['body'], + errorMessage: 'Name is required', + }, + address: + { required: true, string: true, regex: /[\w]+/, in: ['body'], - errorMessage: 'Id is required' + errorMessage: 'address is required' }, - name: + email: { required: true, - regex: /^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/, + string: true, + regex: /[a-z]([[-]*\w+[.]*){1,63}@successive[.]tech$/, in: ['body'], - errorMessage: 'Name is required', + errorMessage: 'email is required' + }, + dob: + { + required: true, + date: true, + in: ['body'], + errorMessage: 'date is required' + }, + mob: + { + required: true, + number: true, + regex: /[0-9]+$/, + in: ['body'], + length: 10, + errorMessage: 'mobile no. is required', + custom: (reqMethod, req, res, next) => { + if ( req[reqMethod].length !== '10' ) { + return true; + } + } + }, + hobbies: + { + required: true, + array: true, + in: ['body'], + errorMessage: 'email is required', + custom: (reqMethod, req, res, next) => { + if ( Array.isArray(req[reqMethod]) === false ) { + return true; + } + }, } }, delete: diff --git a/src/libs/routes/notFoundRoute.ts b/src/libs/routes/notFoundRoute.ts index fa2adf4..1255d79 100644 --- a/src/libs/routes/notFoundRoute.ts +++ b/src/libs/routes/notFoundRoute.ts @@ -1,6 +1,6 @@ import * as express from 'express'; const notFoundRoute = (req: express.Request, res: express.Response, next): express.ErrorRequestHandler => { - const err = {error: 'Not Found' , message: 'error'}; + const err = {error: 'Not Found' , message: 'error', status: 404 }; return next(err); }; export default notFoundRoute; \ No newline at end of file diff --git a/src/libs/routes/validationHandler.ts b/src/libs/routes/validationHandler.ts index f82f271..73907a5 100644 --- a/src/libs/routes/validationHandler.ts +++ b/src/libs/routes/validationHandler.ts @@ -74,6 +74,7 @@ export default (config) => { if (err.length === 0) return next(); else { + console.log(err); const error = { message: 'Error Occurred', status: 400 , diff --git a/src/libs/seedData.ts b/src/libs/seedData.ts index a021a9f..8355a36 100644 --- a/src/libs/seedData.ts +++ b/src/libs/seedData.ts @@ -1,19 +1,19 @@ import UserRepository from '../repositories/user/UserRepository'; const user = { - name: 'Aryan Singhal', + name: 'Vinay Chaudhary', address: 'Ghaziabad', - email: 'aryan.singhal@successive.tech', + email: 'vinay.chaudhary@successive.tech', dob: '07/25/1998', mob: 7789839178, - hobbies: ['watching movies', 'reading books'] , + hobbies: ['watching movies', 'hiking'] , }; const seedData = () => { UserRepository.count().then((count) => { if (count === 0) UserRepository.create(user).then(() => console.log('Data seeded')); else { - console.log(`${ count } Data is already present`); + console.log(`Data is already seeded`); } }) .catch((err) => { diff --git a/src/repositories/user/index.ts b/src/repositories/user/index.ts new file mode 100644 index 0000000..17d4982 --- /dev/null +++ b/src/repositories/user/index.ts @@ -0,0 +1,4 @@ +export { default as UserRepository } from './UserRepository'; +export { default as UserSchema } from './UserSchema'; +export { default as UserModel } from './UserModel'; +export { default as IUserModel } from './IUserModel'; \ No newline at end of file From 9d80808d1cf285ef9b14c7cec93c8935a0f652fb Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Fri, 7 Feb 2020 18:44:15 +0530 Subject: [PATCH 67/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Add=20Models=20set?= =?UTF-8?q?up=20with=20initial=20Seed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40011 --- src/Controllers/user/Controller.ts | 61 +++++++++++++------------ src/Controllers/user/routes.ts | 7 +-- src/Controllers/user/validation.ts | 10 ++-- src/libs/routes/validationHandler.ts | 4 +- src/repositories/user/UserRepository.ts | 13 +++--- 5 files changed, 52 insertions(+), 43 deletions(-) diff --git a/src/Controllers/user/Controller.ts b/src/Controllers/user/Controller.ts index dcdf24b..d519212 100644 --- a/src/Controllers/user/Controller.ts +++ b/src/Controllers/user/Controller.ts @@ -1,4 +1,4 @@ -import { Request, Response } from 'express'; +import { Request, Response, response } from 'express'; import { UserRepository } from '../../repositories/user'; class Controller { static instance: Controller; @@ -25,47 +25,50 @@ class Controller { list = (req: Request, res: Response) => { console.log('----------Trainee List----------'); console.log(`req.query.skip = ${req.query.skip},req.query.limit = ${req.query.limit}`); + UserRepository.list().then((dataList) => { + console.log(dataList); res.send({ status: 'ok', message: 'Trainee List', - data: [{ - id: 241, - name: 'Aman', - address: 'Ghaziabad' - }, - { - id: 242, - name: 'Aryan', - address: 'Noida' - }, - { - id: 243, - name: 'Neeraj', - address: 'Delhi' - }] + data: dataList } ); + }); }; update = (req: Request, res: Response) => { console.log('----------Update Trainee----------'); - res.send({ - status: 'ok', - message: 'Trainee Data successfully Updated', - data: { - id: 241, - name: 'Divyam', - address: 'Gurugram' + UserRepository.update(req.body.id, req.body.dataToUpdate).then((value) => { + if (value) { + res.send({ + status: 'ok', + message: 'Trainee Data successfully Updated', + data: req.body.dataToUpdate + }); + } + else { + res.send({ + status: 'ok', + message: 'Data does not exist', + }); } }); }; delete = (req: Request, res: Response) => { console.log('----------Delete Trainee----------'); - res.send( - { - status: 'ok', - message: 'Trainee Data Successfully Deleted' - } - ); + UserRepository.delete(req.params.id).then((value) => { + if (value) + res.send( + { + status: 'ok', + message: 'Trainee Data Successfully Deleted' + }); + else + res.send({ + status: 'ok', + message: 'Data does not exist' + }); + }); + }; } export default Controller.getInstance(); \ No newline at end of file diff --git a/src/Controllers/user/routes.ts b/src/Controllers/user/routes.ts index dcdcee8..c506a4b 100644 --- a/src/Controllers/user/routes.ts +++ b/src/Controllers/user/routes.ts @@ -5,8 +5,9 @@ import { default as validation } from './validation' ; const userRouter: Router = Router(); userRouter.route('/') .get(authMiddleWare('traineeModule', 'read'), validationHandler(validation.get), Controller.list) - .post(validationHandler(validation.create), Controller.create); // =============== + .post(validationHandler(validation.create), Controller.create) + .put(validationHandler(validation.update), Controller.update); + userRouter.route('/:id') - .delete(authMiddleWare('traineeModule', 'read'), validationHandler(validation.delete), Controller.delete) - .put(authMiddleWare('traineeModule', 'read'), validationHandler(validation.update), Controller.update); + .delete(authMiddleWare('traineeModule', 'read'), validationHandler(validation.delete), Controller.delete); export default userRouter; \ No newline at end of file diff --git a/src/Controllers/user/validation.ts b/src/Controllers/user/validation.ts index 468f0b2..b9043df 100644 --- a/src/Controllers/user/validation.ts +++ b/src/Controllers/user/validation.ts @@ -40,9 +40,11 @@ const validation = { length: 10, errorMessage: 'mobile no. is required', custom: (reqMethod, req, res, next) => { - if ( req[reqMethod].length !== '10' ) { + if ( req[reqMethod].mob.length !== 10 ) { + console.log('inside mob custom'); return true; } + return false; } }, hobbies: @@ -50,11 +52,13 @@ const validation = { required: true, array: true, in: ['body'], - errorMessage: 'email is required', + errorMessage: 'hobbies is required', custom: (reqMethod, req, res, next) => { - if ( Array.isArray(req[reqMethod]) === false ) { + if ( Array.isArray(req[reqMethod].hobbies) === false ) { + console.log('inside hobby custom'); return true; } + return false; }, } }, diff --git a/src/libs/routes/validationHandler.ts b/src/libs/routes/validationHandler.ts index 73907a5..8e4370e 100644 --- a/src/libs/routes/validationHandler.ts +++ b/src/libs/routes/validationHandler.ts @@ -30,7 +30,7 @@ export default (config) => { if (!regex.test(keyValue)) { const obj = { location: `${ reqMethod}`, - msg: `${ errorMessage }`, + msg: `${ key } is invalid`, param: `${ key }` , value: `${keyValue}` }; @@ -47,7 +47,7 @@ export default (config) => { if (!regex.test(keyValue)) { const obj = { location: `${ reqMethod}`, - msg: `${ errorMessage }`, + msg: `${ key } is invalid`, param: `${ key }` , value: `${keyValue}` }; diff --git a/src/repositories/user/UserRepository.ts b/src/repositories/user/UserRepository.ts index 64b76d2..fe7ed88 100644 --- a/src/repositories/user/UserRepository.ts +++ b/src/repositories/user/UserRepository.ts @@ -12,14 +12,15 @@ class UserRepository { count = () => { return this.userModel.countDocuments(); } - delete = (data) => { - // return this.userModel.create(data); + delete = (id) => { + console.log(id); + return this.userModel.findOneAndDelete({_id: id}); } - update = (data) => { - // return this.userModel.create(data); + update = (id, updatedData) => { + return this.userModel.findOneAndUpdate({_id: id}, updatedData); } - list = (data) => { - // return this.userModel.create(data); + list = () => { + return this.userModel.find({}).exec(); } } export default new UserRepository(); \ No newline at end of file From ddb9aeda5b664f9b75988e40356a8c86b9216448 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Fri, 7 Feb 2020 18:49:29 +0530 Subject: [PATCH 68/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Models=20setup=20w?= =?UTF-8?q?ith=20initial=20Seed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40011 --- src/Controllers/user/routes.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Controllers/user/routes.ts b/src/Controllers/user/routes.ts index c506a4b..abc695c 100644 --- a/src/Controllers/user/routes.ts +++ b/src/Controllers/user/routes.ts @@ -5,8 +5,8 @@ import { default as validation } from './validation' ; const userRouter: Router = Router(); userRouter.route('/') .get(authMiddleWare('traineeModule', 'read'), validationHandler(validation.get), Controller.list) - .post(validationHandler(validation.create), Controller.create) - .put(validationHandler(validation.update), Controller.update); + .post(authMiddleWare('traineeModule', 'read'), validationHandler(validation.create), Controller.create) + .put(authMiddleWare('traineeModule', 'read'), validationHandler(validation.update), Controller.update); userRouter.route('/:id') .delete(authMiddleWare('traineeModule', 'read'), validationHandler(validation.delete), Controller.delete); From 45a9415da78aa3bc5b26e34d283b2b3c9ba6eec2 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Mon, 10 Feb 2020 13:11:17 +0530 Subject: [PATCH 69/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Add=20Models=20set?= =?UTF-8?q?up=20with=20initial=20Seed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40011 --- src/Controllers/user/Controller.ts | 64 ++++++++++++++--------------- src/Controllers/user/routes.ts | 8 ++-- src/Controllers/user/validation.ts | 8 ++++ src/libs/SystemResponse.ts | 17 ++++++++ src/libs/seedData.ts | 1 + src/repositories/user/IUserModel.ts | 1 + src/repositories/user/UserSchema.ts | 1 + 7 files changed, 62 insertions(+), 38 deletions(-) create mode 100644 src/libs/SystemResponse.ts diff --git a/src/Controllers/user/Controller.ts b/src/Controllers/user/Controller.ts index d519212..08b1278 100644 --- a/src/Controllers/user/Controller.ts +++ b/src/Controllers/user/Controller.ts @@ -1,5 +1,6 @@ import { Request, Response, response } from 'express'; import { UserRepository } from '../../repositories/user'; +import SystemResponse from '../../libs/SystemResponse'; class Controller { static instance: Controller; static getInstance = () => { @@ -13,13 +14,14 @@ class Controller { } create = (req: Request, res: Response) => { console.log('----------Create Trainee----------'); - const { name, address, email, dob, mob, hobbies } = req.body; - UserRepository.create({ name, address, email, dob, mob, hobbies }).then((userData) => { - res.send({ - status: 'ok', - message: 'Trainee added successfully', - data: userData - }); + const { name, address, email, dob, mob, hobbies, role } = req.body; + UserRepository.create({ name, address, email, dob, mob, hobbies, role }).then((userData) => { + const message = 'Trainee added successfully'; + const data = userData; + SystemResponse.success(res, data, message); + }) + .catch((error: any) => { + return SystemResponse.failure(res, error, 'User is not create'); }); }; list = (req: Request, res: Response) => { @@ -27,46 +29,40 @@ class Controller { console.log(`req.query.skip = ${req.query.skip},req.query.limit = ${req.query.limit}`); UserRepository.list().then((dataList) => { console.log(dataList); - res.send({ - status: 'ok', - message: 'Trainee List', - data: dataList + if (dataList !== []) { + const message = 'Trainee List'; + const data = dataList; + SystemResponse.success(res, data, message); } - ); + }) + .catch((error: any) => { + return SystemResponse.failure(res, error, 'User data does not exist'); }); }; update = (req: Request, res: Response) => { console.log('----------Update Trainee----------'); UserRepository.update(req.body.id, req.body.dataToUpdate).then((value) => { if (value) { - res.send({ - status: 'ok', - message: 'Trainee Data successfully Updated', - data: req.body.dataToUpdate - }); - } - else { - res.send({ - status: 'ok', - message: 'Data does not exist', - }); + const message = 'Trainee Data successfully Updated'; + const data = req.body.dataToUpdate; + SystemResponse.success(res, data, message); } + }) + .catch((error: any) => { + return SystemResponse.failure(res, error, 'User data is not Updated'); }); }; delete = (req: Request, res: Response) => { console.log('----------Delete Trainee----------'); UserRepository.delete(req.params.id).then((value) => { - if (value) - res.send( - { - status: 'ok', - message: 'Trainee Data Successfully Deleted' - }); - else - res.send({ - status: 'ok', - message: 'Data does not exist' - }); + if (value) { + const message = 'Trainee Data Successfully Deleted'; + const data = req.body.dataToUpdate; + SystemResponse.success(res, req.params.id, message); + } + }) + .catch((error: any) => { + return SystemResponse.failure(res, error, 'User data is not deleted'); }); }; diff --git a/src/Controllers/user/routes.ts b/src/Controllers/user/routes.ts index abc695c..3556d1c 100644 --- a/src/Controllers/user/routes.ts +++ b/src/Controllers/user/routes.ts @@ -4,10 +4,10 @@ import { validationHandler, authMiddleWare } from '../../libs/routes' ; import { default as validation } from './validation' ; const userRouter: Router = Router(); userRouter.route('/') - .get(authMiddleWare('traineeModule', 'read'), validationHandler(validation.get), Controller.list) - .post(authMiddleWare('traineeModule', 'read'), validationHandler(validation.create), Controller.create) - .put(authMiddleWare('traineeModule', 'read'), validationHandler(validation.update), Controller.update); + .get(validationHandler(validation.get), Controller.list) + .post(validationHandler(validation.create), Controller.create) + .put(validationHandler(validation.update), Controller.update); userRouter.route('/:id') - .delete(authMiddleWare('traineeModule', 'read'), validationHandler(validation.delete), Controller.delete); + .delete(validationHandler(validation.delete), Controller.delete); export default userRouter; \ No newline at end of file diff --git a/src/Controllers/user/validation.ts b/src/Controllers/user/validation.ts index b9043df..2cc2dd6 100644 --- a/src/Controllers/user/validation.ts +++ b/src/Controllers/user/validation.ts @@ -16,6 +16,14 @@ const validation = { in: ['body'], errorMessage: 'address is required' }, + role: + { + required: true, + string: true, + regex: /^[a-zA-Z]+/, + in: ['body'], + errorMessage: 'role is required' + }, email: { required: true, diff --git a/src/libs/SystemResponse.ts b/src/libs/SystemResponse.ts new file mode 100644 index 0000000..c3d8048 --- /dev/null +++ b/src/libs/SystemResponse.ts @@ -0,0 +1,17 @@ +class SystemResponse { + static success = (res, data, message = 'Success') => { + return res.status(200).send({ + status: 'ok', + message, + data + }); + } + static failure = (res, err, message = 'Failure') => { + return res.status(200).send({ + status: 'Not ok', + message, + err + }); + } +} +export default SystemResponse; \ No newline at end of file diff --git a/src/libs/seedData.ts b/src/libs/seedData.ts index 8355a36..c2cab5d 100644 --- a/src/libs/seedData.ts +++ b/src/libs/seedData.ts @@ -7,6 +7,7 @@ const user = { dob: '07/25/1998', mob: 7789839178, hobbies: ['watching movies', 'hiking'] , + role: 'Head-Trainer' }; const seedData = () => { UserRepository.count().then((count) => { diff --git a/src/repositories/user/IUserModel.ts b/src/repositories/user/IUserModel.ts index a204d3f..9261fc9 100644 --- a/src/repositories/user/IUserModel.ts +++ b/src/repositories/user/IUserModel.ts @@ -4,6 +4,7 @@ export default interface IUserModel extends mongoose.Document { name: string ; address: string ; email: string ; + role: string ; dob: Date ; mob: number; hobbies: string[] ; diff --git a/src/repositories/user/UserSchema.ts b/src/repositories/user/UserSchema.ts index 0719d8e..b985a91 100644 --- a/src/repositories/user/UserSchema.ts +++ b/src/repositories/user/UserSchema.ts @@ -5,6 +5,7 @@ class UserSchema extends mongoose.Schema { id: String , name: String , address: String , + role: String , email: String , dob: Date , mob: Number, From f896d64059b3e6bac7d077714328aef617aaca62 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Mon, 10 Feb 2020 13:39:01 +0530 Subject: [PATCH 70/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Add=20Models=20set?= =?UTF-8?q?up=20with=20initial=20Seed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40011 --- src/Controllers/user/routes.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/Controllers/user/routes.ts b/src/Controllers/user/routes.ts index 3556d1c..abc695c 100644 --- a/src/Controllers/user/routes.ts +++ b/src/Controllers/user/routes.ts @@ -4,10 +4,10 @@ import { validationHandler, authMiddleWare } from '../../libs/routes' ; import { default as validation } from './validation' ; const userRouter: Router = Router(); userRouter.route('/') - .get(validationHandler(validation.get), Controller.list) - .post(validationHandler(validation.create), Controller.create) - .put(validationHandler(validation.update), Controller.update); + .get(authMiddleWare('traineeModule', 'read'), validationHandler(validation.get), Controller.list) + .post(authMiddleWare('traineeModule', 'read'), validationHandler(validation.create), Controller.create) + .put(authMiddleWare('traineeModule', 'read'), validationHandler(validation.update), Controller.update); userRouter.route('/:id') - .delete(validationHandler(validation.delete), Controller.delete); + .delete(authMiddleWare('traineeModule', 'read'), validationHandler(validation.delete), Controller.delete); export default userRouter; \ No newline at end of file From b1a0ba938df5dbc4dcc353d45d7881b21201ff04 Mon Sep 17 00:00:00 2001 From: AryanSinghalGit <60099465+AryanSinghalGit@users.noreply.github.com> Date: Mon, 10 Feb 2020 15:01:15 +0530 Subject: [PATCH 71/91] Update Controller.ts --- src/Controllers/user/Controller.ts | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/src/Controllers/user/Controller.ts b/src/Controllers/user/Controller.ts index 08b1278..76ac5fc 100644 --- a/src/Controllers/user/Controller.ts +++ b/src/Controllers/user/Controller.ts @@ -29,11 +29,9 @@ class Controller { console.log(`req.query.skip = ${req.query.skip},req.query.limit = ${req.query.limit}`); UserRepository.list().then((dataList) => { console.log(dataList); - if (dataList !== []) { - const message = 'Trainee List'; - const data = dataList; - SystemResponse.success(res, data, message); - } + const message = 'Trainee List'; + const data = dataList; + SystemResponse.success(res, data, message); }) .catch((error: any) => { return SystemResponse.failure(res, error, 'User data does not exist'); @@ -67,4 +65,4 @@ class Controller { }; } -export default Controller.getInstance(); \ No newline at end of file +export default Controller.getInstance(); From 8869b68c1fdf356d4bf013c31560c26ff5be9d79 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Mon, 10 Feb 2020 17:27:45 +0530 Subject: [PATCH 72/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Add=20Profile=20Se?= =?UTF-8?q?tup?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40012 --- src/Controllers/user/Controller.ts | 12 ++++---- src/Controllers/user/index.ts | 2 +- src/Controllers/user/routes.ts | 14 +++++---- src/Controllers/user/validation.ts | 2 +- src/libs/hasPermission.ts | 6 ++-- src/libs/routes/authMiddleWare.ts | 38 ++++++++++++++++++------- src/libs/routes/index.ts | 2 +- src/libs/seedData.ts | 2 +- src/repositories/user/UserModel.ts | 12 ++++++-- src/repositories/user/UserRepository.ts | 3 ++ 10 files changed, 63 insertions(+), 30 deletions(-) diff --git a/src/Controllers/user/Controller.ts b/src/Controllers/user/Controller.ts index 08b1278..aec9450 100644 --- a/src/Controllers/user/Controller.ts +++ b/src/Controllers/user/Controller.ts @@ -29,11 +29,9 @@ class Controller { console.log(`req.query.skip = ${req.query.skip},req.query.limit = ${req.query.limit}`); UserRepository.list().then((dataList) => { console.log(dataList); - if (dataList !== []) { - const message = 'Trainee List'; - const data = dataList; - SystemResponse.success(res, data, message); - } + const message = 'Trainee List'; + const data = dataList; + SystemResponse.success(res, data, message); }) .catch((error: any) => { return SystemResponse.failure(res, error, 'User data does not exist'); @@ -66,5 +64,9 @@ class Controller { }); }; + me = (req, res, next) => { + console.log('--------------me-------------'); + SystemResponse.success(res, req.user, 'User data fetched'); + } } export default Controller.getInstance(); \ No newline at end of file diff --git a/src/Controllers/user/index.ts b/src/Controllers/user/index.ts index 8f12f04..d5e1321 100644 --- a/src/Controllers/user/index.ts +++ b/src/Controllers/user/index.ts @@ -1,3 +1,3 @@ export { default as userRouter } from './routes'; -export { default as TraineeControllerInstance } from './Controller'; +export { default as Controller } from './Controller'; export { default as validation } from './validation' ; \ No newline at end of file diff --git a/src/Controllers/user/routes.ts b/src/Controllers/user/routes.ts index 3556d1c..efb835a 100644 --- a/src/Controllers/user/routes.ts +++ b/src/Controllers/user/routes.ts @@ -1,13 +1,15 @@ import { Router } from 'express'; import Controller from './Controller'; -import { validationHandler, authMiddleWare } from '../../libs/routes' ; +import { validationHandler, authMiddleWare } from '../../libs/routes/index' ; import { default as validation } from './validation' ; const userRouter: Router = Router(); userRouter.route('/') - .get(validationHandler(validation.get), Controller.list) - .post(validationHandler(validation.create), Controller.create) - .put(validationHandler(validation.update), Controller.update); + .get(authMiddleWare('traineeModule', 'read'), validationHandler(validation.get), Controller.list) + .post(authMiddleWare('traineeModule', 'read'), validationHandler(validation.create), Controller.create) + .put(authMiddleWare('traineeModule', 'read'), validationHandler(validation.update), Controller.update); -userRouter.route('/:id') - .delete(validationHandler(validation.delete), Controller.delete); + userRouter.route('/:id') + .delete(authMiddleWare('traineeModule', 'read'), validationHandler(validation.delete), Controller.delete); + userRouter.route('/me') + .get(authMiddleWare('traineeModule', 'read'), validationHandler(validation.get), Controller.me); export default userRouter; \ No newline at end of file diff --git a/src/Controllers/user/validation.ts b/src/Controllers/user/validation.ts index 2cc2dd6..45b55d0 100644 --- a/src/Controllers/user/validation.ts +++ b/src/Controllers/user/validation.ts @@ -134,4 +134,4 @@ const validation = { } } }; -export default validation ; +export default validation ; \ No newline at end of file diff --git a/src/libs/hasPermission.ts b/src/libs/hasPermission.ts index 08d17c5..b52c940 100644 --- a/src/libs/hasPermission.ts +++ b/src/libs/hasPermission.ts @@ -7,12 +7,14 @@ export default function hasPermission(moduleName: string, role: string, permissi let tmp: boolean = false; if (data[permissionType] === undefined) return false; - + data.all.forEach(element => { + if (element === role) + tmp = true; + }); data[permissionType].forEach(element => { if (element === role) { tmp = true; } - }); return tmp; } \ No newline at end of file diff --git a/src/libs/routes/authMiddleWare.ts b/src/libs/routes/authMiddleWare.ts index 07fa8ff..1546993 100644 --- a/src/libs/routes/authMiddleWare.ts +++ b/src/libs/routes/authMiddleWare.ts @@ -2,7 +2,14 @@ import * as jwt from 'jsonwebtoken'; import { default as config } from '../../config/configuration'; import hasPermission from '../hasPermission'; import { Request, Response, NextFunction } from 'express'; -export default (module, permissionType) => (req: Request, res: Response, next: NextFunction) => { +import UserRepository from '../../repositories/user/UserRepository'; +import IUserModel from '../../repositories/user/IUserModel'; +import { Controller } from '../../Controllers/user'; + +interface IRequest extends Request { + user: IUserModel; +} +const authMiddleWare = (module, permissionType) => (req: IRequest, res: Response, next: NextFunction) => { console.log('------------AUTHMIDDLEWARE------------', module, permissionType); try { const token: string = req.headers.authorization; @@ -16,15 +23,22 @@ export default (module, permissionType) => (req: Request, res: Response, next: N message: 'Unauthorized Access' }); } - const role: string = decodedUser.role; - if (!hasPermission(module, role, permissionType)) { - return next({ - status: 403, - error: 'Unauthorized Access', - message: 'Unauthorized Access' - }); - } - next(); + console.log(decodedUser); + console.log(decodedUser._id); + UserRepository.findOne(decodedUser._id).then((userData) => { + console.log(userData); + req.user = userData; + const role: string = userData.role; + if (!hasPermission(module, role, permissionType)) { + console.log(`${ role } does not permission of ${ permissionType }`); + return next({ + status: 403, + error: 'Unauthorized Access', + message: 'Unauthorized Access' + }); + } + next(); + }); } catch (error) { return next({ @@ -33,4 +47,6 @@ export default (module, permissionType) => (req: Request, res: Response, next: N message: error.message }); } -}; \ No newline at end of file +}; + +export { authMiddleWare }; \ No newline at end of file diff --git a/src/libs/routes/index.ts b/src/libs/routes/index.ts index bb7135c..0707367 100644 --- a/src/libs/routes/index.ts +++ b/src/libs/routes/index.ts @@ -1,4 +1,4 @@ export { default as errorHandler } from './errorHandler'; export { default as notFoundRoute }from './notFoundRoute'; export { default as validationHandler } from './validationHandler' ; -export { default as authMiddleWare } from './authMiddleWare' ; \ No newline at end of file +export { authMiddleWare } from './authMiddleWare' ; \ No newline at end of file diff --git a/src/libs/seedData.ts b/src/libs/seedData.ts index c2cab5d..cf178ec 100644 --- a/src/libs/seedData.ts +++ b/src/libs/seedData.ts @@ -7,7 +7,7 @@ const user = { dob: '07/25/1998', mob: 7789839178, hobbies: ['watching movies', 'hiking'] , - role: 'Head-Trainer' + role: 'head-trainer' }; const seedData = () => { UserRepository.count().then((count) => { diff --git a/src/repositories/user/UserModel.ts b/src/repositories/user/UserModel.ts index 9e3002d..0c80780 100644 --- a/src/repositories/user/UserModel.ts +++ b/src/repositories/user/UserModel.ts @@ -1,8 +1,16 @@ import UserSchema from './UserSchema'; import * as mongoose from 'mongoose'; import IUserModel from './IUserModel'; - +const toConvert = { + transfers: (docs: any, ret: any) => { + ret.id = ret._id; + delete ret._id; + delete ret._v; + } +}; export const userSchema = new UserSchema({ - collection: 'Users' + collection: 'Users', + toJSON: toConvert, + toObject: toConvert, }); export const userModel: mongoose.Model = mongoose.model('User', userSchema, 'Users', true); \ No newline at end of file diff --git a/src/repositories/user/UserRepository.ts b/src/repositories/user/UserRepository.ts index fe7ed88..48fc032 100644 --- a/src/repositories/user/UserRepository.ts +++ b/src/repositories/user/UserRepository.ts @@ -22,5 +22,8 @@ class UserRepository { list = () => { return this.userModel.find({}).exec(); } + findOne = (id) => { + return this.userModel.findOne({_id: id}).exec(); + } } export default new UserRepository(); \ No newline at end of file From 719bd50fb921b23cc1776718c8d143af9a797d7b Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Wed, 12 Feb 2020 18:28:22 +0530 Subject: [PATCH 73/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20add=20Setup=20all?= =?UTF-8?q?=20the=20Entities?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40013 --- src/Controllers/user/Controller.ts | 3 +- src/libs/routes/authMiddleWare.ts | 13 ++++++-- src/libs/seedData.ts | 14 +++++---- src/repositories/user/IUserModel.ts | 4 +-- src/repositories/user/UserRepository.ts | 22 ++++---------- src/repositories/user/UserSchema.ts | 3 +- .../versionable/IVersionableDocument.ts | 9 ++++++ .../versionable/VersionableRepository.ts | 30 +++++++++++++++++++ .../versionable/VersionableSchema.ts | 14 +++++++++ src/repositories/versionable/index.ts | 3 ++ 10 files changed, 86 insertions(+), 29 deletions(-) create mode 100644 src/repositories/versionable/IVersionableDocument.ts create mode 100644 src/repositories/versionable/VersionableRepository.ts create mode 100644 src/repositories/versionable/VersionableSchema.ts create mode 100644 src/repositories/versionable/index.ts diff --git a/src/Controllers/user/Controller.ts b/src/Controllers/user/Controller.ts index b60127c..502960d 100644 --- a/src/Controllers/user/Controller.ts +++ b/src/Controllers/user/Controller.ts @@ -39,7 +39,8 @@ class Controller { }; update = (req: Request, res: Response) => { console.log('----------Update Trainee----------'); - UserRepository.update(req.body.id, req.body.dataToUpdate).then((value) => { + UserRepository.update(req.body.id, req.body.dataToUpdate) + .then((value) => { if (value) { const message = 'Trainee Data successfully Updated'; const data = req.body.dataToUpdate; diff --git a/src/libs/routes/authMiddleWare.ts b/src/libs/routes/authMiddleWare.ts index 1546993..3684306 100644 --- a/src/libs/routes/authMiddleWare.ts +++ b/src/libs/routes/authMiddleWare.ts @@ -4,8 +4,6 @@ import hasPermission from '../hasPermission'; import { Request, Response, NextFunction } from 'express'; import UserRepository from '../../repositories/user/UserRepository'; import IUserModel from '../../repositories/user/IUserModel'; -import { Controller } from '../../Controllers/user'; - interface IRequest extends Request { user: IUserModel; } @@ -25,7 +23,8 @@ const authMiddleWare = (module, permissionType) => (req: IRequest, res: Response } console.log(decodedUser); console.log(decodedUser._id); - UserRepository.findOne(decodedUser._id).then((userData) => { + UserRepository.findOne(decodedUser._id) + .then((userData) => { console.log(userData); req.user = userData; const role: string = userData.role; @@ -38,6 +37,14 @@ const authMiddleWare = (module, permissionType) => (req: IRequest, res: Response }); } next(); + }) + .catch((err) => { + console.log(err); + return next({ + status: 403, + error: 'Unauthorized Access', + message: 'Unauthorized Access' + }); }); } catch (error) { diff --git a/src/libs/seedData.ts b/src/libs/seedData.ts index cf178ec..fae3e01 100644 --- a/src/libs/seedData.ts +++ b/src/libs/seedData.ts @@ -1,5 +1,4 @@ import UserRepository from '../repositories/user/UserRepository'; - const user = { name: 'Vinay Chaudhary', address: 'Ghaziabad', @@ -7,19 +6,22 @@ const user = { dob: '07/25/1998', mob: 7789839178, hobbies: ['watching movies', 'hiking'] , - role: 'head-trainer' + role: 'head-trainer', + createdAt: Date.now(), + createdBy: 'seed data', }; const seedData = () => { - UserRepository.count().then((count) => { + UserRepository.count() + .then((count) => { if (count === 0) - UserRepository.create(user).then(() => console.log('Data seeded')); + return UserRepository.create(user); else { - console.log(`Data is already seeded`); + throw new Error(`Data is already seeded`); } }) + .then(() => console.log('Data seeded')) .catch((err) => { console.log(err); }); - }; export default seedData; \ No newline at end of file diff --git a/src/repositories/user/IUserModel.ts b/src/repositories/user/IUserModel.ts index 9261fc9..3291ded 100644 --- a/src/repositories/user/IUserModel.ts +++ b/src/repositories/user/IUserModel.ts @@ -1,5 +1,5 @@ -import * as mongoose from 'mongoose'; -export default interface IUserModel extends mongoose.Document { +import { IVersionableDocument } from '../versionable'; +export default interface IUserModel extends IVersionableDocument { id: string ; name: string ; address: string ; diff --git a/src/repositories/user/UserRepository.ts b/src/repositories/user/UserRepository.ts index 48fc032..c31e512 100644 --- a/src/repositories/user/UserRepository.ts +++ b/src/repositories/user/UserRepository.ts @@ -1,29 +1,19 @@ import * as mongoose from 'mongoose'; import IUserModel from './IUserModel'; import { userModel } from './UserModel'; -class UserRepository { - private userModel: mongoose.Model; +import { VersionableRepository } from '../versionable'; +class UserRepository extends VersionableRepository> { constructor() { - this.userModel = userModel; - } - create = (data) => { - return this.userModel.create(data); + super(userModel); } count = () => { - return this.userModel.countDocuments(); - } - delete = (id) => { - console.log(id); - return this.userModel.findOneAndDelete({_id: id}); - } - update = (id, updatedData) => { - return this.userModel.findOneAndUpdate({_id: id}, updatedData); + return this.versionModel.countDocuments(); } list = () => { - return this.userModel.find({}).exec(); + return this.versionModel.find({}).exec(); } findOne = (id) => { - return this.userModel.findOne({_id: id}).exec(); + return this.versionModel.findOne({_id: id}).exec(); } } export default new UserRepository(); \ No newline at end of file diff --git a/src/repositories/user/UserSchema.ts b/src/repositories/user/UserSchema.ts index b985a91..df1dd03 100644 --- a/src/repositories/user/UserSchema.ts +++ b/src/repositories/user/UserSchema.ts @@ -1,5 +1,6 @@ import * as mongoose from 'mongoose'; -class UserSchema extends mongoose.Schema { +import { VersionableSchema } from '../versionable'; +class UserSchema extends VersionableSchema { constructor(options) { const userSchema = { id: String , diff --git a/src/repositories/versionable/IVersionableDocument.ts b/src/repositories/versionable/IVersionableDocument.ts new file mode 100644 index 0000000..653e4fb --- /dev/null +++ b/src/repositories/versionable/IVersionableDocument.ts @@ -0,0 +1,9 @@ +import * as mongoose from 'mongoose'; +export default interface IVersionableDocument extends mongoose.Document { + originalId: string; + createdAt: Date; + UpdatedAt: Date; + createdBy: string; + UpdatedBy: string; + DeletedBy: string; +} \ No newline at end of file diff --git a/src/repositories/versionable/VersionableRepository.ts b/src/repositories/versionable/VersionableRepository.ts new file mode 100644 index 0000000..d9b8fe1 --- /dev/null +++ b/src/repositories/versionable/VersionableRepository.ts @@ -0,0 +1,30 @@ +import * as mongoose from 'mongoose'; +import { IVersionableDocument, VersionableRepository } from '.'; +export default class VersionRepository< D extends mongoose.Document, M extends mongoose.Model > { + protected versionModel: M ; + constructor(versionModel) { + this.versionModel = versionModel; + } + public static generateObjectId = () => { + return String(mongoose.Types.ObjectId()); + } + create = (data) => { + const id = VersionableRepository.generateObjectId(); + return this.versionModel.create({ + ...data, + _id: id, + originalId: id + }); + } + delete = (id) => { + console.log(id); + return this.versionModel.findOneAndUpdate({_id: id}, { $set: { deletedAt: Date.now()}}); + } + update = (id, updatedData) => { + this.versionModel.update({actualId: id, deletedAt: undefined }, { $set: { deletedAt: Date.now() } } ); + return this.versionModel.create({ + ...updatedData, + originalId: id + }); + } +} \ No newline at end of file diff --git a/src/repositories/versionable/VersionableSchema.ts b/src/repositories/versionable/VersionableSchema.ts new file mode 100644 index 0000000..098ade2 --- /dev/null +++ b/src/repositories/versionable/VersionableSchema.ts @@ -0,0 +1,14 @@ +import * as mongoose from 'mongoose'; +export default class VersionableSchema extends mongoose.Schema { + constructor(userSchema, options) { + const versionSchema = { + originalId: String, + createdAt: {type: Date, default: Date.now()} , + UpdatedAt: Date, + createdBy: String, + UpdatedBy: String, + DeletedBy: String, + }; + super({ ...userSchema, ...versionSchema}, options); + } +} \ No newline at end of file diff --git a/src/repositories/versionable/index.ts b/src/repositories/versionable/index.ts new file mode 100644 index 0000000..2c2a02c --- /dev/null +++ b/src/repositories/versionable/index.ts @@ -0,0 +1,3 @@ +export { default as IVersionableDocument } from './IVersionableDocument'; +export { default as VersionableRepository } from './VersionableRepository'; +export { default as VersionableSchema } from './VersionableSchema'; \ No newline at end of file From 3ad57a5f7752ec1d082c4c24bace40f56ecd7b82 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Thu, 13 Feb 2020 17:01:30 +0530 Subject: [PATCH 74/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20add=20Setup=20all?= =?UTF-8?q?=20the=20Entities?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40013 --- src/Controllers/user/Controller.ts | 15 +++---- src/libs/seedData.ts | 6 +-- src/repositories/user/UserRepository.ts | 13 +++++- .../versionable/IVersionableDocument.ts | 7 ++-- .../versionable/VersionableRepository.ts | 41 ++++++++++++++----- .../versionable/VersionableSchema.ts | 9 ++-- 6 files changed, 62 insertions(+), 29 deletions(-) diff --git a/src/Controllers/user/Controller.ts b/src/Controllers/user/Controller.ts index 502960d..70ceefb 100644 --- a/src/Controllers/user/Controller.ts +++ b/src/Controllers/user/Controller.ts @@ -12,10 +12,10 @@ class Controller { return Controller.instance; } } - create = (req: Request, res: Response) => { + create = (req, res: Response) => { console.log('----------Create Trainee----------'); const { name, address, email, dob, mob, hobbies, role } = req.body; - UserRepository.create({ name, address, email, dob, mob, hobbies, role }).then((userData) => { + UserRepository.create(req.user._id, { name, address, email, dob, mob, hobbies, role }).then((userData) => { const message = 'Trainee added successfully'; const data = userData; SystemResponse.success(res, data, message); @@ -37,9 +37,9 @@ class Controller { return SystemResponse.failure(res, error, 'User data does not exist'); }); }; - update = (req: Request, res: Response) => { + update = (req, res: Response) => { console.log('----------Update Trainee----------'); - UserRepository.update(req.body.id, req.body.dataToUpdate) + UserRepository.update(req, req.body.id, req.body.dataToUpdate) .then((value) => { if (value) { const message = 'Trainee Data successfully Updated'; @@ -51,12 +51,13 @@ class Controller { return SystemResponse.failure(res, error, 'User data is not Updated'); }); }; - delete = (req: Request, res: Response) => { + delete = (req, res: Response) => { console.log('----------Delete Trainee----------'); - UserRepository.delete(req.params.id).then((value) => { + UserRepository.delete(req, req.params.id).then((value) => { + console.log(value); if (value) { const message = 'Trainee Data Successfully Deleted'; - const data = req.body.dataToUpdate; + console.log(message); SystemResponse.success(res, req.params.id, message); } }) diff --git a/src/libs/seedData.ts b/src/libs/seedData.ts index fae3e01..7de831b 100644 --- a/src/libs/seedData.ts +++ b/src/libs/seedData.ts @@ -6,15 +6,13 @@ const user = { dob: '07/25/1998', mob: 7789839178, hobbies: ['watching movies', 'hiking'] , - role: 'head-trainer', - createdAt: Date.now(), - createdBy: 'seed data', + role: 'head-trainer' }; const seedData = () => { UserRepository.count() .then((count) => { if (count === 0) - return UserRepository.create(user); + return UserRepository.create(undefined, user); else { throw new Error(`Data is already seeded`); } diff --git a/src/repositories/user/UserRepository.ts b/src/repositories/user/UserRepository.ts index c31e512..ba5b525 100644 --- a/src/repositories/user/UserRepository.ts +++ b/src/repositories/user/UserRepository.ts @@ -6,11 +6,22 @@ class UserRepository extends VersionableRepository { + return super.create(creatorId, data); + } + delete = (req, id) => { + console.log(id); + return super.delete(req, id); + } + update = (req, id, updatedData) => { + console.log('userRepo'); + return super.update(req, id, updatedData); + } count = () => { return this.versionModel.countDocuments(); } list = () => { - return this.versionModel.find({}).exec(); + return super.list(); } findOne = (id) => { return this.versionModel.findOne({_id: id}).exec(); diff --git a/src/repositories/versionable/IVersionableDocument.ts b/src/repositories/versionable/IVersionableDocument.ts index 653e4fb..8276ebd 100644 --- a/src/repositories/versionable/IVersionableDocument.ts +++ b/src/repositories/versionable/IVersionableDocument.ts @@ -2,8 +2,9 @@ import * as mongoose from 'mongoose'; export default interface IVersionableDocument extends mongoose.Document { originalId: string; createdAt: Date; - UpdatedAt: Date; + updatedAt: Date; + deletedAt: Date; createdBy: string; - UpdatedBy: string; - DeletedBy: string; + updatedBy: string; + deletedBy: string; } \ No newline at end of file diff --git a/src/repositories/versionable/VersionableRepository.ts b/src/repositories/versionable/VersionableRepository.ts index d9b8fe1..4555ec0 100644 --- a/src/repositories/versionable/VersionableRepository.ts +++ b/src/repositories/versionable/VersionableRepository.ts @@ -8,23 +8,44 @@ export default class VersionRepository< D extends mongoose.Document, M extends m public static generateObjectId = () => { return String(mongoose.Types.ObjectId()); } - create = (data) => { + public create(creatorId, data) { const id = VersionableRepository.generateObjectId(); return this.versionModel.create({ ...data, _id: id, - originalId: id + originalId: id, + createdBy: creatorId, + createdAt: Date.now(), }); } - delete = (id) => { - console.log(id); - return this.versionModel.findOneAndUpdate({_id: id}, { $set: { deletedAt: Date.now()}}); + async delete(req, id) { + console.log('>>>>>>>>>', id); + const oldData: any = await this.versionModel.findOne({originalId: id , deletedAt: undefined}).exec(); + console.log('oldData Id', oldData._id); + return this.versionModel.findByIdAndUpdate( oldData._id , + { + deletedAt: Date.now(), + deletedBy: req.user._id + } + ); } - update = (id, updatedData) => { - this.versionModel.update({actualId: id, deletedAt: undefined }, { $set: { deletedAt: Date.now() } } ); - return this.versionModel.create({ + async update(req, id, updatedData) { + const oldData: any = await this.versionModel.findOne({originalId: id , deletedAt: undefined}).exec(); + console.log('oldData Id', oldData._id); + this.versionModel.create({ ...updatedData, - originalId: id + originalId: id, + updatedAt: Date.now(), + updatedBy: req.user._id }); - } + return this.versionModel.findByIdAndUpdate( oldData._id , + { + deletedAt: Date.now(), + deletedBy: req.user._id + } + ); + } + public list() { + return this.versionModel.find({deletedAt: undefined}).exec(); + } } \ No newline at end of file diff --git a/src/repositories/versionable/VersionableSchema.ts b/src/repositories/versionable/VersionableSchema.ts index 098ade2..a0be1db 100644 --- a/src/repositories/versionable/VersionableSchema.ts +++ b/src/repositories/versionable/VersionableSchema.ts @@ -3,11 +3,12 @@ export default class VersionableSchema extends mongoose.Schema { constructor(userSchema, options) { const versionSchema = { originalId: String, - createdAt: {type: Date, default: Date.now()} , - UpdatedAt: Date, + createdAt: Date, + updatedAt: Date, + deletedAt: Date, createdBy: String, - UpdatedBy: String, - DeletedBy: String, + updatedBy: String, + deletedBy: String, }; super({ ...userSchema, ...versionSchema}, options); } From 1108280d49d14337798942acb87ee8b57142815e Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Thu, 13 Feb 2020 17:05:22 +0530 Subject: [PATCH 75/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20add=20Setup=20all?= =?UTF-8?q?=20the=20Entities?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controllers/user/Controller.ts | 4 +--- src/repositories/user/UserRepository.ts | 1 - src/repositories/versionable/VersionableRepository.ts | 3 --- 3 files changed, 1 insertion(+), 7 deletions(-) diff --git a/src/Controllers/user/Controller.ts b/src/Controllers/user/Controller.ts index 70ceefb..836f94d 100644 --- a/src/Controllers/user/Controller.ts +++ b/src/Controllers/user/Controller.ts @@ -54,10 +54,8 @@ class Controller { delete = (req, res: Response) => { console.log('----------Delete Trainee----------'); UserRepository.delete(req, req.params.id).then((value) => { - console.log(value); if (value) { const message = 'Trainee Data Successfully Deleted'; - console.log(message); SystemResponse.success(res, req.params.id, message); } }) @@ -71,4 +69,4 @@ class Controller { SystemResponse.success(res, req.user, 'User data fetched'); } } -export default Controller.getInstance(); +export default Controller.getInstance(); \ No newline at end of file diff --git a/src/repositories/user/UserRepository.ts b/src/repositories/user/UserRepository.ts index ba5b525..09f69fc 100644 --- a/src/repositories/user/UserRepository.ts +++ b/src/repositories/user/UserRepository.ts @@ -14,7 +14,6 @@ class UserRepository extends VersionableRepository { - console.log('userRepo'); return super.update(req, id, updatedData); } count = () => { diff --git a/src/repositories/versionable/VersionableRepository.ts b/src/repositories/versionable/VersionableRepository.ts index 4555ec0..86b5952 100644 --- a/src/repositories/versionable/VersionableRepository.ts +++ b/src/repositories/versionable/VersionableRepository.ts @@ -19,9 +19,7 @@ export default class VersionRepository< D extends mongoose.Document, M extends m }); } async delete(req, id) { - console.log('>>>>>>>>>', id); const oldData: any = await this.versionModel.findOne({originalId: id , deletedAt: undefined}).exec(); - console.log('oldData Id', oldData._id); return this.versionModel.findByIdAndUpdate( oldData._id , { deletedAt: Date.now(), @@ -31,7 +29,6 @@ export default class VersionRepository< D extends mongoose.Document, M extends m } async update(req, id, updatedData) { const oldData: any = await this.versionModel.findOne({originalId: id , deletedAt: undefined}).exec(); - console.log('oldData Id', oldData._id); this.versionModel.create({ ...updatedData, originalId: id, From dee37795c792464387ca8ecca012a7196626ab18 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Thu, 13 Feb 2020 18:54:32 +0530 Subject: [PATCH 76/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20add=20Magic=20of?= =?UTF-8?q?=20Await?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env | 3 +- package.json | 1 + src/Controllers/user/Controller.ts | 32 +++++++++++++++++++-- src/Controllers/user/routes.ts | 4 +-- src/Controllers/user/validation.ts | 11 ++++++++ src/config/IConfig.ts | 1 + src/config/configuration.ts | 1 + src/libs/SystemResponse.ts | 4 +-- src/libs/seedData.ts | 44 ++++++++++++++--------------- src/repositories/user/IUserModel.ts | 1 + src/repositories/user/UserSchema.ts | 2 +- 11 files changed, 74 insertions(+), 30 deletions(-) diff --git a/.env b/.env index 6f151cc..15ba9fd 100644 --- a/.env +++ b/.env @@ -1,4 +1,5 @@ PORT=9000 NODE_ENV=dev SECRET_KEY=qwertyuiopasdfghjklzxcvbnm123456 -MONGO_URL=mongodb://localhost:27017/express-training \ No newline at end of file +MONGO_URL=mongodb://localhost:27017/express-training +PASSWORD=aryan@123 \ No newline at end of file diff --git a/package.json b/package.json index a87624d..008a691 100644 --- a/package.json +++ b/package.json @@ -28,6 +28,7 @@ "@types/node": "13.5.1", "babel": "6.23.0", "babel-node": "0.0.1-security", + "bcrypt": "^3.0.8", "body-parser": "1.19.0", "commitizen": "4.0.3", "cz-conventional-changelog": "3.1.0", diff --git a/src/Controllers/user/Controller.ts b/src/Controllers/user/Controller.ts index 836f94d..2901a02 100644 --- a/src/Controllers/user/Controller.ts +++ b/src/Controllers/user/Controller.ts @@ -1,6 +1,9 @@ -import { Request, Response, response } from 'express'; +import * as bcrypt from 'bcrypt'; +import { Request, Response, response, NextFunction } from 'express'; import { UserRepository } from '../../repositories/user'; import SystemResponse from '../../libs/SystemResponse'; +import * as jwt from 'jsonwebtoken'; +import config from '../../config/configuration'; class Controller { static instance: Controller; static getInstance = () => { @@ -64,9 +67,34 @@ class Controller { }); }; - me = (req, res, next) => { + me = (req, res: Response, next: NextFunction) => { console.log('--------------me-------------'); + delete req.user.password; SystemResponse.success(res, req.user, 'User data fetched'); } + login = async(req , res: Response) => { + console.log('--------------Login-------------'); + try { + const { email, password } = req.body; + console.log(email, password); + const user = await UserRepository.findOne({email}); + console.log('>>>>>>>>>>>>>>>'); + if (!user) { + return SystemResponse.failure(res, 'User data not found', 'User not found', 404); + } + const result = await bcrypt.compare(password, user.password); + console.log(result); + if (!result) { + return SystemResponse.failure(res, 'Password is incorrect', 'Password does not match', 422); + } + console.log('Password matched'); + const token = jwt.sign({ email: user.email , id: user.originalId }, config.Key); + return SystemResponse.success(res, token); + } + catch (err) { + console.log(err); + return SystemResponse.failure(res, err.message); + } + } } export default Controller.getInstance(); \ No newline at end of file diff --git a/src/Controllers/user/routes.ts b/src/Controllers/user/routes.ts index f495cf1..161a4b1 100644 --- a/src/Controllers/user/routes.ts +++ b/src/Controllers/user/routes.ts @@ -11,6 +11,6 @@ userRouter.route('/:id') .delete(authMiddleWare('traineeModule', 'read'), validationHandler(validation.delete), Controller.delete); userRouter.route('/me') .get(authMiddleWare('traineeModule', 'read'), validationHandler(validation.get), Controller.me); -userRouter.route('/:id') - .delete(authMiddleWare('traineeModule', 'read'), validationHandler(validation.delete), Controller.delete); +userRouter.route('/login') + .post(validationHandler(validation.login), Controller.login); export default userRouter; \ No newline at end of file diff --git a/src/Controllers/user/validation.ts b/src/Controllers/user/validation.ts index 45b55d0..927ac5e 100644 --- a/src/Controllers/user/validation.ts +++ b/src/Controllers/user/validation.ts @@ -132,6 +132,17 @@ const validation = { } } } + }, + login: + { + email: + { + required: true, + string: true, + regex: /[a-z]([[-]*\w+[.]*){1,63}@successive[.]tech$/, + in: ['body'], + errorMessage: 'email is required' + }, } }; export default validation ; \ No newline at end of file diff --git a/src/config/IConfig.ts b/src/config/IConfig.ts index 3dff2f4..15d3bc0 100644 --- a/src/config/IConfig.ts +++ b/src/config/IConfig.ts @@ -3,4 +3,5 @@ export interface IConfig { NODE_ENV: string; Key: string; MongoURL: string; + Password: string; } \ No newline at end of file diff --git a/src/config/configuration.ts b/src/config/configuration.ts index 68a64fe..95f817c 100644 --- a/src/config/configuration.ts +++ b/src/config/configuration.ts @@ -6,6 +6,7 @@ const configuration: IConfig = { NODE_ENV : process.env.NODE_ENV, Key : process.env.SECRET_KEY, MongoURL: process.env.MONGO_URL, + Password: process.env.PASSWORD, }; Object.freeze(configuration); export default configuration; \ No newline at end of file diff --git a/src/libs/SystemResponse.ts b/src/libs/SystemResponse.ts index c3d8048..ede6456 100644 --- a/src/libs/SystemResponse.ts +++ b/src/libs/SystemResponse.ts @@ -6,8 +6,8 @@ class SystemResponse { data }); } - static failure = (res, err, message = 'Failure') => { - return res.status(200).send({ + static failure = (res, err, message = 'Failure', status = 400) => { + return res.status(status).send({ status: 'Not ok', message, err diff --git a/src/libs/seedData.ts b/src/libs/seedData.ts index 7de831b..3fc9071 100644 --- a/src/libs/seedData.ts +++ b/src/libs/seedData.ts @@ -1,25 +1,25 @@ +import * as bcrypt from 'bcrypt'; import UserRepository from '../repositories/user/UserRepository'; -const user = { - name: 'Vinay Chaudhary', - address: 'Ghaziabad', - email: 'vinay.chaudhary@successive.tech', - dob: '07/25/1998', - mob: 7789839178, - hobbies: ['watching movies', 'hiking'] , - role: 'head-trainer' -}; -const seedData = () => { - UserRepository.count() - .then((count) => { - if (count === 0) - return UserRepository.create(undefined, user); - else { - throw new Error(`Data is already seeded`); - } - }) - .then(() => console.log('Data seeded')) - .catch((err) => { - console.log(err); - }); +import config from '../config/configuration'; +const seedData = async () => { + const user = { + name: 'Vinay Chaudhary', + address: 'Ghaziabad', + email: 'vinay.chaudhary@successive.tech', + dob: '07/25/1998', + mob: 7789839178, + hobbies: ['watching movies', 'hiking'] , + role: 'head-trainer' + }; + const count = await UserRepository.count(); + if (count === 0) { + const { Password } = config; + const hash = await bcrypt.hash(Password, 10); + UserRepository.create(undefined, { ...user, password: hash }); + console.log('Data seeded'); + } + else + console.log(`Data is already seeded`); + }; export default seedData; \ No newline at end of file diff --git a/src/repositories/user/IUserModel.ts b/src/repositories/user/IUserModel.ts index 3291ded..0fdbfcd 100644 --- a/src/repositories/user/IUserModel.ts +++ b/src/repositories/user/IUserModel.ts @@ -5,6 +5,7 @@ export default interface IUserModel extends IVersionableDocument { address: string ; email: string ; role: string ; + password: string; dob: Date ; mob: number; hobbies: string[] ; diff --git a/src/repositories/user/UserSchema.ts b/src/repositories/user/UserSchema.ts index df1dd03..111dfb8 100644 --- a/src/repositories/user/UserSchema.ts +++ b/src/repositories/user/UserSchema.ts @@ -1,4 +1,3 @@ -import * as mongoose from 'mongoose'; import { VersionableSchema } from '../versionable'; class UserSchema extends VersionableSchema { constructor(options) { @@ -8,6 +7,7 @@ class UserSchema extends VersionableSchema { address: String , role: String , email: String , + password: String , dob: Date , mob: Number, hobbies: [String], From 9ff84557b3f47d9cf71ab13cc6a55f3a7bffb477 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Fri, 14 Feb 2020 12:35:11 +0530 Subject: [PATCH 77/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Magic=20of=20Await?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40014 --- src/Controllers/user/Controller.ts | 15 +++++++-------- src/libs/routes/authMiddleWare.ts | 2 -- src/repositories/user/UserRepository.ts | 3 +++ src/repositories/user/index.ts | 2 +- 4 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/Controllers/user/Controller.ts b/src/Controllers/user/Controller.ts index 2901a02..abfd04b 100644 --- a/src/Controllers/user/Controller.ts +++ b/src/Controllers/user/Controller.ts @@ -1,6 +1,6 @@ import * as bcrypt from 'bcrypt'; import { Request, Response, response, NextFunction } from 'express'; -import { UserRepository } from '../../repositories/user'; +import { userRepository } from '../../repositories/user'; import SystemResponse from '../../libs/SystemResponse'; import * as jwt from 'jsonwebtoken'; import config from '../../config/configuration'; @@ -18,7 +18,7 @@ class Controller { create = (req, res: Response) => { console.log('----------Create Trainee----------'); const { name, address, email, dob, mob, hobbies, role } = req.body; - UserRepository.create(req.user._id, { name, address, email, dob, mob, hobbies, role }).then((userData) => { + userRepository.create(req.user._id, { name, address, email, dob, mob, hobbies, role }).then((userData) => { const message = 'Trainee added successfully'; const data = userData; SystemResponse.success(res, data, message); @@ -30,7 +30,7 @@ class Controller { list = (req: Request, res: Response) => { console.log('----------Trainee List----------'); console.log(`req.query.skip = ${req.query.skip},req.query.limit = ${req.query.limit}`); - UserRepository.list().then((dataList) => { + userRepository.list().then((dataList) => { console.log(dataList); const message = 'Trainee List'; const data = dataList; @@ -42,7 +42,7 @@ class Controller { }; update = (req, res: Response) => { console.log('----------Update Trainee----------'); - UserRepository.update(req, req.body.id, req.body.dataToUpdate) + userRepository.update(req, req.body.id, req.body.dataToUpdate) .then((value) => { if (value) { const message = 'Trainee Data successfully Updated'; @@ -56,7 +56,7 @@ class Controller { }; delete = (req, res: Response) => { console.log('----------Delete Trainee----------'); - UserRepository.delete(req, req.params.id).then((value) => { + userRepository.delete(req, req.params.id).then((value) => { if (value) { const message = 'Trainee Data Successfully Deleted'; SystemResponse.success(res, req.params.id, message); @@ -77,8 +77,7 @@ class Controller { try { const { email, password } = req.body; console.log(email, password); - const user = await UserRepository.findOne({email}); - console.log('>>>>>>>>>>>>>>>'); + const user = await userRepository.findByEmail(email); if (!user) { return SystemResponse.failure(res, 'User data not found', 'User not found', 404); } @@ -88,7 +87,7 @@ class Controller { return SystemResponse.failure(res, 'Password is incorrect', 'Password does not match', 422); } console.log('Password matched'); - const token = jwt.sign({ email: user.email , id: user.originalId }, config.Key); + const token = jwt.sign({ email: user.email , _id: user.originalId }, config.Key); return SystemResponse.success(res, token); } catch (err) { diff --git a/src/libs/routes/authMiddleWare.ts b/src/libs/routes/authMiddleWare.ts index 3684306..aa2fc15 100644 --- a/src/libs/routes/authMiddleWare.ts +++ b/src/libs/routes/authMiddleWare.ts @@ -22,7 +22,6 @@ const authMiddleWare = (module, permissionType) => (req: IRequest, res: Response }); } console.log(decodedUser); - console.log(decodedUser._id); UserRepository.findOne(decodedUser._id) .then((userData) => { console.log(userData); @@ -55,5 +54,4 @@ const authMiddleWare = (module, permissionType) => (req: IRequest, res: Response }); } }; - export { authMiddleWare }; \ No newline at end of file diff --git a/src/repositories/user/UserRepository.ts b/src/repositories/user/UserRepository.ts index 09f69fc..430ff43 100644 --- a/src/repositories/user/UserRepository.ts +++ b/src/repositories/user/UserRepository.ts @@ -25,5 +25,8 @@ class UserRepository extends VersionableRepository { return this.versionModel.findOne({_id: id}).exec(); } + findByEmail = (emailId) => { + return this.versionModel.findOne({email: emailId}); + } } export default new UserRepository(); \ No newline at end of file diff --git a/src/repositories/user/index.ts b/src/repositories/user/index.ts index 17d4982..8a54624 100644 --- a/src/repositories/user/index.ts +++ b/src/repositories/user/index.ts @@ -1,4 +1,4 @@ -export { default as UserRepository } from './UserRepository'; +export { default as userRepository } from './UserRepository'; export { default as UserSchema } from './UserSchema'; export { default as UserModel } from './UserModel'; export { default as IUserModel } from './IUserModel'; \ No newline at end of file From 801003b082219681694d6b90b2f36be72fdff018 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Fri, 14 Feb 2020 13:04:20 +0530 Subject: [PATCH 78/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20Magic=20of=20Await?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controllers/user/Controller.ts | 55 ++++++++++++++++-------------- 1 file changed, 29 insertions(+), 26 deletions(-) diff --git a/src/Controllers/user/Controller.ts b/src/Controllers/user/Controller.ts index abfd04b..b891a48 100644 --- a/src/Controllers/user/Controller.ts +++ b/src/Controllers/user/Controller.ts @@ -15,56 +15,59 @@ class Controller { return Controller.instance; } } - create = (req, res: Response) => { + create = async (req, res: Response) => { console.log('----------Create Trainee----------'); const { name, address, email, dob, mob, hobbies, role } = req.body; - userRepository.create(req.user._id, { name, address, email, dob, mob, hobbies, role }).then((userData) => { + try { + const userData = await userRepository.create(req.user._id, { name, address, email, dob, mob, hobbies, role }); const message = 'Trainee added successfully'; const data = userData; SystemResponse.success(res, data, message); - }) - .catch((error: any) => { + } + catch (error) { return SystemResponse.failure(res, error, 'User is not create'); - }); + } }; - list = (req: Request, res: Response) => { + list = async (req: Request, res: Response) => { console.log('----------Trainee List----------'); console.log(`req.query.skip = ${req.query.skip},req.query.limit = ${req.query.limit}`); - userRepository.list().then((dataList) => { - console.log(dataList); - const message = 'Trainee List'; - const data = dataList; - SystemResponse.success(res, data, message); - }) - .catch((error: any) => { - return SystemResponse.failure(res, error, 'User data does not exist'); - }); + try { + const dataList = await userRepository.list(); + console.log(dataList); + const message = 'Trainee List'; + const data = dataList; + SystemResponse.success(res, data, message); + } + catch (error) { + return SystemResponse.failure(res, error, 'User data does not exist'); + } }; - update = (req, res: Response) => { + update = async (req, res: Response) => { console.log('----------Update Trainee----------'); - userRepository.update(req, req.body.id, req.body.dataToUpdate) - .then((value) => { + try { + const value = await userRepository.update(req, req.body.id, req.body.dataToUpdate); if (value) { const message = 'Trainee Data successfully Updated'; const data = req.body.dataToUpdate; SystemResponse.success(res, data, message); } - }) - .catch((error: any) => { + } + catch (error) { return SystemResponse.failure(res, error, 'User data is not Updated'); - }); + } }; - delete = (req, res: Response) => { + delete = async(req, res: Response) => { console.log('----------Delete Trainee----------'); - userRepository.delete(req, req.params.id).then((value) => { + try { + const value = await userRepository.delete(req, req.params.id); if (value) { const message = 'Trainee Data Successfully Deleted'; SystemResponse.success(res, req.params.id, message); } - }) - .catch((error: any) => { + } + catch (error) { return SystemResponse.failure(res, error, 'User data is not deleted'); - }); + } }; me = (req, res: Response, next: NextFunction) => { From 0c21991fb5fe0169d264703655da7fb56cb0bcfd Mon Sep 17 00:00:00 2001 From: AryanSinghalGit <60099465+AryanSinghalGit@users.noreply.github.com> Date: Fri, 14 Feb 2020 15:12:19 +0530 Subject: [PATCH 79/91] Update Controller.ts --- src/Controllers/user/Controller.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Controllers/user/Controller.ts b/src/Controllers/user/Controller.ts index b891a48..cedf171 100644 --- a/src/Controllers/user/Controller.ts +++ b/src/Controllers/user/Controller.ts @@ -90,7 +90,7 @@ class Controller { return SystemResponse.failure(res, 'Password is incorrect', 'Password does not match', 422); } console.log('Password matched'); - const token = jwt.sign({ email: user.email , _id: user.originalId }, config.Key); + const token = jwt.sign({ email: user.email , _id: user.originalId }, config.Key, { expiresIn: 900 }); return SystemResponse.success(res, token); } catch (err) { @@ -99,4 +99,4 @@ class Controller { } } } -export default Controller.getInstance(); \ No newline at end of file +export default Controller.getInstance(); From ab029c8d300c980ade9e3680e6668fb479942bf1 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Fri, 14 Feb 2020 18:26:50 +0530 Subject: [PATCH 80/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20add=20APIs=20Compl?= =?UTF-8?q?etion?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40313 --- .env | 2 +- src/Controllers/index.ts | 2 +- src/Controllers/trainee/Controller.ts | 98 +++++++++-------- src/Controllers/trainee/index.ts | 2 +- src/Controllers/trainee/routes.ts | 10 +- src/Controllers/trainee/validation.ts | 70 ++++++++++-- src/Controllers/user/Controller.ts | 61 +---------- src/Controllers/user/routes.ts | 6 - src/Controllers/user/validation.ts | 103 ------------------ src/repositories/user/UserRepository.ts | 11 +- .../versionable/VersionableRepository.ts | 4 +- .../versionable/VersionableSchema.ts | 2 +- 12 files changed, 137 insertions(+), 234 deletions(-) diff --git a/.env b/.env index 15ba9fd..ef5d356 100644 --- a/.env +++ b/.env @@ -1,4 +1,4 @@ -PORT=9000 +PORT=9002 NODE_ENV=dev SECRET_KEY=qwertyuiopasdfghjklzxcvbnm123456 MONGO_URL=mongodb://localhost:27017/express-training diff --git a/src/Controllers/index.ts b/src/Controllers/index.ts index 3c96a5b..2f2e277 100644 --- a/src/Controllers/index.ts +++ b/src/Controllers/index.ts @@ -1,2 +1,2 @@ -export { traineeRouter, TraineeControllerInstance } from './trainee'; +export { traineeRouter, traineeController } from './trainee'; export { default as userRouter } from './user/routes'; \ No newline at end of file diff --git a/src/Controllers/trainee/Controller.ts b/src/Controllers/trainee/Controller.ts index a5fad40..a65fbfb 100644 --- a/src/Controllers/trainee/Controller.ts +++ b/src/Controllers/trainee/Controller.ts @@ -1,4 +1,6 @@ import { Request, Response } from 'express'; +import { userRepository } from '../../repositories/user'; +import SystemResponse from '../../libs/SystemResponse'; class Controller { static instance: Controller; static getInstance = () => { @@ -10,62 +12,68 @@ class Controller { return Controller.instance; } } - create = (req: Request, res: Response) => { + create = async (req, res: Response) => { console.log('----------Create Trainee----------'); - res.send({ - status: 'ok', - message: 'Trainee added successfully', - data: { - id: 241, - name: 'Aman', - address: 'Ghaziabad' - } - }); + const { name, address, email, dob, mob, hobbies, role } = req.body; + try { + const userData = await userRepository.create(req.user._id, { name, address, email, dob, mob, hobbies, role }); + const message = 'Trainee added successfully'; + const data = userData; + SystemResponse.success(res, data, message); + } + catch (error) { + return SystemResponse.failure(res, error, 'User is not create'); + } }; - list = (req: Request, res: Response) => { + list = async (req: Request, res: Response) => { console.log('----------Trainee List----------'); console.log(`req.query.skip = ${req.query.skip},req.query.limit = ${req.query.limit}`); - res.send({ - status: 'ok', - message: 'Trainee List', - data: [{ - id: 241, - name: 'Aman', - address: 'Ghaziabad' - }, - { - id: 242, - name: 'Aryan', - address: 'Noida' - }, - { - id: 243, - name: 'Neeraj', - address: 'Delhi' - }] + try { + let sortBy; + if (req.query.sortBy === 'email') + sortBy = { email: 1 }; + else if (req.query.sortBy === 'name') + sortBy = { name: 1 }; + else + sortBy = {updatedAt: 1}; + const dataList = await userRepository.list('trainee', req.query.skip, req.query.limit, sortBy); + console.log(dataList); + const count = await userRepository.countTrainee(); + const message = 'Trainee List , No. of trainee: ' + count ; + const data = dataList; + SystemResponse.success(res, data, message); + } + catch (error) { + return SystemResponse.failure(res, error, 'User data does not exist'); } - ); }; - update = (req: Request, res: Response) => { + update = async (req, res: Response) => { console.log('----------Update Trainee----------'); - res.send({ - status: 'ok', - message: 'Trainee Data successfully Updated', - data: { - id: 241, - name: 'Divyam', - address: 'Gurugram' + try { + const value = await userRepository.update(req, req.body.id, req.body.dataToUpdate); + if (value) { + const message = 'Trainee Data successfully Updated'; + const data = req.body.dataToUpdate; + SystemResponse.success(res, data, message); } - }); + } + catch (error) { + return SystemResponse.failure(res, error, 'User data is not Updated'); + } }; - delete = (req: Request, res: Response) => { + delete = async(req, res: Response) => { console.log('----------Delete Trainee----------'); - res.send( - { - status: 'ok', - message: 'Trainee Data Successfully Deleted' + try { + const value = await userRepository.delete(req, req.params.id); + if (value) { + const message = 'Trainee Data Successfully Deleted'; + SystemResponse.success(res, req.params.id, message); } - ); + } + catch (error) { + return SystemResponse.failure(res, error, 'User data is not deleted'); + } + }; } export default Controller.getInstance(); \ No newline at end of file diff --git a/src/Controllers/trainee/index.ts b/src/Controllers/trainee/index.ts index 0645919..b9ddfff 100644 --- a/src/Controllers/trainee/index.ts +++ b/src/Controllers/trainee/index.ts @@ -1,3 +1,3 @@ export { default as traineeRouter } from './routes'; -export { default as TraineeControllerInstance } from './Controller'; +export { default as traineeController } from './Controller'; export { default as validation } from './validation' ; \ No newline at end of file diff --git a/src/Controllers/trainee/routes.ts b/src/Controllers/trainee/routes.ts index cab6470..92eb732 100644 --- a/src/Controllers/trainee/routes.ts +++ b/src/Controllers/trainee/routes.ts @@ -1,12 +1,12 @@ import { Router } from 'express'; -import Controller from './Controller'; +import controller from './Controller'; import { validationHandler, authMiddleWare } from '../../libs/routes' ; import { default as validation } from './validation' ; const traineeRouter: Router = Router(); traineeRouter.route('/') - .get(authMiddleWare('traineeModule', 'read'), validationHandler(validation.get), Controller.list) - .post(authMiddleWare('traineeModule', 'read'), validationHandler(validation.create), Controller.create); + .get(authMiddleWare('traineeModule', 'read'), validationHandler(validation.get), controller.list) + .post(authMiddleWare('traineeModule', 'write'), validationHandler(validation.create), controller.create) + .put(authMiddleWare('traineeModule', 'write'), validationHandler(validation.update), controller.update); traineeRouter.route('/:id') - .delete(authMiddleWare('traineeModule', 'read'), validationHandler(validation.delete), Controller.delete) - .put(authMiddleWare('traineeModule', 'read'), validationHandler(validation.update), Controller.update); + .delete(authMiddleWare('traineeModule', 'delete'), validationHandler(validation.delete), controller.delete); export default traineeRouter; \ No newline at end of file diff --git a/src/Controllers/trainee/validation.ts b/src/Controllers/trainee/validation.ts index c5638da..ebf2d92 100644 --- a/src/Controllers/trainee/validation.ts +++ b/src/Controllers/trainee/validation.ts @@ -1,18 +1,74 @@ const validation = { - create: { - id: { + create: + { + name: + { + required: true, + regex: /^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/, + in: ['body'], + errorMessage: 'Name is required', + }, + address: + { required: true, string: true, regex: /[\w]+/, in: ['body'], - errorMessage: 'Id is required' + errorMessage: 'address is required' }, - name: + role: { required: true, - regex: /^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/, + string: true, + regex: /^[a-zA-Z]+/, in: ['body'], - errorMessage: 'Name is required', + errorMessage: 'role is required' + }, + email: + { + required: true, + string: true, + regex: /[a-z]([[-]*\w+[.]*){1,63}@successive[.]tech$/, + in: ['body'], + errorMessage: 'email is required' + }, + dob: + { + required: true, + date: true, + in: ['body'], + errorMessage: 'date is required' + }, + mob: + { + required: true, + number: true, + regex: /[0-9]+$/, + in: ['body'], + length: 10, + errorMessage: 'mobile no. is required', + custom: (reqMethod, req, res, next) => { + console.log( req[reqMethod].mob); + if ( req[reqMethod].mob !== undefined ) { + if ( req[reqMethod].mob.length !== 10) + return true; + } + return false; + } + }, + hobbies: + { + required: true, + array: true, + in: ['body'], + errorMessage: 'hobbies is required', + custom: (reqMethod, req, res, next) => { + if ( Array.isArray(req[reqMethod].hobbies) === false ) { + console.log('inside hobby custom'); + return true; + } + return false; + }, } }, delete: @@ -79,4 +135,4 @@ const validation = { } } }; -export default validation ; +export default validation ; \ No newline at end of file diff --git a/src/Controllers/user/Controller.ts b/src/Controllers/user/Controller.ts index b891a48..ccedd3e 100644 --- a/src/Controllers/user/Controller.ts +++ b/src/Controllers/user/Controller.ts @@ -1,5 +1,5 @@ import * as bcrypt from 'bcrypt'; -import { Request, Response, response, NextFunction } from 'express'; +import { Request, Response } from 'express'; import { userRepository } from '../../repositories/user'; import SystemResponse from '../../libs/SystemResponse'; import * as jwt from 'jsonwebtoken'; @@ -15,62 +15,7 @@ class Controller { return Controller.instance; } } - create = async (req, res: Response) => { - console.log('----------Create Trainee----------'); - const { name, address, email, dob, mob, hobbies, role } = req.body; - try { - const userData = await userRepository.create(req.user._id, { name, address, email, dob, mob, hobbies, role }); - const message = 'Trainee added successfully'; - const data = userData; - SystemResponse.success(res, data, message); - } - catch (error) { - return SystemResponse.failure(res, error, 'User is not create'); - } - }; - list = async (req: Request, res: Response) => { - console.log('----------Trainee List----------'); - console.log(`req.query.skip = ${req.query.skip},req.query.limit = ${req.query.limit}`); - try { - const dataList = await userRepository.list(); - console.log(dataList); - const message = 'Trainee List'; - const data = dataList; - SystemResponse.success(res, data, message); - } - catch (error) { - return SystemResponse.failure(res, error, 'User data does not exist'); - } - }; - update = async (req, res: Response) => { - console.log('----------Update Trainee----------'); - try { - const value = await userRepository.update(req, req.body.id, req.body.dataToUpdate); - if (value) { - const message = 'Trainee Data successfully Updated'; - const data = req.body.dataToUpdate; - SystemResponse.success(res, data, message); - } - } - catch (error) { - return SystemResponse.failure(res, error, 'User data is not Updated'); - } - }; - delete = async(req, res: Response) => { - console.log('----------Delete Trainee----------'); - try { - const value = await userRepository.delete(req, req.params.id); - if (value) { - const message = 'Trainee Data Successfully Deleted'; - SystemResponse.success(res, req.params.id, message); - } - } - catch (error) { - return SystemResponse.failure(res, error, 'User data is not deleted'); - } - - }; - me = (req, res: Response, next: NextFunction) => { + me = (req, res: Response) => { console.log('--------------me-------------'); delete req.user.password; SystemResponse.success(res, req.user, 'User data fetched'); @@ -90,7 +35,7 @@ class Controller { return SystemResponse.failure(res, 'Password is incorrect', 'Password does not match', 422); } console.log('Password matched'); - const token = jwt.sign({ email: user.email , _id: user.originalId }, config.Key); + const token = jwt.sign({ email: user.email , _id: user.originalId }, config.Key, { expiresIn: 900 }); return SystemResponse.success(res, token); } catch (err) { diff --git a/src/Controllers/user/routes.ts b/src/Controllers/user/routes.ts index 161a4b1..3c49bbd 100644 --- a/src/Controllers/user/routes.ts +++ b/src/Controllers/user/routes.ts @@ -3,12 +3,6 @@ import Controller from './Controller'; import { validationHandler, authMiddleWare } from '../../libs/routes/index' ; import { default as validation } from './validation' ; const userRouter: Router = Router(); -userRouter.route('/') - .get(authMiddleWare('traineeModule', 'read'), validationHandler(validation.get), Controller.list) - .post(authMiddleWare('traineeModule', 'read'), validationHandler(validation.create), Controller.create) - .put(authMiddleWare('traineeModule', 'read'), validationHandler(validation.update), Controller.update); -userRouter.route('/:id') - .delete(authMiddleWare('traineeModule', 'read'), validationHandler(validation.delete), Controller.delete); userRouter.route('/me') .get(authMiddleWare('traineeModule', 'read'), validationHandler(validation.get), Controller.me); userRouter.route('/login') diff --git a/src/Controllers/user/validation.ts b/src/Controllers/user/validation.ts index 927ac5e..5023cf3 100644 --- a/src/Controllers/user/validation.ts +++ b/src/Controllers/user/validation.ts @@ -1,84 +1,4 @@ const validation = { - create: - { - name: - { - required: true, - regex: /^[a-zA-Z]+(([',. -][a-zA-Z ])?[a-zA-Z]*)*$/, - in: ['body'], - errorMessage: 'Name is required', - }, - address: - { - required: true, - string: true, - regex: /[\w]+/, - in: ['body'], - errorMessage: 'address is required' - }, - role: - { - required: true, - string: true, - regex: /^[a-zA-Z]+/, - in: ['body'], - errorMessage: 'role is required' - }, - email: - { - required: true, - string: true, - regex: /[a-z]([[-]*\w+[.]*){1,63}@successive[.]tech$/, - in: ['body'], - errorMessage: 'email is required' - }, - dob: - { - required: true, - date: true, - in: ['body'], - errorMessage: 'date is required' - }, - mob: - { - required: true, - number: true, - regex: /[0-9]+$/, - in: ['body'], - length: 10, - errorMessage: 'mobile no. is required', - custom: (reqMethod, req, res, next) => { - if ( req[reqMethod].mob.length !== 10 ) { - console.log('inside mob custom'); - return true; - } - return false; - } - }, - hobbies: - { - required: true, - array: true, - in: ['body'], - errorMessage: 'hobbies is required', - custom: (reqMethod, req, res, next) => { - if ( Array.isArray(req[reqMethod].hobbies) === false ) { - console.log('inside hobby custom'); - return true; - } - return false; - }, - } - }, - delete: - { - id: - { - required: true, - errorMessage: 'Id is required', - in: ['params'] - } - }, get: { skip: @@ -110,29 +30,6 @@ const validation = { } } }, - update: - { - id: - { - required: true, - string: true, - regex: /[\w]+/, - in: ['body'] , - errorMessage: 'Id is required' - }, - dataToUpdate: - { - in: ['body'], - required: true, - isObject: true, - errorMessage: 'Data is required', - custom: (reqMethod, req, res, next) => { - if (typeof req[reqMethod] !== 'object' ) { - return { error: 'Error Occured', message: 'Not an Object'}; - } - } - } - }, login: { email: diff --git a/src/repositories/user/UserRepository.ts b/src/repositories/user/UserRepository.ts index 430ff43..868318f 100644 --- a/src/repositories/user/UserRepository.ts +++ b/src/repositories/user/UserRepository.ts @@ -16,14 +16,17 @@ class UserRepository extends VersionableRepository { return super.update(req, id, updatedData); } - count = () => { + count = () => { return this.versionModel.countDocuments(); } - list = () => { - return super.list(); + countTrainee = () => { + return this.versionModel.countDocuments({role: 'trainee', deletedAt: {$exists: false}}); + } + list = (userRole, skip, limit, sortBy) => { + return super.list(userRole, skip, limit, sortBy); } findOne = (id) => { - return this.versionModel.findOne({_id: id}).exec(); + return this.versionModel.findOne({originalId: id}).exec(); } findByEmail = (emailId) => { return this.versionModel.findOne({email: emailId}); diff --git a/src/repositories/versionable/VersionableRepository.ts b/src/repositories/versionable/VersionableRepository.ts index 86b5952..c0553d2 100644 --- a/src/repositories/versionable/VersionableRepository.ts +++ b/src/repositories/versionable/VersionableRepository.ts @@ -42,7 +42,7 @@ export default class VersionRepository< D extends mongoose.Document, M extends m } ); } - public list() { - return this.versionModel.find({deletedAt: undefined}).exec(); + public list(userRole, skipRecord, limitRecord, sortBy) { + return this.versionModel.find({deletedAt: undefined, role: userRole}).sort(sortBy).skip(Number(skipRecord)).limit(Number(limitRecord)); } } \ No newline at end of file diff --git a/src/repositories/versionable/VersionableSchema.ts b/src/repositories/versionable/VersionableSchema.ts index a0be1db..1e10d79 100644 --- a/src/repositories/versionable/VersionableSchema.ts +++ b/src/repositories/versionable/VersionableSchema.ts @@ -4,7 +4,7 @@ export default class VersionableSchema extends mongoose.Schema { const versionSchema = { originalId: String, createdAt: Date, - updatedAt: Date, + updatedAt: { type: Date, default: Date.now() }, deletedAt: Date, createdBy: String, updatedBy: String, From 0733218897522a375939253886994833b024dc01 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Mon, 17 Feb 2020 17:55:53 +0530 Subject: [PATCH 81/91] =?UTF-8?q?fix:=20=F0=9F=90=9B=20add=20changes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controllers/trainee/Controller.ts | 19 +++++++----- src/Controllers/trainee/validation.ts | 18 ++++++++++- src/Controllers/user/validation.ts | 5 ++++ src/libs/SystemResponse.ts | 2 +- src/libs/routes/authMiddleWare.ts | 30 +++++++------------ src/libs/routes/validationHandler.ts | 2 -- src/repositories/user/UserRepository.ts | 2 +- .../versionable/VersionableRepository.ts | 4 ++- 8 files changed, 49 insertions(+), 33 deletions(-) diff --git a/src/Controllers/trainee/Controller.ts b/src/Controllers/trainee/Controller.ts index a65fbfb..8252d8a 100644 --- a/src/Controllers/trainee/Controller.ts +++ b/src/Controllers/trainee/Controller.ts @@ -1,6 +1,7 @@ import { Request, Response } from 'express'; import { userRepository } from '../../repositories/user'; import SystemResponse from '../../libs/SystemResponse'; +import * as bcrypt from 'bcrypt'; class Controller { static instance: Controller; static getInstance = () => { @@ -14,12 +15,14 @@ class Controller { } create = async (req, res: Response) => { console.log('----------Create Trainee----------'); - const { name, address, email, dob, mob, hobbies, role } = req.body; + const { name, address, email, dob, mob, hobbies, role, password} = req.body; try { - const userData = await userRepository.create(req.user._id, { name, address, email, dob, mob, hobbies, role }); + const hash = await bcrypt.hash(password, 10); + const userData = await userRepository.create(req.user._id, { name, address, email, dob, mob, hobbies, role, password: hash }); const message = 'Trainee added successfully'; - const data = userData; - SystemResponse.success(res, data, message); + userData.password = '*****'; + console.log(userData); + SystemResponse.success(res, userData, message); } catch (error) { return SystemResponse.failure(res, error, 'User is not create'); @@ -31,16 +34,16 @@ class Controller { try { let sortBy; if (req.query.sortBy === 'email') - sortBy = { email: 1 }; + sortBy = { email: req.query.order}; else if (req.query.sortBy === 'name') - sortBy = { name: 1 }; + sortBy = { name: req.query.order}; else - sortBy = {updatedAt: 1}; + sortBy = {updatedAt: req.query.order}; const dataList = await userRepository.list('trainee', req.query.skip, req.query.limit, sortBy); console.log(dataList); const count = await userRepository.countTrainee(); const message = 'Trainee List , No. of trainee: ' + count ; - const data = dataList; + const data = {Count: count, ...dataList}; SystemResponse.success(res, data, message); } catch (error) { diff --git a/src/Controllers/trainee/validation.ts b/src/Controllers/trainee/validation.ts index ebf2d92..71f5c9a 100644 --- a/src/Controllers/trainee/validation.ts +++ b/src/Controllers/trainee/validation.ts @@ -48,7 +48,6 @@ const validation = { length: 10, errorMessage: 'mobile no. is required', custom: (reqMethod, req, res, next) => { - console.log( req[reqMethod].mob); if ( req[reqMethod].mob !== undefined ) { if ( req[reqMethod].mob.length !== 10) return true; @@ -69,6 +68,11 @@ const validation = { } return false; }, + }, + password: + { + required: true, + in: ['body'], } }, delete: @@ -109,6 +113,18 @@ const validation = { req[reqMethod].limit = '10'; } } + } , + order: + { + required: false, + default: 1, + in: ['query'], + errorMessage: 'Order is invalid', + custom: (reqMethod, req, res, next): void => { + if ( req[reqMethod].order === undefined || req[reqMethod].order !== '-1' ) { + req[reqMethod].order = '1'; + } + } } }, update: diff --git a/src/Controllers/user/validation.ts b/src/Controllers/user/validation.ts index 5023cf3..47e8cd8 100644 --- a/src/Controllers/user/validation.ts +++ b/src/Controllers/user/validation.ts @@ -40,6 +40,11 @@ const validation = { in: ['body'], errorMessage: 'email is required' }, + password: + { + required: true, + in: ['body'], + } } }; export default validation ; \ No newline at end of file diff --git a/src/libs/SystemResponse.ts b/src/libs/SystemResponse.ts index ede6456..059663e 100644 --- a/src/libs/SystemResponse.ts +++ b/src/libs/SystemResponse.ts @@ -8,7 +8,7 @@ class SystemResponse { } static failure = (res, err, message = 'Failure', status = 400) => { return res.status(status).send({ - status: 'Not ok', + status: err.status || 'Bad Request', message, err }); diff --git a/src/libs/routes/authMiddleWare.ts b/src/libs/routes/authMiddleWare.ts index aa2fc15..29de1c3 100644 --- a/src/libs/routes/authMiddleWare.ts +++ b/src/libs/routes/authMiddleWare.ts @@ -7,7 +7,7 @@ import IUserModel from '../../repositories/user/IUserModel'; interface IRequest extends Request { user: IUserModel; } -const authMiddleWare = (module, permissionType) => (req: IRequest, res: Response, next: NextFunction) => { +const authMiddleWare = (module, permissionType) => async (req: IRequest, res: Response, next: NextFunction) => { console.log('------------AUTHMIDDLEWARE------------', module, permissionType); try { const token: string = req.headers.authorization; @@ -22,29 +22,21 @@ const authMiddleWare = (module, permissionType) => (req: IRequest, res: Response }); } console.log(decodedUser); - UserRepository.findOne(decodedUser._id) - .then((userData) => { - console.log(userData); - req.user = userData; - const role: string = userData.role; - if (!hasPermission(module, role, permissionType)) { - console.log(`${ role } does not permission of ${ permissionType }`); - return next({ - status: 403, - error: 'Unauthorized Access', - message: 'Unauthorized Access' - }); - } - next(); - }) - .catch((err) => { - console.log(err); + const userData = await UserRepository.findOne(decodedUser._id); + console.log(userData); + req.user = userData; + const role: string = userData.role; + if (decodedUser._id === req.body.id && req.method === 'PUT') + return next(); + if (!hasPermission(module, role, permissionType)) { + console.log(`${ role } does not permission of ${ permissionType }`); return next({ status: 403, error: 'Unauthorized Access', message: 'Unauthorized Access' }); - }); + } + next(); } catch (error) { return next({ diff --git a/src/libs/routes/validationHandler.ts b/src/libs/routes/validationHandler.ts index 8e4370e..ac8b07e 100644 --- a/src/libs/routes/validationHandler.ts +++ b/src/libs/routes/validationHandler.ts @@ -5,8 +5,6 @@ export default (config) => { console.log(config); console.log(req.body); const err = []; - const params = new Set(); - const values = new Set(); Object.keys(config).forEach(key => { console.log(`---------${ key }---------`); const { errorMessage } = config[key]; diff --git a/src/repositories/user/UserRepository.ts b/src/repositories/user/UserRepository.ts index 868318f..5154d4b 100644 --- a/src/repositories/user/UserRepository.ts +++ b/src/repositories/user/UserRepository.ts @@ -29,7 +29,7 @@ class UserRepository extends VersionableRepository { - return this.versionModel.findOne({email: emailId}); + return this.versionModel.findOne({email: emailId, deletedAt: undefined}); } } export default new UserRepository(); \ No newline at end of file diff --git a/src/repositories/versionable/VersionableRepository.ts b/src/repositories/versionable/VersionableRepository.ts index c0553d2..565cd23 100644 --- a/src/repositories/versionable/VersionableRepository.ts +++ b/src/repositories/versionable/VersionableRepository.ts @@ -29,7 +29,9 @@ export default class VersionRepository< D extends mongoose.Document, M extends m } async update(req, id, updatedData) { const oldData: any = await this.versionModel.findOne({originalId: id , deletedAt: undefined}).exec(); + const { name, address, email, dob, mob, hobbies, role, password} = oldData; this.versionModel.create({ + name, address, email, dob, mob, hobbies, role, password, ...updatedData, originalId: id, updatedAt: Date.now(), @@ -43,6 +45,6 @@ export default class VersionRepository< D extends mongoose.Document, M extends m ); } public list(userRole, skipRecord, limitRecord, sortBy) { - return this.versionModel.find({deletedAt: undefined, role: userRole}).sort(sortBy).skip(Number(skipRecord)).limit(Number(limitRecord)); + return this.versionModel.find({deletedAt: undefined, role: userRole}, {password: 0}).sort(sortBy).skip(Number(skipRecord)).limit(Number(limitRecord)); } } \ No newline at end of file From 0fa24cbd702c9c01384d8a9ff70f6450c091f1e8 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 18 Feb 2020 13:37:10 +0530 Subject: [PATCH 82/91] =?UTF-8?q?fix:=20=F0=9F=90=9B=20add=20changes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env | 2 +- src/Controllers/trainee/Controller.ts | 14 ++++++- src/repositories/user/UserRepository.ts | 4 +- .../versionable/VersionableRepository.ts | 37 +++++++++++-------- 4 files changed, 38 insertions(+), 19 deletions(-) diff --git a/.env b/.env index ef5d356..15ba9fd 100644 --- a/.env +++ b/.env @@ -1,4 +1,4 @@ -PORT=9002 +PORT=9000 NODE_ENV=dev SECRET_KEY=qwertyuiopasdfghjklzxcvbnm123456 MONGO_URL=mongodb://localhost:27017/express-training diff --git a/src/Controllers/trainee/Controller.ts b/src/Controllers/trainee/Controller.ts index 8252d8a..a86f331 100644 --- a/src/Controllers/trainee/Controller.ts +++ b/src/Controllers/trainee/Controller.ts @@ -18,11 +18,16 @@ class Controller { const { name, address, email, dob, mob, hobbies, role, password} = req.body; try { const hash = await bcrypt.hash(password, 10); + const validity = await userRepository.findByEmail(email); + if (!validity) { const userData = await userRepository.create(req.user._id, { name, address, email, dob, mob, hobbies, role, password: hash }); const message = 'Trainee added successfully'; userData.password = '*****'; console.log(userData); SystemResponse.success(res, userData, message); + } + else + return SystemResponse.failure(res, 'User is not create', 'Email id already exist'); } catch (error) { return SystemResponse.failure(res, error, 'User is not create'); @@ -33,13 +38,18 @@ class Controller { console.log(`req.query.skip = ${req.query.skip},req.query.limit = ${req.query.limit}`); try { let sortBy; + let searchBy = {}; if (req.query.sortBy === 'email') sortBy = { email: req.query.order}; else if (req.query.sortBy === 'name') sortBy = { name: req.query.order}; else sortBy = {updatedAt: req.query.order}; - const dataList = await userRepository.list('trainee', req.query.skip, req.query.limit, sortBy); + if ( req.query.email !== undefined) + searchBy = {...searchBy, email: req.query.email }; + else if (req.query.name !== undefined) + searchBy = {...searchBy, name: req.query.name }; + const dataList = await userRepository.list('trainee', req.query.skip, req.query.limit, sortBy, searchBy); console.log(dataList); const count = await userRepository.countTrainee(); const message = 'Trainee List , No. of trainee: ' + count ; @@ -59,6 +69,8 @@ class Controller { const data = req.body.dataToUpdate; SystemResponse.success(res, data, message); } + else + return SystemResponse.failure(res, 'User data is not Updated', 'Email id already exist'); } catch (error) { return SystemResponse.failure(res, error, 'User data is not Updated'); diff --git a/src/repositories/user/UserRepository.ts b/src/repositories/user/UserRepository.ts index 5154d4b..0e38603 100644 --- a/src/repositories/user/UserRepository.ts +++ b/src/repositories/user/UserRepository.ts @@ -22,8 +22,8 @@ class UserRepository extends VersionableRepository { return this.versionModel.countDocuments({role: 'trainee', deletedAt: {$exists: false}}); } - list = (userRole, skip, limit, sortBy) => { - return super.list(userRole, skip, limit, sortBy); + list = (userRole, skip, limit, sortBy, searchBy) => { + return super.list(userRole, skip, limit, sortBy, searchBy); } findOne = (id) => { return this.versionModel.findOne({originalId: id}).exec(); diff --git a/src/repositories/versionable/VersionableRepository.ts b/src/repositories/versionable/VersionableRepository.ts index 565cd23..b147e28 100644 --- a/src/repositories/versionable/VersionableRepository.ts +++ b/src/repositories/versionable/VersionableRepository.ts @@ -30,21 +30,28 @@ export default class VersionRepository< D extends mongoose.Document, M extends m async update(req, id, updatedData) { const oldData: any = await this.versionModel.findOne({originalId: id , deletedAt: undefined}).exec(); const { name, address, email, dob, mob, hobbies, role, password} = oldData; - this.versionModel.create({ - name, address, email, dob, mob, hobbies, role, password, - ...updatedData, - originalId: id, - updatedAt: Date.now(), - updatedBy: req.user._id - }); - return this.versionModel.findByIdAndUpdate( oldData._id , - { - deletedAt: Date.now(), - deletedBy: req.user._id - } - ); + const bool = await this.versionModel.findOne({email: updatedData.email, deletedAt: undefined}); + if ( updatedData.email !== email && ! bool) { + this.versionModel.create({ + name, address, email, dob, mob, hobbies, role, + ...updatedData, + password, + originalId: id, + updatedAt: Date.now(), + updatedBy: req.user._id + }); + return this.versionModel.findByIdAndUpdate( oldData._id , + { + deletedAt: Date.now(), + deletedBy: req.user._id + } + ); + } + else { + return false; + } } - public list(userRole, skipRecord, limitRecord, sortBy) { - return this.versionModel.find({deletedAt: undefined, role: userRole}, {password: 0}).sort(sortBy).skip(Number(skipRecord)).limit(Number(limitRecord)); + public list(userRole, skipRecord, limitRecord, sortBy, searchBy) { + return this.versionModel.find({deletedAt: undefined, role: userRole, ...searchBy}, {password: 0}).sort(sortBy).skip(Number(skipRecord)).limit(Number(limitRecord)); } } \ No newline at end of file From e28d791187f351a3fdc411c839ac89fa99d9f8f3 Mon Sep 17 00:00:00 2001 From: AryanSinghalGit <60099465+AryanSinghalGit@users.noreply.github.com> Date: Tue, 18 Feb 2020 18:36:18 +0530 Subject: [PATCH 83/91] Update UserSchema.ts --- src/repositories/user/UserSchema.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/repositories/user/UserSchema.ts b/src/repositories/user/UserSchema.ts index 111dfb8..6a38cb8 100644 --- a/src/repositories/user/UserSchema.ts +++ b/src/repositories/user/UserSchema.ts @@ -6,7 +6,7 @@ class UserSchema extends VersionableSchema { name: String , address: String , role: String , - email: String , + email: {type: String, unique: true}, password: String , dob: Date , mob: Number, @@ -15,4 +15,4 @@ class UserSchema extends VersionableSchema { super(userSchema, options); } } -export default UserSchema; \ No newline at end of file +export default UserSchema; From 8671ce719ea9658d403531612e5faec5716c2253 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 18 Feb 2020 18:39:46 +0530 Subject: [PATCH 84/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20add=20APIs=20Compl?= =?UTF-8?q?etion?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 3 +++ src/Server.ts | 34 +++++++++++++++-------------- src/api/swagger/swagger.yaml | 13 +++++++++++ src/repositories/user/UserSchema.ts | 2 +- 4 files changed, 35 insertions(+), 17 deletions(-) create mode 100644 src/api/swagger/swagger.yaml diff --git a/package.json b/package.json index 008a691..ec1f493 100644 --- a/package.json +++ b/package.json @@ -41,6 +41,9 @@ "nodemon": "2.0.2", "pre-commit": "1.2.2", "pre-push": "0.1.1", + "swagger": "0.7.5", + "swagger-jsdoc": "^3.5.0", + "swagger-ui-express": "^4.1.3", "tslint": "6.0.0" }, "devDependencies": { diff --git a/src/Server.ts b/src/Server.ts index 08523ec..9471b0e 100644 --- a/src/Server.ts +++ b/src/Server.ts @@ -1,8 +1,10 @@ import * as express from 'express'; import * as bodyParser from 'body-parser'; -import { notFoundRoute , errorHandler } from './libs/routes'; +import { notFoundRoute, errorHandler } from './libs/routes'; import { default as mainRouter } from './router'; import Database from './libs/Database'; +import * as swaggerJsDoc from 'swagger-jsdoc'; +import * as swaggerUI from 'swagger-ui-express'; export class Server { private app: express.Express; constructor(protected config) { @@ -14,22 +16,22 @@ export class Server { return this; } public run = (): Server => { - const { app, config: { Port, MongoURL} }: Server = this; + const { app, config: { Port, MongoURL } }: Server = this; Database.open(MongoURL) - .then(() => { - app.listen(Port, (err) => { - if (err) { - console.log(err); - } - else { - console.log(`Express app Successfully started on port : ${Port} `); - } - }); - }) - .catch((err) => { - console.log(err); - } - ); + .then(() => { + app.listen(Port, (err) => { + if (err) { + console.log(err); + } + else { + console.log(`Express app Successfully started on port : ${Port} `); + } + }); + }) + .catch((err) => { + console.log(err); + } + ); return this; } public initBodyParser = () => { diff --git a/src/api/swagger/swagger.yaml b/src/api/swagger/swagger.yaml new file mode 100644 index 0000000..f663504 --- /dev/null +++ b/src/api/swagger/swagger.yaml @@ -0,0 +1,13 @@ +swagger: "2.3" +info: + version: "1.0.0" + title: Javascript-Server API +host: localhost:9000 +basepath: / +schemes: + - http +consumes: + - application/json +produces: + - application/json +paths: \ No newline at end of file diff --git a/src/repositories/user/UserSchema.ts b/src/repositories/user/UserSchema.ts index 111dfb8..03c51fa 100644 --- a/src/repositories/user/UserSchema.ts +++ b/src/repositories/user/UserSchema.ts @@ -6,7 +6,7 @@ class UserSchema extends VersionableSchema { name: String , address: String , role: String , - email: String , + email: {type: String, unique: true}, password: String , dob: Date , mob: Number, From 4e0bfc3f69f72efa5d2d2798d4ef0bed53ffacf1 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Wed, 19 Feb 2020 15:52:12 +0530 Subject: [PATCH 85/91] =?UTF-8?q?fix:=20=F0=9F=90=9B=20add=20changes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controllers/trainee/Controller.ts | 17 +++++++++++------ src/repositories/user/UserRepository.ts | 3 +++ .../versionable/VersionableRepository.ts | 7 ++++++- 3 files changed, 20 insertions(+), 7 deletions(-) diff --git a/src/Controllers/trainee/Controller.ts b/src/Controllers/trainee/Controller.ts index a86f331..dc1cbff 100644 --- a/src/Controllers/trainee/Controller.ts +++ b/src/Controllers/trainee/Controller.ts @@ -15,9 +15,12 @@ class Controller { } create = async (req, res: Response) => { console.log('----------Create Trainee----------'); - const { name, address, email, dob, mob, hobbies, role, password} = req.body; + const { address, dob, mob, hobbies, role, password} = req.body; + let { name, email } = req.body; try { const hash = await bcrypt.hash(password, 10); + email = email.toLowerCase(); + name = name.toLowerCase(); const validity = await userRepository.findByEmail(email); if (!validity) { const userData = await userRepository.create(req.user._id, { name, address, email, dob, mob, hobbies, role, password: hash }); @@ -41,14 +44,16 @@ class Controller { let searchBy = {}; if (req.query.sortBy === 'email') sortBy = { email: req.query.order}; - else if (req.query.sortBy === 'name') + if (req.query.sortBy === 'name') sortBy = { name: req.query.order}; else sortBy = {updatedAt: req.query.order}; - if ( req.query.email !== undefined) - searchBy = {...searchBy, email: req.query.email }; - else if (req.query.name !== undefined) - searchBy = {...searchBy, name: req.query.name }; + if ( req.query.email !== undefined) { + searchBy = {...searchBy, email: { $regex: req.query.email.toLowerCase() }}; + } + if (req.query.name !== undefined) { + searchBy = {...searchBy, name: { $regex: req.query.order.toLowerCase()}}; + } const dataList = await userRepository.list('trainee', req.query.skip, req.query.limit, sortBy, searchBy); console.log(dataList); const count = await userRepository.countTrainee(); diff --git a/src/repositories/user/UserRepository.ts b/src/repositories/user/UserRepository.ts index 0e38603..d12f654 100644 --- a/src/repositories/user/UserRepository.ts +++ b/src/repositories/user/UserRepository.ts @@ -31,5 +31,8 @@ class UserRepository extends VersionableRepository { return this.versionModel.findOne({email: emailId, deletedAt: undefined}); } + // createIndexes = (searchBy: string, search: string): IUserModel => { + // return this.versionModel.createIndexes({ name : 'text', email: 'text' ); + // } } export default new UserRepository(); \ No newline at end of file diff --git a/src/repositories/versionable/VersionableRepository.ts b/src/repositories/versionable/VersionableRepository.ts index b147e28..3a46b72 100644 --- a/src/repositories/versionable/VersionableRepository.ts +++ b/src/repositories/versionable/VersionableRepository.ts @@ -30,8 +30,13 @@ export default class VersionRepository< D extends mongoose.Document, M extends m async update(req, id, updatedData) { const oldData: any = await this.versionModel.findOne({originalId: id , deletedAt: undefined}).exec(); const { name, address, email, dob, mob, hobbies, role, password} = oldData; + if ( updatedData.name !== undefined) + updatedData.name = updatedData.name.toLowerCase(); + if ( updatedData.email !== undefined) + updatedData.email = updatedData.email.toLowerCase(); const bool = await this.versionModel.findOne({email: updatedData.email, deletedAt: undefined}); - if ( updatedData.email !== email && ! bool) { + console.log(updatedData.email, email , bool, updatedData.email !== email); + if ( !(updatedData.email !== email && updatedData.email !== undefined && bool !== null)) { this.versionModel.create({ name, address, email, dob, mob, hobbies, role, ...updatedData, From ccf59335427d82842d59a91183a15570fa9a1840 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Thu, 20 Feb 2020 18:48:44 +0530 Subject: [PATCH 86/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20add=20APIs=20Compl?= =?UTF-8?q?etion?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- package.json | 2 +- src/Controllers/trainee/routes.ts | 196 +++++++++++++++++++++++++++++- src/Controllers/user/routes.ts | 69 ++++++++++- src/Server.ts | 54 +++++--- src/api/swagger/swagger.yaml | 13 -- src/index.ts | 3 +- 6 files changed, 303 insertions(+), 34 deletions(-) delete mode 100644 src/api/swagger/swagger.yaml diff --git a/package.json b/package.json index ec1f493..cec5436 100644 --- a/package.json +++ b/package.json @@ -50,4 +50,4 @@ "tsc-watch": "4.1.0", "typescript": "3.7.5" } -} +} \ No newline at end of file diff --git a/src/Controllers/trainee/routes.ts b/src/Controllers/trainee/routes.ts index 92eb732..0c763c0 100644 --- a/src/Controllers/trainee/routes.ts +++ b/src/Controllers/trainee/routes.ts @@ -1,12 +1,204 @@ import { Router } from 'express'; import controller from './Controller'; -import { validationHandler, authMiddleWare } from '../../libs/routes' ; -import { default as validation } from './validation' ; +import { validationHandler, authMiddleWare } from '../../libs/routes'; +import { default as validation } from './validation'; const traineeRouter: Router = Router(); traineeRouter.route('/') + /** + * @swagger + * + * /api/trainee: + * get: + * description: Returns the list of the trainees + * security: + * - Bearer: [] + * consumes: + * - application/json + * produces: + * - application/json + * responses: + * 200: + * description: Trainee List + * schema: + * allOf: + * properties: + * status: + * example: Ok + * message: + * example: 'Trainee List , No. of trainee: 2' + * count: + * example: 2 + * data: + * type: object + * allOf: + * - $ref: '#/definitions/TraineeResponse' + * 403: + * description: unauthorised access + */ .get(authMiddleWare('traineeModule', 'read'), validationHandler(validation.get), controller.list) + /** + * @swagger + * + * definitions: + * TraineePost: + * type: object + * properties: + * email: + * type: string + * example: aryan.singhal@successive.tech + * name: + * type: string + * example: aryan singhal + * password: + * type: string + * example: training@123 + * mob: + * type: number + * example: "9811422797" + * address: + * type: string + * example: Ghaziabad + * dob: + * type: Date + * example: 06/07/1998 + * role: + * type: string + * example: trainee + * hobbies: + * type: array + * example: ["singing", "hiking"] + * + * TraineeResponse: + * type: object + * properties: + * _id: + * example: 5e4e6e93c095d84d34045a30 + * email: + * type: string + * example: aryan.singhal@successive.tech + * name: + * type: string + * example: Aryan Singhal + * mob: + * type: number + * example: "9811422797" + * address: + * type: string + * example: Ghaziabad + * dob: + * type: Date + * example: 06/07/1998 + * role: + * type: string + * example: trainee + * hobbies: + * type: array + * example: ["singing", "hiking"] + * originalId: + * example: 5e4e6e93c095d84d34045a30 + * createdBy: + * example: 5e45404398e86d576ad964e6 + * createdAt: + * example: 2020-02-20T11:33:39.325Z + * v: + * example:0 + * + */ + + + + + /** + * @swagger + * + * /api/trainee: + * post: + * description: Returns the success reponse on creation + * security: + * - Bearer: [] + * produces: + * - application/json + * parameters: + * - name: User + * description: User's Data. + * in: body + * required: true + * type: object + * schema: + * $ref: '#/definitions/TraineePost' + * responses: + * 200: + * description: User created successfully + * schema: + * allOf: + * properties: + * status: + * example: Ok + * message: + * example: Trainee successfully created + * data: + * type: object + * allOf: + * - $ref: '#/definitions/TraineeResponse' + * properties: + * password: + * type: string + * example: "*****" + * 403: + * description: unauthorised access + */ .post(authMiddleWare('traineeModule', 'write'), validationHandler(validation.create), controller.create) + + /** + * @swagger + * + * /api/trainee: + * put: + * description: Returns the success reponse on creation + * security: + * - Bearer: [] + * produces: + * - application/json + * schema: + * allOf: + * properties: + * allOf: + * id: + * type: string + * example: 5e4e6e93c095d84d34045a30 + * dataToUpdate: + * type: object + * allOf: + * $ref: '#/definitions/TraineePost' + * responses: + * 200: + * description: user data successfully updated + * 403: + * description: unauthorised access + */ .put(authMiddleWare('traineeModule', 'write'), validationHandler(validation.update), controller.update); +/** + * @swagger + * + * /api/trainee/{id}: + * delete: + * description: Returns the success reponse on creation + * security: + * - Bearer: [] + * produces: + * - application/json + * parameters: + * - name: id + * description: id of user to be deleted. + * in: path + * required: true + * type: string + * responses: + * 200: + * description: login + * 403: + * description: unauthorised access + */ traineeRouter.route('/:id') .delete(authMiddleWare('traineeModule', 'delete'), validationHandler(validation.delete), controller.delete); export default traineeRouter; \ No newline at end of file diff --git a/src/Controllers/user/routes.ts b/src/Controllers/user/routes.ts index 3c49bbd..adc6c8f 100644 --- a/src/Controllers/user/routes.ts +++ b/src/Controllers/user/routes.ts @@ -3,8 +3,75 @@ import Controller from './Controller'; import { validationHandler, authMiddleWare } from '../../libs/routes/index' ; import { default as validation } from './validation' ; const userRouter: Router = Router(); +/** + * @swagger + * + * definitions: + * Login: + * type: object + * properties: + * email: + * type: string + * example: vinay.chaudhary@successive.tech + * password: + * type: string + * example: aryan@123 + * Token: + * type: string + * properties: + * status: + * example: Ok + * message: + * example: Success + * data: + * type:string + * example:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InZpbmF5LmNoYXVkaGFyeUBzdWNjZXNzaXZlLnRlY2giLCJfaWQiOiI1ZTQ1NDA0Mzk4ZTg2ZDU3NmFkOTY0ZTYiLCJpYXQiOjE1ODIxOTY2MjUsImV4cCI6MTU4MjE5NzUyNX0.sLT3-1NmeyJtS0eDjhO3SUDiVSgaizfX0R7sqPgG040 + */ + +/** + * @swagger + * + * /api/user/me: + * get: + * description: Details of the current user. + * security: + * - Bearer: [] + * produces: + * - application/json + * responses: + * 200: + * description: success + * schema: + * $ref: '#/definitions/TraineeResponse' + */ userRouter.route('/me') .get(authMiddleWare('traineeModule', 'read'), validationHandler(validation.get), Controller.me); +/** + * @swagger + * + * /api/user/login: + * post: + * description: Login Credentials + * security: + * - Bearer: [] + * produces: + * - application/json + * parameters: + * - name: User + * description: User email and password + * in: body + * required: true + * type: object + * schema: + * $ref: '#/definitions/Login' + * responses: + * 200: + * description: login + * schema: + * $ref: '#/definitions/Token' + * 422: + * description: invalid email or password + */ userRouter.route('/login') .post(validationHandler(validation.login), Controller.login); -export default userRouter; \ No newline at end of file +export default userRouter; diff --git a/src/Server.ts b/src/Server.ts index 9471b0e..74713fc 100644 --- a/src/Server.ts +++ b/src/Server.ts @@ -15,23 +15,44 @@ export class Server { this.setupRoutes(); return this; } - public run = (): Server => { - const { app, config: { Port, MongoURL } }: Server = this; - Database.open(MongoURL) - .then(() => { - app.listen(Port, (err) => { - if (err) { - console.log(err); - } - else { - console.log(`Express app Successfully started on port : ${Port} `); - } - }); - }) - .catch((err) => { - console.log(err); + public initSwagger = () => { + const options = { + definition: { + info: { + title: 'Javascript-Server API', + version: '1.0.0', + }, + securityDefinitions: { + Bearer: { + type: 'apiKey', + name: 'Authorization', + in: 'headers' + } } - ); + }, + basePath: '/api', + swagger: '2.0', + apis: ['./dist/Controllers/**/routes.js'], + }; + const swaggerSpec = swaggerJsDoc(options); + return swaggerSpec; + } + public run = async (): Promise => { + try { + const { app, config: { Port, MongoURL } }: Server = this; + await Database.open(MongoURL); + app.listen(Port, (err) => { + if (err) { + console.log(err); + } + else { + console.log(`Express app Successfully started on port : ${Port} `); + } + }); + } + catch (err) { + console.log(err); + } return this; } public initBodyParser = () => { @@ -41,6 +62,7 @@ export class Server { } public setupRoutes = (): void => { const { app }: Server = this; + this.app.use('/swagger', swaggerUI.serve, swaggerUI.setup(this.initSwagger())); app.get('/health-check', (req: express.Request, res: express.Response) => res.send('I am OK')); app.use('/api', mainRouter); app.use(notFoundRoute); diff --git a/src/api/swagger/swagger.yaml b/src/api/swagger/swagger.yaml deleted file mode 100644 index f663504..0000000 --- a/src/api/swagger/swagger.yaml +++ /dev/null @@ -1,13 +0,0 @@ -swagger: "2.3" -info: - version: "1.0.0" - title: Javascript-Server API -host: localhost:9000 -basepath: / -schemes: - - http -consumes: - - application/json -produces: - - application/json -paths: \ No newline at end of file diff --git a/src/index.ts b/src/index.ts index 481013e..7318eb8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -2,4 +2,5 @@ import { Server } from './Server'; import config from './config/configuration'; const server: Server = new Server(config); server.bootstrap(); -server.run(); \ No newline at end of file +server.run(); +server.initSwagger(); \ No newline at end of file From 7d416dba6e5b71e931f3fe4ee4ed9e62bad76052 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Fri, 21 Feb 2020 09:50:08 +0530 Subject: [PATCH 87/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20add=20APIs=20Compl?= =?UTF-8?q?etion?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controllers/trainee/Controller.ts | 14 ++- src/Controllers/trainee/routes.ts | 151 +++++++++++++++++++------- 2 files changed, 117 insertions(+), 48 deletions(-) diff --git a/src/Controllers/trainee/Controller.ts b/src/Controllers/trainee/Controller.ts index dc1cbff..c38a37b 100644 --- a/src/Controllers/trainee/Controller.ts +++ b/src/Controllers/trainee/Controller.ts @@ -41,20 +41,22 @@ class Controller { console.log(`req.query.skip = ${req.query.skip},req.query.limit = ${req.query.limit}`); try { let sortBy; - let searchBy = {}; + let dataList; if (req.query.sortBy === 'email') sortBy = { email: req.query.order}; if (req.query.sortBy === 'name') sortBy = { name: req.query.order}; else sortBy = {updatedAt: req.query.order}; - if ( req.query.email !== undefined) { - searchBy = {...searchBy, email: { $regex: req.query.email.toLowerCase() }}; + if (req.query.search !== undefined) { + dataList = await userRepository.list('trainee', req.query.skip, req.query.limit, sortBy, {name: { $regex: req.query.search.toLowerCase()}}); + const List = await userRepository.list('trainee', req.query.skip, req.query.limit, sortBy, {email: { $regex: req.query.search.toLowerCase()}}); + dataList = {...dataList, ...List }; } - if (req.query.name !== undefined) { - searchBy = {...searchBy, name: { $regex: req.query.order.toLowerCase()}}; + else { + dataList = await userRepository.list('trainee', req.query.skip, req.query.limit, sortBy, {}); } - const dataList = await userRepository.list('trainee', req.query.skip, req.query.limit, sortBy, searchBy); + console.log(dataList); const count = await userRepository.countTrainee(); const message = 'Trainee List , No. of trainee: ' + count ; diff --git a/src/Controllers/trainee/routes.ts b/src/Controllers/trainee/routes.ts index 0c763c0..3ebde1a 100644 --- a/src/Controllers/trainee/routes.ts +++ b/src/Controllers/trainee/routes.ts @@ -3,39 +3,6 @@ import controller from './Controller'; import { validationHandler, authMiddleWare } from '../../libs/routes'; import { default as validation } from './validation'; const traineeRouter: Router = Router(); -traineeRouter.route('/') - /** - * @swagger - * - * /api/trainee: - * get: - * description: Returns the list of the trainees - * security: - * - Bearer: [] - * consumes: - * - application/json - * produces: - * - application/json - * responses: - * 200: - * description: Trainee List - * schema: - * allOf: - * properties: - * status: - * example: Ok - * message: - * example: 'Trainee List , No. of trainee: 2' - * count: - * example: 2 - * data: - * type: object - * allOf: - * - $ref: '#/definitions/TraineeResponse' - * 403: - * description: unauthorised access - */ - .get(authMiddleWare('traineeModule', 'read'), validationHandler(validation.get), controller.list) /** * @swagger * @@ -102,12 +69,81 @@ traineeRouter.route('/') * example: 2020-02-20T11:33:39.325Z * v: * example:0 + * Unauthorized: + * type: object + * properties: + * error: + * example: Unauthorized + * message: + * example: Token not found + * status: + * example: 403 + * timestamp: + * example: 2019-03-10T19:51:37.066Z * */ - - - +traineeRouter.route('/') + /** + * @swagger + * + * /api/trainee: + * get: + * description: Returns the list of the trainees + * security: + * - Bearer: [] + * consumes: + * - application/json + * produces: + * - application/json + * parameters: + * - name: skip + * description: elements to be skip + * in: path + * required: false + * type: number + * - name: limit + * description: number of elements to be shown + * in: path + * required: false + * type: number + * - name: sortBy + * description: elements to be sort by + * in: path + * required: false + * type: string + * - name: searchBy + * description: elements to be skip + * in: path + * required: false + * type: string + * - name: order + * description: elements to be skip + * in: path + * required: false + * type: number + * responses: + * 200: + * description: Trainee List + * schema: + * allOf: + * properties: + * status: + * example: Ok + * message: + * example: 'Trainee List , No. of trainee: 2' + * count: + * example: 2 + * data: + * type: object + * allOf: + * - $ref: '#/definitions/TraineeResponse' + * 403: + * description: unauthorised access + * schema: + * $ref: '#/definitions/Unauthorized' + */ + .get(authMiddleWare('traineeModule', 'read'), validationHandler(validation.get), controller.list) /** * @swagger * @@ -146,6 +182,8 @@ traineeRouter.route('/') * example: "*****" * 403: * description: unauthorised access + * schema: + * $ref: '#/definitions/Unauthorized' */ .post(authMiddleWare('traineeModule', 'write'), validationHandler(validation.create), controller.create) @@ -159,22 +197,39 @@ traineeRouter.route('/') * - Bearer: [] * produces: * - application/json - * schema: - * allOf: + * parameters: + * - name: User + * description: User's Data. + * in: body + * required: true + * type: object + * schema: + * allOf: * properties: - * allOf: * id: - * type: string * example: 5e4e6e93c095d84d34045a30 * dataToUpdate: * type: object - * allOf: + * schema: * $ref: '#/definitions/TraineePost' * responses: * 200: * description: user data successfully updated + * schema: + * allOf: + * properties: + * status: + * example: Ok + * message: + * example: User data successfully Updated + * data: + * type: object + * allOf: + * - $ref: '#/definitions/TraineeResponse' * 403: * description: unauthorised access + * schema: + * $ref: '#/definitions/Unauthorized' */ .put(authMiddleWare('traineeModule', 'write'), validationHandler(validation.update), controller.update); /** @@ -193,11 +248,23 @@ traineeRouter.route('/') * in: path * required: true * type: string + * example: 5e4e6e93c095d84d34045a30 * responses: * 200: - * description: login + * description: Data deleted + * schema: + * allOf: + * properties: + * status: + * example: Ok + * message: + * example: User data successfully deleted + * data: + * example: 5e4e6e93c095d84d34045a30 * 403: * description: unauthorised access + * schema: + * $ref: '#/definitions/Unauthorized' */ traineeRouter.route('/:id') .delete(authMiddleWare('traineeModule', 'delete'), validationHandler(validation.delete), controller.delete); From 4cd210b50685fe17d65f748bbf21818542849547 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Fri, 21 Feb 2020 10:07:00 +0530 Subject: [PATCH 88/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20add=20APIs=20Compl?= =?UTF-8?q?etition?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40314 --- src/Controllers/trainee/routes.ts | 17 ++++++++--------- src/Controllers/user/validation.ts | 28 ---------------------------- 2 files changed, 8 insertions(+), 37 deletions(-) diff --git a/src/Controllers/trainee/routes.ts b/src/Controllers/trainee/routes.ts index 3ebde1a..51b4096 100644 --- a/src/Controllers/trainee/routes.ts +++ b/src/Controllers/trainee/routes.ts @@ -99,34 +99,33 @@ traineeRouter.route('/') * parameters: * - name: skip * description: elements to be skip - * in: path + * in: query * required: false * type: number * - name: limit * description: number of elements to be shown - * in: path + * in: query * required: false * type: number * - name: sortBy * description: elements to be sort by - * in: path + * in: query * required: false * type: string - * - name: searchBy - * description: elements to be skip - * in: path + * - name: search + * description: element to be search + * in: query * required: false * type: string * - name: order - * description: elements to be skip - * in: path + * description: order for sorting 1 or -1 + * in: query * required: false * type: number * responses: * 200: * description: Trainee List * schema: - * allOf: * properties: * status: * example: Ok diff --git a/src/Controllers/user/validation.ts b/src/Controllers/user/validation.ts index 47e8cd8..dbe3d1a 100644 --- a/src/Controllers/user/validation.ts +++ b/src/Controllers/user/validation.ts @@ -1,34 +1,6 @@ const validation = { get: { - skip: - { - required: false, - default: 0, - number: true, - regex: /[0-9]+/, - in: ['query'], - errorMessage: 'Skip is invalid', - custom: (reqMethod, req, res, next): void => { - if ( req[reqMethod].skip === undefined ) { - req[reqMethod].skip = '0'; - } - } - }, - limit: - { - required: false, - default: 10, - number: true, - regex: /[0-9]+/, - in: ['query'], - errorMessage: 'Limit is invalid', - custom: (reqMethod, req, res, next): void => { - if ( req[reqMethod].limit === undefined ) { - req[reqMethod].limit = '10'; - } - } - } }, login: { From da5cba8fb55e14e1b1bc1f1136efe31a9d40b882 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Fri, 21 Feb 2020 15:00:54 +0530 Subject: [PATCH 89/91] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20add=20APIs=20Compl?= =?UTF-8?q?etion?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ✅ Closes: 40314 --- src/Controllers/trainee/routes.ts | 4 ++-- src/Controllers/user/routes.ts | 14 +++++++++++--- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/Controllers/trainee/routes.ts b/src/Controllers/trainee/routes.ts index 51b4096..770817f 100644 --- a/src/Controllers/trainee/routes.ts +++ b/src/Controllers/trainee/routes.ts @@ -209,8 +209,8 @@ traineeRouter.route('/') * example: 5e4e6e93c095d84d34045a30 * dataToUpdate: * type: object - * schema: - * $ref: '#/definitions/TraineePost' + * allOf: + * - $ref: '#/definitions/TraineePost' * responses: * 200: * description: user data successfully updated diff --git a/src/Controllers/user/routes.ts b/src/Controllers/user/routes.ts index adc6c8f..cc65bbd 100644 --- a/src/Controllers/user/routes.ts +++ b/src/Controllers/user/routes.ts @@ -17,15 +17,14 @@ const userRouter: Router = Router(); * type: string * example: aryan@123 * Token: - * type: string + * type: object * properties: * status: * example: Ok * message: * example: Success * data: - * type:string - * example:eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InZpbmF5LmNoYXVkaGFyeUBzdWNjZXNzaXZlLnRlY2giLCJfaWQiOiI1ZTQ1NDA0Mzk4ZTg2ZDU3NmFkOTY0ZTYiLCJpYXQiOjE1ODIxOTY2MjUsImV4cCI6MTU4MjE5NzUyNX0.sLT3-1NmeyJtS0eDjhO3SUDiVSgaizfX0R7sqPgG040 + * example: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6InZpbmF5LmNoYXVkaGFyeUBzdWNjZXNzaXZlLnRlY2giLCJfaWQiOiI1ZTQ1NDA0Mzk4ZTg2ZDU3NmFkOTY0ZTYiLCJpYXQiOjE1ODIxOTY2MjUsImV4cCI6MTU4MjE5NzUyNX0.sLT3-1NmeyJtS0eDjhO3SUDiVSgaizfX0R7sqPgG040 */ /** @@ -71,6 +70,15 @@ userRouter.route('/me') * $ref: '#/definitions/Token' * 422: * description: invalid email or password + * schema: + * allOf: + * properties: + * status: + * example: "Bad Request" + * message: + * example: Password does not match + * err: + * example: Password is incorrect */ userRouter.route('/login') .post(validationHandler(validation.login), Controller.login); From f0c1f40be7943221d939f7a97b36149266b437af Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Fri, 21 Feb 2020 15:09:59 +0530 Subject: [PATCH 90/91] =?UTF-8?q?fix:=20=F0=9F=90=9B=20add=20changes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controllers/user/routes.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Controllers/user/routes.ts b/src/Controllers/user/routes.ts index cc65bbd..6b56e51 100644 --- a/src/Controllers/user/routes.ts +++ b/src/Controllers/user/routes.ts @@ -71,7 +71,7 @@ userRouter.route('/me') * 422: * description: invalid email or password * schema: - * allOf: + * oneOf: * properties: * status: * example: "Bad Request" From bb6bebda1b39c313928ffd09e8591c491dcfc301 Mon Sep 17 00:00:00 2001 From: Aryan Singhal Date: Tue, 25 Feb 2020 12:56:03 +0530 Subject: [PATCH 91/91] =?UTF-8?q?fix:=20=F0=9F=90=9B=20add=20changes?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/Controllers/trainee/routes.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Controllers/trainee/routes.ts b/src/Controllers/trainee/routes.ts index 770817f..6ce7d52 100644 --- a/src/Controllers/trainee/routes.ts +++ b/src/Controllers/trainee/routes.ts @@ -165,7 +165,7 @@ traineeRouter.route('/') * 200: * description: User created successfully * schema: - * allOf: + * oneOf: * properties: * status: * example: Ok @@ -203,7 +203,7 @@ traineeRouter.route('/') * required: true * type: object * schema: - * allOf: + * oneOf: * properties: * id: * example: 5e4e6e93c095d84d34045a30 @@ -215,7 +215,7 @@ traineeRouter.route('/') * 200: * description: user data successfully updated * schema: - * allOf: + * oneOf: * properties: * status: * example: Ok