Kiebot Learning Solutions

Blog

Your blog category

Building RESTful APIs with NestJS

Building RESTful APIs with NestJS User authentication is a critical aspect of any application, providing a layer of security to protect user data and sensitive information.Passport is the most popular node.js authentication library that is successfully used in many production applications. BLOGS Posted on July 16, 2024 By Jumana Jaleel (Application Developer) July 16, 2024 Introduction: NestJS is a progressive Node.js framework for building efficient, reliable, and scalable server-side applications. It embraces modern JavaScript/TypeScript features and design patterns while providing a robust architecture based on Angular-style dependency injection, modularization, and powerful testing capabilities. Building RESTful APIs with NestJS is straightforward and intuitive, thanks to its modular structure and extensive feature set. Setting up a Nestjs Project Before diving into building RESTful APIs with NestJS, ensure you have the following prerequisites installed: Node.js and npm (or yarn) installed on your system Basic knowledge of JavaScript/TypeScript Familiarity with RESTful API concepts Once you have those set up, you can use the Nestjs CLI to create a new project by running the following command: Install the NestJS CLI globally: npm install -g @nestjs/cli Create a new NestJS project: nest new sample-project This command will create a new directory called sample-project with the basic structure of a Nestjs application. Creating a RESTful API Endpoint Nestjs follows a modular architecture where each module represents a feature or a domain of your application. Let’s create a simple module for handling user-related functionality. Run the following command to generate a new module: $ nest generate module users Next, we’ll create a controller for handling HTTP requests related to users: $ nest generate controller users Open the generated users.controller.ts file and define a new endpoint for retrieving a list of users: Implementing Service Logic While the controller handles the incoming HTTP requests, the actual business logic should be encapsulated in a service. Let’s create a UsersService to handle the retrieval of user data: $ nest generate controller users Open the generated users.service.ts file and implement the logic for retrieving users: In this example, we define a simple array of users and a findAll method that returns all the users. The @Injectable decorator marks the class as a provider that can be injected into other classes. Update the UsersController to use the UsersService : By injecting the UsersService into the constructor of the UsersController , we can access its methods and retrieve the user data. Adding Database Integration In real-world applications, you’ll often need to interact with a database to persist and retrieve data. Nestjs provides excellent support for various databases and ORMs (Object-Relational Mappers). Let’s see how to integrate a PostgreSQL database into our NestJS application. First, install the necessary dependencies. In this example, we’ll use TypeORM and PostgreSQL:  $ npm install  @nestjs/typeorm typeorm pg Next, update the app.module.ts file to configure the database connection: In this example, we configure TypeORM to use PostgreSQL as the database. Adjust the host, port, username, password, and database fields according to your PostgreSQL configuration. The entities option tells TypeORM where to find entity classes, and synchronize ensures that the database schema is automatically updated based on the entity definitions. Create a new file called user.entity.ts to define the User entity: Update the UsersModule to include the TypeOrmModule and specify the User entity: Finally, update the UsersService to use the User repository provided by TypeORM: With these changes, the UsersService now retrieves user data from the PostgreSQL database using the UsersRepository. Adjust the database configuration and entity definitions as per your application’s requirements. Conclusion Building RESTful APIs with Nestjs is a straightforward and enjoyable process. Nestjs provides a structured and modular approach to building server-side applications, making it easy to create scalable and maintainable APIs.  By leveraging Nestjs’s powerful features, such as dependency injection, decorators, and database integration, you can quickly build robust APIs that serve as the backbone of your application. Remember to follow best practices, such as proper error handling, validation, and authentication, to ensure the security and reliability of your API.  Nestjs provides a wide range of plugins and libraries that can help you implement these features efficiently. Continue to explore the rich NestJS ecosystem and leverage community resources to enhance your development experience. Recent Posts Social 16 Jul 2024 Building RESTful APIs with NestJS 24 May 2024 NestJS Authentication Deep Dive 04 Apr 2024 Node.js Development to the Next Level Linkedin Instagram Facebook Youtube Recent Posts _kiebot Follow on Instagram

Building RESTful APIs with NestJS Read More »

NestJS Authentication Deep Dive

NestJS Authentication Deep Dive: Leveraging Passport, JWT, and bcrypt User authentication is a critical aspect of any application, providing a layer of security to protect user data and sensitive information.Passport is the most popular node.js authentication library that is successfully used in many production applications. BLOGS Posted on May 24, 2024 By Yunus (Application Developer) May 24, 2024 Introduction: User authentication is a critical aspect of any application, providing a layer of security to protect user data and sensitive information. Passport is the most popular node.js authentication library that is successfully used in many production applications. Nest applications can be integrated with the Passport library using the @nestjs/passport module. Passport uses the concept of strategies to authenticate requests. Strategies can range from verifying username and password credentials, delegated authentication using OAuth (for example, via Facebook or Twitter) etc. Please refer https://www.passportjs.org/packages/ to identify the strategies suitable for your application needs.  In this article, we are making use of two passport strategies, namely: passport-local: to authenticate a user based on username and password passport-jwt: to authenticate a user based on the JSON Web Token. After an initial successful local username and password authentication by the user, corresponding JWT can be generated. This JWT can then be used to get authenticated when accessing subsequent protected routes within the application. Pre-requisites In a real world Nest application, following setup would have been completed before implementing user authentication. We will however not be discussing them in detail. Install Nest CLI Create a new NestJs project using the Nest CLI that generates a base project structure with the initial core Nest files and supporting modules Install @nestjs/config package and import its ConfigModule and use it to read the environment variables configurations from the .env file Install the associated client API libraries for TypeORM integration with PostgreSQL database Create a ‘database’ module and into that import TypeOrmModule and configure it using the ConfigService by reading the PostgreSQL database environment variables Packages required Following is a list of packages that are to be installed or commands to be executed to meet the prerequisites and to get the authentication function implemented. Project Folder structure The folder structure of the described NestJS application is shown below. User Module The user module represents the user store within our Nest JS application.The User entity and its DTO are shown here. The UsersController has a user signup route /api/v1/users configured and it invokes the create() method of UsersService The utils method hashpassword() makes use of the bcrypt package. The findOneByUsername() method of the UsersService returns a full user object if the passed username matches, but otherwise returns a null object. We will soon observe that this method is invoked from an AuthService. Apart from these methods, there are other methods too like finding all users, updating the details of a specific user or removing a user from the user store etc, however they are not related to the topic of user authentication and hence not relevant in this discussion. Authentication requirements For this use case, we have following authentication requirements: A client application authenticates with a username and password via a login route. Once authenticated, the server will issue a JWT. We will create a protected route that is accessible only to requests that contain a valid JWT. The client application can send the JWT received from step-1 (after successful login), as a bearer token in the authorization header on subsequent requests to prove authentication – this would be required to access the protected route/s. In case the routes are protected globally across the application or protected at a module-level, we will need to skip JWT authentication checks on a few of the routes. For example, protect all API routes of the user module but only keep the user signup route open / public. Local authentication Local authentication refers to when the client application or end-user sends in username and password for login, to a login API route. A login route is set-up in the AppController of our Nest application as shown below. There is a guard named ‘LocalAuthGuard’ placed in front of the login route and so all login requests are first handled by this guard, before it hands over the processed result to the login() method. The @nestjs/passport module provides us with a built-in guard ‘AuthGuard’ that invokes the required Passport strategy. The string parameter to the AuthGuard informs which Passport strategy needs to be invoked (as it is possible that an application has configured more than one passport strategy at the same time). In this case, the LocalAuthGuard uses the string parameter ‘local’ and so invokes the passport-local strategy for the incoming username and password parameters of the login request. In general, there are two things to be provided when configuring any of the passport strategies: A set of options that are specific to that strategy. These strategy options are passed by calling the super() method A “verify callback”, which is implemented by a validate() method and defines some kind of interaction with the user store (either checking if the user exists, or checking if credentials are valid or fetching more information about the user). In all these cases, if validation succeeds it returns a user object or returns null if it fails.   In the LocalStrategy we simply call super() as we do not have any options to specify. Note! Instead of using default property names (username and password) for login, if for example you are using ’email’ instead of username, then this needs to be included in the options when calling super(), example: super({ usernameField: ’email’ }). In the validate() method, it uses the AuthService. The validateUser() method checks if a user exists with the passed-in username. This is done by calling the findOneByUsername() of the UsersService. If the user exists and the passed-in password matches with the actual password of the user, then it returns the user object containing the id and the name of the user (after stripping off the sensitive details such as

NestJS Authentication Deep Dive Read More »

Node.js Development to the Next Level

NestJS: Elevating Node.js Development to the Next Level Node.js has revolutionized server-side JavaScript development with its BLOGS Posted on April 4, 2024 Afara (Application Developer) April 4, 2024 Introduction: Node.js has revolutionized server-side JavaScript development with its asynchronous, event-driven architecture. However, as applications grow in complexity, developers seek more structure, maintainability, and scalability. This is where NestJS shines. NestJS builds upon the foundation of Node.js and provides a structured framework that simplifies development, enhances code maintainability, and promotes best practices. In this blog post, we’ll explore why NestJS is more than just Node.js, and how it elevates the development experience to the next level. Core Highlights: Architecture and Organization TypeScript Integration Dependency Injection and Inversion of Control (IoC) Decorators and Metadata Built-in Support for Features Scalability and Maintainability Community and Ecosystem 1. Architecture and Organization : Node.js allows flexibility in project structure, which can lead to inconsistency and confusion in larger projects. NestJS, on the other hand, introduces a modular and organized architecture inspired by Angular. It promotes the separation of concerns, making code easier to understand, maintain, and scale. 2. TypeScript Integration : While Node.js supports JavaScript, NestJS takes advantage of TypeScript, a superset of JavaScript that adds static typing and other advanced features. TypeScript brings benefits such as improved code quality, better IDE support, and enhanced developer productivity by catching errors at compile-time rather than runtime. 3. Dependency Injection and Inversion of Control (IoC) : NestJS embraces the principles of dependency injection and inversion of control, enabling loose coupling between components and promoting testability and reusability. With NestJS, dependencies are injected into components at runtime, allowing for easier mocking and testing of components in isolation. 4. Decorators and Metadata : Decorators and metadata, borrowed from TypeScript, play a crucial role in defining routes, middleware, providers, and other aspects of NestJS applications. Decorators provide a declarative and intuitive way to configure application features, reducing boilerplate code and making codebase more readable and maintainable. 5. Built-in Support for Features : NestJS comes with built-in support for essential features such as HTTP server, middleware, routing, validation, authentication, and more. This reduces the need for external dependencies and simplifies the development process, allowing developers to focus on building application logic rather than reinventing the wheel. We use only the built-in modules provided by NestJS. @Controller() and @Get(), @Post() decorators are used to define routes and HTTP methods directly within the controller class. @Body() decorator is used for request body parsing. NestJS handles dependency injection and module initialization internally, removing the need for additional external modules. 6. Scalability and Maintainability : By promoting modularity, TypeScript support, dependency injection, and other best practices, NestJS enables developers to build scalable and maintainable applications with ease. The structured architecture and built-in features facilitate code organization, refactoring, and collaboration, even as applications grow in complexity. 7. Community and Ecosystem : NestJS benefits from a vibrant and active community, with a growing ecosystem of plugins, libraries, and tools. The community contributes to the ongoing development and improvement of NestJS, providing support, resources, and contributions to help developers succeed with the framework. Conclusion: NestJS represents a significant evolution in Node.js development, offering a structured and opinionated framework that combines the power of Node.js with the benefits of TypeScript, dependency injection, and architectural best practices. With NestJS, developers can build scalable, maintainable, and feature-rich applications more efficiently than ever before. So, if you’re looking to take your Node.js development to the next level, consider embracing NestJS and experience the difference it can make in your projects. Recent Posts 16 Jul 2024 Building RESTful APIs with NestJS 24 May 2024 NestJS Authentication Deep Dive 04 Apr 2024 Node.js Development to the Next Level Social Linkedin Instagram Facebook Youtube Recent Posts _kiebot Follow on Instagram

Node.js Development to the Next Level Read More »

Mastering Agile Testing

Mastering Agile Testing: Key principles and practices for High – Quality software delivery Agile stands as a renowned project management framework in software development. Agile software testing is a methodology that facilitates rapid code testing for developers while enabling testers to promptly gather feedback from customers. In agile testing, various team members have distinct roles and responsibilities. BLOGS Posted on March 26, 2024 By Dijisha (QA Engineer) March 26, 2024 Mastering Agile Testing       Agile stands as a renowned project management framework in software development. Agile software testing is a methodology that facilitates rapid code testing for developers while enabling testers to promptly gather feedback from customers. In agile testing, various team members have distinct roles and responsibilities. Agile stands as a renowned project management framework in software development. Agile software testing is a methodology that facilitates continuous and rapid code testing for developers while enabling testers to promptly gather feedback from customers. In agile testing, various team members have distinct roles and responsibilities. In this article, I will provide an overview of Agile testing. What are the Main Principles of Agile Testing The Main Principles of Agile testing are:- Early and Frequent Testing :- Testing is performed early and often to identify and address issues as they arise, reducing the cost and efforts required for fixing defects Test-Driven Development(TDD) :- Tests are created before the code, helping define the expected behavior and ensuring that the code meets requirements. Whole Team Approach :- Agile testing encourages the entire team, including developers, testers, business analysts, and product owners, to take responsibility for quality. Frequent deliveries :- Agile teams deliver functional software frequently, often every two weeks. Customer Involvement :- Customers actively participate in the Agile development process, offering feedback during each iteration, which helps the team to make continuous improvements. Working Software :- The Agile team prioritizes quality software management in every iteration, This is more important than documentation or other deliverables. Flexible approach :- Agile development is known for its flexibility, allowing teams to modify requirements at any point during development. What are the Main Principles of Agile Testing The agile testing life cycle has five distinct phases, as shown in the image below Phase 1: Impact Assessment In this phase, we collect feedback from users and stakeholders to conduct an impact assessment, which will guide the direction for the next cycle Phase 2: Agile Testing Planning In this phase, developers, test engineers, stakeholders, customers, and end-users come together to jointly plan testing schedules, meetings, and deliverables Phase 3: Release Readiness The next phase is release readiness. Test engineers review features for readiness and determine if they are ready for deployment or require further development phase iterations Phase 4: Daily Scrums Daily scrums are the next phase in Agile testing. These morning meetings check testing progress and set daily goals and targets for test engineers. Phase 5: Test Agility Review The final phase in Agile is the test agility review, involving weekly stakeholder meetings to assess progress against goals. These reviews provide regular insights into the development process. What Are the Main Testing Activities in Agile? The main testing activities in Agile include:- Requirement analysis Testers collaborate with business analysts and product owners to grasp the requirements of the new feature Test Design Creating or updating the test cases, test scenarios, and data based on requirements Test Execution Testers run the test cases and report any identified bugs. Defect management Testers work with developers to address and resolve defects. Release management Testers assist in planning and executing the release of the new feature What Are the Most Important Skills for Agile Testers? Strong communication skills :- Effective communication with the team and understanding customer needs are essential for testers. Strong technical skills :- Strong technical skills, including code and technology stack comprehension, are vital for testers. Strong problem-solving skills :- Testers must excel at quick problem-solving and creative solution generation. Strong team player :- Testers require strong teamwork, adaptability, and the ability to work under pressure. How is Agile Testing done? In Agile testing, continuous code integration promotes collaboration and swift issue resolution. Test-driven development (TDD) entails writing unit tests before coding new features to establish requirements, and developers subsequently run these tests to validate functionality. Why is Agile Testing Important? Agile testing ensures customer needs are met through continuous feedback and improvement. It detects defects early and enables quick adjustments through frequent releases. Advantages of Agile Testing Agile testing provides continuous end-user feedback for improved software quality. Daily meetings help to identify issues more effectively Agile testing minimizes documentation requirements The primary benefit of Agile software testing is error reduction and improved software productivity. In Agile, work is divided into smaller parts, keeping developers focused and resulting in fewer inconsistencies and increased efficiency. Disadvantages of Agile Testing A significant drawback of Agile testing is project vulnerability if multiple team members depart Testing requires determination, and inconsistency can be a challenge for the testing team Agile testing can sometimes introduce new bugs due to frequent bug fixes, modifications, and releases After reviewing the earlier topics, it’s clear that Agile testing is a highly effective approach for today’s complex software. It offers flexibility, adaptability to changing requirements, and a strong focus on customer satisfaction. Collaboration among developers, test engineers, and customers ensures the delivery of high-quality software that meets user expectations. Agile testing also emphasizes early integration of testing into the Software Development Life Cycle, Highlighting the critical role of effective communication among teams in its success. Recent Posts 24 May 2024 NestJS Authentication Deep Dive 04 Apr 2024 Node.js Development to the Next Level 26 Mar 2024 Mastering Agile Testing Social Linkedin Instagram Facebook Youtube Recent Posts _kiebot Follow on Instagram

Mastering Agile Testing Read More »

Scroll to Top