Header image

TypeScript – How To Avoid “Any”?

26/09/2022

1.23k

  • The harmful effects of any
  • Avoiding any
TypeScript - How To Avoid "Any"?

How to avoid any?

In the previous blog – Typescript and “any” type, I introduced TypeScript and what exactly is any type.

In this blog, I’d like to show more about the harmful effects when using any and introduce some built-in types, features and customs types that you can use to avoid any.

The harmful effects of any

While TypeScript is a type checker, any type tells TypeScript to skip/disable type-checking. On the other hand, due to the nature of JavaScript, in some cases providing accurate types isn’t a simple task. In such situations, programmers are tempted to use any.

In most situations using or implicit any – a type that allows to store anything and skip type checkers, programmers can’t guarantee what type the value is stored and how it will be used. Furthermore, when the code is executed at runtime, errors may occur even though they were not warned before. For example:

let result; // Variable 'result' implicitly has an 'any' type.
result = 10.123; // Number is stored at 'result'

console.log(result.toFixed()); // `toFixed()` is a method of `number`

result.willExist(); // `willExist()` isn't a method of `number`, but no errors appear.

Because of that, the use of any is something that should be minimized as much as possible, to ensure the source code does not encounter any errors.

Avoiding any

Based on the basics of TypeScript and Everyday Types, in this blog, I’ll be sharing what I learned and used to write code without any.

Type aliases & Interfaces

A type alias is exactly a name for any type, you can actually use a type alias to give a name to any type at all, not just an object type. For example:

// Type alias
type Point = {
  x: number,
  y: number
};

type ID = number | string;

An interface declaration is another way to name an object type:

// Interface
interface IPoint {
  x: number,
  y: number
};

Differences between Type Aliases and Interfaces:

// Override
type Point = { // TypeError: Duplicate identifier 'Point'.
  a: string
};
interface IPoint {
  a: string
};

Union & Literal types

A union type is a type formed from two or more other types, representing values that may be any one of those types.

// Union types
let anyNumber: string | number;

// Usage
anyNumber = '123';
anyNumber = 123;
anyNumber = true; // TypeError: Type 'boolean' is not assignable to type 'string | number'.

In addition to the general types of string and number, you can refer to specific value of strings and numbers.
By combining literals into unions, you can express a much more useful concept. For example:

// Literal types
let direction: 'top' | 'left' | 'right' | 'bottom';

direction = 'top';
direction = 'top-right'; // TypeError: Type '"top-right"' is not assignable to type '"top" | "left" | "right" | "bottom"'

Type assertions

Sometimes you will have information about the type of a value that TypeScript can’t know about.

For example, if you’re using document.getElementById, TypeScript only knows that this will return some kind of HTMLElement, but you might know that your page will always have an HTMLCanvasElement with a given ID.

In this situation, you can use a type assertion to specify a more specific type:

// Type assertions
const myCanvas = document.getElementById('main-canvas') as HTMLCanvasElement;

Generics

// Example
const getRandomNumber = (items: number[]): number => {
  let randomIndex = Math.floor(Math.random() * items.length);
  return items[randomIndex];
};
const getRandomString = (items: string[]): string => {
  let randomIndex = Math.floor(Math.random() * items.length);
  return items[randomIndex];
};

// Generics function
const getRandomGeneric = <T>(items: T[]): T => {
  let randomIndex = Math.floor(Math.random() * items.length);
  return items[randomIndex];
};

// Usage
const teams: string[] = ['frontend', 'ios', 'android'];
const numbers: number[] = [1, 2, 3, 4, 5, 6, 7, 9, 10];

const randomResult1 = getRandomGeneric<string>(teams);
const randomResult2 = getRandomGeneric<number>(numbers);

In the example above, the getRandomGeneric is the generic identity function that worked over a range of types.

The type of generic functions is just like those of non-generic functions, with the type parameters listed first, similarly to function declarations:

const identity = <Type>(param: Type): Type => {
  return param;
};

When calling identity a function, you now will also need to specify the type of param that the function will use.

The detail above just Generic identity functions, you can read more generics Generic link

Unknown

unknown is what should be used when you don’t know a proper type of object. Unlike any, it doesn’t let you do any operations on a value until you know its type (skip/disable type-checker).

When you unknow something, you need to check before executing. For example:

const invokeAnything = (callback: unknown): void => {
  if (typeof callback === 'function') {
    callback();
  }
  if (typeof callback === 'number') {
    console.log(callback);
  }
  if (typeof callback === 'string') {
    console.log(callback.toUpperCase());
  }
};

// Usage
invokeAnything('typescript'); // Result: TYPESCRIPT

Record for basic object

Probably, nearly every JavaScript developer at some time has used an object as a map-like collection. However, with strict types, it may not be that obvious how to type this. So, you may use interface, but this way you can’t add anything to the object. Then, you need to think about using Record.

The definition:

type Record<K extends keyof any, T> = {
  [P in K]: T;
};

And the usage:

// Usage
const dict: Record<string, number> = {};
dict.a = 1;
dict.b = 'a'; // TypeError: "a" is not assignable to type number

let obj: Record<string, number>;
obj = {
  a: 1,
  b: 2
};

As you can see, it means that the developer can enter any key, but the value has to be of a specific type.

Conclusion

The TypeScript compiler is so powerful. There are so many things we can do with it.

any type can be avoided with more advanced technics such as interface, type intersection, and the use of generics, etc.

Hope you like it! Enjoy TypeScript and make the code without any!

Author: Anh Nguyen

Related Blog

prd-thumb-draft-product

Software Development

+0

    TypeScript And “Any” Type

    TypeScript is a strongly typed programming language that builds on JavaScript, giving you a better ability to detect errors and describe your code. But sometimes you don't know the exact type of value that you're using because it comes from user input or a third-party API. In this case, you want to skip the type checking and allow the value to pass through the compile check. The TypeScript any type is the perfect solution for you because if you use it, the TypeScript compiler will not complain about the type issue. This blog will help you understand the any type in TypeScript, but before doing that, let's begin with some basic concepts! What is TypeScript? TypeScript checks a program for errors before execution and does so based on the kinds of values; it’s a static type checker. Superset of JavaScript TypeScript is a language that is a superset of JavaScript: JS syntax is, therefore, legal TS. However, TypeScript is a typed superset that adds rules about how different kinds of values can be used. Runtime Behavior TypeScript is also a programming language that preserves JavaScript's runtime behavior. This means that if you move code from JavaScript to TypeScript, it is guaranteed to run the same way, even if TypeScript thinks the code has type errors. Erased Types Roughly speaking, once TypeScript’s compiler is done with checking your code, it erases the types to produce the resulting compiled code. This means that once your code is compiled, the resulting plain JS code has no type information. An easy way of understanding TypeScript A languageA superset of JavaScriptPreserver the runtime behavior of JavaScriptType checker layer JavaScript + Types = TypeScript Basic typing Type annotations TypeScript uses type annotations to explicitly specify types for identifiers such as variables, functions, objects, etc. // Syntax : type Once an identifier is annotated with a type, it can be used as that type only. If the identifier is used as a different type, the TypeScript compiler will issue an error. let counter: number; counter = 1; counter = 'Hello'; // Error: Type '"Hello"' is not assignable to type 'number'. The following shows other examples of type annotations: let name: string = 'John'; let age: number = 25; let active: boolean = true; // Array let names: string[] = ['John', 'Jane', 'Peter', 'David', 'Mary']; // Object let person: { name: string; age: number }; person = { name: 'John', age: 25 }; // Valid // Function let sayHello : (name: string) => string; sayHello = (name: string) => { return `Hello ${name}`; }; Type inference Type inference describes where and how TypeScript infers types when you don’t explicitly annotate them. For example: // Annotations let counter: number; // Inference: TypeScript will infer the type the `counter` to be `number` let counter = 1; Likewise, when you assign a function parameter a value, TypeScript infers the type of the parameter to the type of the default value. For example: // TypeScript infers type of the `max` parameter to be `number` const setCounter = (max = 100) => { // ... } Similarly, TypeScript infers the return type to the type of the return value: const increment = (counter: number) => { return counter++; } // It is the same as: const increment = (counter: number) : number => { return counter++; } The following shows other examples of type inference: const items = [0, 1, null, 'Hi']; // (number | string)[] const mixArr = [new Date(), new RegExp('\d+')]; // (RegExp | Date)[] const increase = (counter: number, max = 100) => { return counter++; }; // (counter: number, max?: number) => number Contextual typing TypeScript uses the locations of variables to infer their types. This mechanism is known as contextual typing. For example: document.addEventListener('click', (event) => { console.log(event.button); // Valid }); In this example, TypeScript knows that the event the parameter is an instance of MouseEvent because of the click event. However, when you change the click event to the scroll the event, TypeScript will issue an error: document.addEventListener('scroll', (event) => { console.log(event.button); // Compile error }); // Property 'button' does not exist on type 'Event'. TypeScript knows that the event in this case, is an instance of UIEvent, not a MouseEvent. And UIEvent does not have the button property, therefore, TypeScript throws an error. Other examples of contextual typing // Array members const names = ['John', 'Jane', 'Peter', 'David', 'Mary']; // string[] names.map(name => name.toUpperCase()); // (name: string) => string // Type assertions const myCanvas = document.getElementById('main-canvas') as HTMLCanvasElement; Type inference vs Type annotations Type inferenceType annotationsTypeScript guesses the typeYou explicitly tell TypeScript the type What exactly is TypeScript any? When you don’t explicitly annotate and TypeScript can't infer exactly the type, that means you declare a variable without specifying a type, TypeScript assumes that you use the any type. This practice is called implicit typing. For example: let result; // Variable 'result' implicitly has an 'any' type. So, what exactly is any? TypeScript any is a particular type that you can use whenever you don't want a particular value to cause type-checking errors. That means the TypeScript compiler doesn't complain or issue any errors. When a value is of type any, you can access any properties of it, call it like a function, assign it to (or from) a value of any type, or pretty much anything else that’s syntactically legal: let obj: any = { x: 0 }; // None of the following lines of code will throw compiler errors. // Using `any` disables all further type checking, and it is assumed // you know the environment better than TypeScript. obj.foo(); obj(); obj.bar = 100; obj = 'hello'; const n: number = obj; Looking back at an easier-to-understand any: A special type.Skip/Disable type-checking.TypeScript doesn't complain or issue any errors.Default implicit typing is any. Note that to disable implicit typing to the any type, you change the noImplicitAny option in the tsconfig.json file to true. Why does TypeScript provide any type? As described above, while TypeScript is a type checker, any type tells TypeScript to skip/disable type-checking. Whether TypeScript has made a mistake here and why it provides any type? In fact, sometimes the developer can't determine the type of value or can't determine the return value from the 3rd party. In most cases they use any type or implicit typing as any. So they seem to think that TypeScript provides any to do those things. So, is that the root reason that TypeScript provides any? Actually, I think there is a more compelling reason for TypeScript providing any that the any type provides you with a way to work with the existing JavaScript codebase. It allows you to gradually opt-in and opt out of type checking during compilation. Therefore, you can use the any type for migrating a JavaScript project over to TypeScript. Conclusion TypeScript is a Type checker layer. The TypeScript any type allows you to store a value of any type. It instructs the compiler to skip type-checking. Use the any type to store a value when you migrate a JavaScript project over to a TypeScript project. In the next blog, I will show you more about the harmful effects of any and how to avoid them. Hope you like it! See you in the next blog! Reference TypeScript handbookTypeScript tutorial Author: Anh Nguyen

    07/09/2022

    825

    Software Development

    +0

      TypeScript And “Any” Type

      07/09/2022

      825

      Knowledge

      Software Development

      +0

        Mastering AWS Lambda: An Introduction to Serverless Computing

        Imagine this: you have a system that sends emails to users to notify them about certain events at specific times of the day or week. During peak hours, the system demands a lot of resources, but it barely uses any for the rest of the time. If you were to dedicate a server just for this task, managing resources efficiently and maintaining the system would be incredibly complex. This is where AWS Lambda comes in as a solution to these challenges. Its ability to automatically scale, eliminate server management, and, most importantly, charge you only for the resources you use simplifies everything. Hello everyone! I’m Đang Đo Quang Bao, a Software Engineer at SupremeTech. Today, I’m excited to introduce the series' first episode, “Mastering AWS Lambda: An Introduction to Serverless Computing.” In this episode, we’ll explore: The definition of AWS Lambda and how it works.The benefits of serverless computing.Real-world use cases. Let’s dive in! What is AWS Lambda? AWS Lambda is a serverless computing service that Amazon Web Services (AWS) provides. It executes your code in response to specific triggers and scales automatically, charging you only for the compute time you use. How Does AWS Lambda Work? AWS Lambda operates on an event-driven model, reacting to specific actions or events. In simple terms, it executes code in response to particular triggers. Let’s explore this model further to gain a more comprehensive understanding. The above is a simplified workflow for sending emails to many users simultaneously, designed to give you a general understanding of how AWS Lambda works. The workflow includes: Amazon EventBridge:Role: EventBridge acts as the starting point of the workflow. It triggers the first AWS Lambda function at a specific time each day based on a cron schedule.How It Works:Configured to run automatically at 00:00 UTC or any desired time.Ensures the workflow begins consistently without manual intervention.Amazon DynamoDB:Role: DynamoDB is the primary database for user information. It holds the email addresses and other relevant metadata for all registered users.How It Works:The first Lambda function queries DynamoDB to fetch the list of users who need to receive emails.AWS Lambda (1st Function):Role: This Lambda function prepares the user data for email sending by fetching it from DynamoDB, batching it, and sending it to Amazon SQS.How It Works:Triggered by EventBridge at the scheduled time.Retrieves user data from DynamoDB in a single query or multiple paginated queries.Split the data into smaller batches (e.g., 100 users per batch) for efficient processing.Pushes each batch as a separate message into Amazon SQS.Amazon SQS (Simple Queue Service).Role: SQS serves as a message queue, temporarily storing user batches and decoupling the data preparation process from email-sending.How It Works:Each message in SQS represents one batch of users (e.g., 100 users).Messages are stored reliably and are processed independently by the second Lambda function.AWS Lambda (2nd Function):Role: This Lambda function processes each user batch from SQS and sends emails to the users in that batch.How It Works:Triggered by SQS for every new message in the queue.Reads the batch data (e.g., 100 users) from the message.Sends individual emails to each user in the batch using Amazon SES.Amazon SES (Simple Email Service).Role: SES handles the actual email delivery, reliably ensuring messages reach users’ inboxes.How It Works:Receives the email content (recipient address, subject, body) from the second Lambda function.Delivers emails to the specified users.Provides feedback on delivery status, including successful deliveries, bounces, and complaints. As you can see, AWS Lambda is triggered by external events or actions (AWS EventBridge schedule) and only "lives" for the duration of its execution. >>> Maybe you are interested: The Rise of Serverless CMS Solutions Benefits of AWS Lambda No Server Management:Eliminate the need to provision, configure, and maintain servers. AWS handles the underlying infrastructure, allowing developers to focus on writing code.Cost Efficiency:Pay only for the compute time used (measured in milliseconds). There are no charges when the function isn’t running.Scalability:AWS Lambda automatically scales horizontally to handle thousands of requests per second.Integration with AWS Services:Lambda integrates seamlessly with services like S3, DynamoDB, and SQS, enabling event-driven workflows.Improved Time-to-Market:Developers can deploy and iterate applications quickly without worrying about managing infrastructure. Real-World Use Cases for AWS Lambda AWS Lambda is versatile and can be applied in various scenarios. Here are some of the most common and impactful use cases: Real-Time File ProcessingExample: Automatically resizing images uploaded to an Amazon S3 bucket.How It Works:An upload to S3 triggered a Lambda function.The function processes the file (e.g., resizing or compressing an image).The processed file is stored back in S3 or another storage system.Why It’s Useful:Eliminates the need for a dedicated server to process files.Automatically scales based on the number of uploads.Building RESTful APIsExample: Creating a scalable backend for a web or mobile application.How It Works:Amazon API Gateway triggers AWS Lambda in response to HTTP requests.Lambda handles the request, performs necessary logic (e.g., CRUD operations), and returns a response.Why It’s Useful:Enables fully serverless APIs.Simplifies backend management and scaling.IoT ApplicationsExample: Processing data from IoT devices.How It Works:IoT devices publish data to AWS IoT Core, which triggers Lambda.Lambda processes the data (e.g., analyzing sensor readings) and stores results in DynamoDB or ElasticSearch.Why It’s Useful:Handles bursts of incoming data without requiring a dedicated server.Integrates seamlessly with other AWS IoT services.Real-Time Streaming and AnalyticsExample: Analyzing streaming data for fraud detection or stock market trends.How It Works:Events from Amazon Kinesis or Kafka trigger AWS Lambda.Lambda processes each data stream in real time and outputs results to an analytics service like ElasticSearch.Why It’s Useful:Allows real-time data insights without managing complex infrastructure.Scheduled TasksExample: Running daily tasks/reports or cleaning up expired data.How It Works:Amazon EventBridge triggers Lambda at scheduled intervals (e.g., midnight daily).Lambda performs tasks like querying a database, generating reports, or deleting old records.Why It’s Useful:Replaces traditional cron jobs with a scalable, serverless solution. Conclusion AWS Lambda is a powerful service that enables developers to build highly scalable, event-driven applications without managing infrastructure. Lambda simplifies workflows and accelerates time-to-market by automating tasks and seamlessly integrating with other AWS services like EventBridge, DynamoDB, SQS, and SEStime to market. We’ve explored the fundamentals of AWS Lambda, including its definition, how it works, its benefits, and its application in real-world use cases. It offers an optimized and cost-effective solution for many scenarios, making it a vital tool in modern development. At SupremeTech, we’re committed to harnessing innovative technologies to deliver impactful solutions. This is just the beginning of our journey with AWS Lambda. In upcoming episodes, we’ll explore implementing AWS Lambda in different programming languages and uncover best practices for building efficient serverless applications. Stay tuned, and let’s continue mastering AWS Lambda together!

        25/12/2024

        41

        Bao Dang D. Q.

        Knowledge

        +1

        • Software Development

        Mastering AWS Lambda: An Introduction to Serverless Computing

        25/12/2024

        41

        Bao Dang D. Q.

        Automate your git flow with git hooks

        Knowledge

        +0

          Automate Your Git Workflow with Git Hooks for Efficiency

          Have you ever wondered how you can make your Git workflow smarter and more efficient? What if repetitive tasks like validating commit messages, enforcing branch naming conventions, or preventing sensitive data leaks could happen automatically? Enter Git Hooks—a powerful feature in Git that enables automation at every step of your development process. If you’ve worked with webhooks, the concept of Git Hooks might already feel familiar. Like API events trigger webhooks, Git Hooks are scripts triggered by Git actions such as committing, pushing, or merging. These hooks allow developers to automate tasks, enforce standards, and improve the overall quality of their Git workflows. By integrating Git Hooks into your project, you can gain numerous benefits, including clearer commit histories, fewer human errors, and smoother team collaboration. Developers can also define custom rules tailored to their Git flow, ensuring consistency and boosting productivity. In this SupremeTech blog, I, Đang Đo Quang Bao, will introduce you to Git Hooks, explain how they work, and guide you through implementing them to transform your Git workflow. Let’s dive in! What Are Git Hooks? Git Hooks are customizable scripts that automatically execute when specific events occur in a Git repository. These events might include committing code, pushing changes, or merging branches. By leveraging Git Hooks, you can tailor Git's behavior to your project's requirements, automate repetitive tasks, and reduce the likelihood of human errors. Imagine validating commit messages, running tests before a push, or preventing large file uploads—all without manual intervention. Git Hooks makes this possible, enabling developers to integrate useful automation directly into their workflows. Type of Git Hooks Git Hooks come in two main categories, each serving distinct purposes: Client-Side Hooks These hooks run on the user’s local machine and are triggered by actions like committing or pushing changes. They are perfect for automating tasks like linting, testing, or enforcing commit message standards. Examples:pre-commit: Runs before a commit is finalized.pre-push: Executes before pushing changes to a remote repository.post-merge: Triggers after merging branches. Server-Side Hooks These hooks operate on the server hosting the repository and are used to enforce project-wide policies. They are ideal for ensuring consistent workflows across teams by validating changes before they’re accepted into the central repository. Examples: pre-receive: Runs before changes are accepted by the remote repository.update: Executes when a branch or tag is updated on the server. My Journey to Git Hooks When I was working on personal projects, Git management was fairly straightforward. There were no complex workflows, and mistakes were easy to spot and fix. However, everything changed when I joined SupremeTech and started collaborating on larger projects. Adhering to established Git flows across a team introduced new challenges. Minor missteps—like inconsistent commit messages, improper branch naming, accidental force pushes, or forgetting to run unit tests—quickly led to inefficiencies and avoidable errors. That’s when I discovered the power of Git Hooks. By combining client-side Git Hooks with tools like Husky, ESLint, Jest, and commitlint, I could automate and streamline our Git processes. Some of the tasks I automated include: Enforcing consistent commit message formats.Validating branch naming conventions.Automating testing and linting.Preventing accidental force pushes and large file uploads.Monitoring and blocking sensitive data in commits. This level of automation was a game-changer. It improved productivity, reduced human errors, and allowed developers to focus on their core tasks while Git Hooks quietly enforced the rules in the background. It transformed Git from a version control tool into a seamless system for maintaining best practices. Getting Started with Git Hooks Setting up Git Hooks manually can be dull, especially in team environments where consistency is critical. Tools like Husky simplify the process, allowing you to manage Git Hooks and integrate them into your workflows easily. By leveraging Husky, you can unlock the full potential of Git Hooks with minimal setup effort. I’ll use Bun as the JavaScript runtime and package manager in this example. If you’re using npm or yarn, replace Bun-specific commands with their equivalents. Setup Steps 1. Initialize Git: Start by initializing a Git repository if one doesn’t already exist git init 2. Install Husky: Use Bun to add Husky as a development dependency bun add -D husky 3. Enable Husky Hooks: Initialize Husky to set up Git Hooks for your project bunx husky init 4. Verify the Setup: At this point, a folder named .husky will be created, which already includes a sample of pre-commit hook. With this, the setup for Git Hooks is complete. Now, let’s customize it to optimize some simple processes. Examples of Git Hook Automation Git Hooks empowers you to automate tedious yet essential tasks and enforce team-wide best practices. Below are four practical examples of how you can leverage Git Hooks to improve your workflow: Commit Message Validation Ensuring consistent and clear commit messages improves collaboration and makes Git history easier to understand. For example, enforce the following format: pbi-203 - refactor - [description…] [task-name] - [scope] - [changes] Setup: Install Commitlint: bun add -D husky @commitlint/{config-conventional,cli} Configure rules in commitlint.config.cjs: module.exports = {     rules: {         'task-name-format': [2, 'always', /^pbi-\d+ -/],         'scope-type-format': [2, 'always', /-\s(refactor|fix|feat|docs|test|chore|style)\s-\s[[^\]]+\]$/]     },     plugins: [         {             rules: {                 'task-name-format': ({ raw }) => {                     const regex = /^pbi-\d+ -/;                     return [regex.test(raw),                         `❌ Commit message must start with "pbi-<number> -". Example: "pbi-1234 - refactor - [optimize function]"`                     ];                 },                 'scope-type-format': ({ raw}) => {                     const regex = /-\s(refactor|fix|feat|docs|test|chore|style)\s-\s[[^\]]+\]$/;                     return [regex.test(raw),                         `❌ Commit message must include a valid scope and description. Example: "pbi-1234 - refactor - [optimize function]".                         \nValid scopes: refactor, fix, feat, docs, test, chore, style`                     ];                 }             }         }     ] } Add Commitlint to the commit-msg hook: echo "bunx commitlint --edit \$1" >> .husky/commit-msg With this, we have completed the commit message validation setup. Now, let’s test it to see how it works. Now, developers will be forced to follow this committing rule, which increases the readability of the Git History. Automate Branch Naming Conventions Enforce branch names like feature/pbi-199/add-validation. First, we will create a script in the project directory named scripts/check-branch-name.sh. #!/bin/bash # Define allowed branch naming pattern branch_pattern="^(feature|bugfix|hotfix|release)/pbi-[0-9]+/[a-zA-Z0-9._-]+$" # Get the current branch name current_branch=$(git symbolic-ref --short HEAD) # Check if the branch name matches the pattern if [[ ! "$current_branch" =~ $branch_pattern ]]; then   echo "❌ Branch name '$current_branch' is invalid!"   echo "✅ Branch names must follow this pattern:"   echo "   - feature/pbi-<number>/<description>"   echo "   - bugfix/pbi-<number>/<description>"   echo "   - hotfix/pbi-<number>/<description>"   echo "   - release/pbi-<number>/<description>"   exit 1 fi echo "✅ Branch name '$current_branch' is valid." Add the above script execution command into the pre-push hook. echo "bash ./scripts/check-branch-name.sh" >> .husky/pre-push Grant execute permissions to the check-branch-name.sh file. chmod +x ./scripts/check-branch-name.sh Let’s test the result by pushing our code to the server. Invalid case: git checkout main git push Output: ❌ Branch name 'main' is invalid! ✅ Branch names must follow this pattern:   - feature/pbi-<number>/<description>   - bugfix/pbi-<number>/<description>   - hotfix/pbi-<number>/<description>   - release/pbi-<number>/<description> husky - pre-push script failed (code 1) Valid case: git checkout -b feature/pbi-100/add-new-feature git push Output: ✅ Branch name 'feature/pbi-100/add-new-feature' is valid. Prevent Accidental Force Pushes Force pushes can overwrite shared branch history, causing significant problems in collaborative projects. We will implement validation for the prior pre-push hook to prevent accidental force pushes to critical branches like main or develop. Create a script named scripts/prevent-force-push.sh. #!/bin/bash # Define the protected branches protected_branches=("main" "develop") # Get the current branch name current_branch=$(git symbolic-ref --short HEAD) # Check if the current branch is in the list of protected branches if [[ " ${protected_branches[@]} " =~ " ${current_branch} " ]]; then # Check if the push is a force push for arg in "$@"; do   if [[ "$arg" == "--force" || "$arg" == "-f" ]]; then     echo "❌ Force pushing to the protected branch '${current_branch}' is not allowed!"     exit 1   fi done fi echo "✅ Push to '${current_branch}' is valid." Add the above script execution command into the pre-push hook. echo "bash ./scripts/prevent-force-push.sh" >> .husky/pre-push Grant execute permissions to the check-branch-name.sh file. chmod +x ./scripts/prevent-force-push.sh Result: Invalid case: git checkout main git push -f Output: ❌ Force pushing to the protected branch 'main' is not allowed! husky - pre-push script failed (code 1) Valid case: git checkout main git push Output: ✅ Push is valid. Monitor for Secrets in Commits Developers sometimes unexpectedly include sensitive data in commits. We will set up a pre-commit hook to scan files for sensitive patterns before committing to prevent accidental commits containing sensitive information (such as API keys, passwords, or other secrets). Create a script named scripts/monitor-secrets-with-values.sh. #!/bin/bash # Define sensitive value patterns patterns=( # Base64-encoded strings "([A-Za-z0-9+/]{40,})={0,2}" # PEM-style private keys "-----BEGIN RSA PRIVATE KEY-----" "-----BEGIN OPENSSH PRIVATE KEY-----" "-----BEGIN PRIVATE KEY-----" # AWS Access Key ID "AKIA[0-9A-Z]{16}" # AWS Secret Key "[a-zA-Z0-9/+=]{40}" # Email addresses (optional) "[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}" # Others (e.g., passwords, tokens) ) # Scan staged files for sensitive patterns echo "🔍 Scanning staged files for sensitive values..." # Get the list of staged files staged_files=$(git diff --cached --name-only) # Initialize a flag to track if any sensitive data is found found_sensitive_data=false # Loop through each file and pattern for file in $staged_files; do # Skip binary files if [[ $(file --mime-type -b "$file") == "application/octet-stream" ]]; then   continue fi # Scan each pattern using grep -E (extended regex) for pattern in "${patterns[@]}"; do   if grep -E -- "$pattern" "$file"; then     echo "❌ Sensitive value detected in file '$file': Pattern '$pattern'"     found_sensitive_data=true     break   fi done done # If sensitive data is found, prevent the commit if $found_sensitive_data; then echo "❌ Commit aborted. Please remove sensitive values before committing." exit 1 fi echo "✅ No sensitive values detected. Proceeding with committing." Add the above script execution command into the pre-commit hook. echo "bash ./scripts/monitor-secrets-with-values.sh" >> .husky/pre-commit Grant execute permissions to the monitor-secrets-with-values.sh file. chmod +x ./scripts/monitor-secrets-with-values.sh Result: Invalid case: git add private git commit -m “pbi-002 - chore - add unexpected private file” Result: 🔍 Scanning staged files for sensitive values... -----BEGIN OPENSSH PRIVATE KEY----- ❌ Sensitive value detected in file 'private': Pattern '-----BEGIN OPENSSH PRIVATE KEY-----' ❌ Commit aborted. Please remove sensitive values before committing. husky - pre-commit script failed (code 1) Valid case: git reset private git commit -m “pbi-002 - chore - remove unexpected private file” Result: 🔍 Scanning staged files for sensitive values... ✅ No sensitive values detected. Proceeding with commit. [main c575028] pbi-002 - chore - remove unexpected private file 4 files changed, 5 insertions(+) create mode 100644 .env.example create mode 100644 .husky/commit-msg create mode 100644 .husky/pre-commit create mode 100644 .husky/pre-push Conclusion "Humans make mistakes" in software development; even minor errors can disrupt workflows or create inefficiencies. That’s where Git Hooks come in. By automating essential checks and enforcing best practices, Git Hooks reduces the chances of errors slipping through and ensures a smoother, more consistent workflow. Tools like Husky make it easier to set up Git Hooks, allowing developers to focus on writing code instead of worrying about process compliance. Whether it’s validating commit messages, enforcing branch naming conventions, or preventing sensitive data from being committed, Git Hooks acts as a safety net that ensures quality at every step. If you want to optimize your Git workflow, now is the time to start integrating Git Hooks. With the proper setup, you can make your development process reliable but also effortless and efficient. Let automation handle the rules so your team can focus on building great software.

          24/12/2024

          46

          Bao Dang D. Q.

          Knowledge

          +0

            Automate Your Git Workflow with Git Hooks for Efficiency

            24/12/2024

            46

            Bao Dang D. Q.

            Knowledge

            Software Development

            +0

               Exploring API Performance Testing with Postman

              Hello, tech enthusiasts and creative developers! I’m Vu, the author of SupremeTech’s performance testing series. In the article “The Ultimate Guide to JMeter Performance Testing Tool,” we explored JMeter's strengths and critical role in performance testing. Today, I’m introducing an exciting and straightforward way to do API performance testing using Postman. What is Postman? Postman is a robust API (Application Programming Interface) platform that empowers developers to quickly design, test, document, and interact with APIs. It is a widely used tool for testing APIs, which is valuable in software development, primarily web or mobile app development. Why Use Postman for API Testing? Postman is favored by software developers, testers, and API specialists because of its many advantages: User-Friendly Interface: Postman’s intuitive design makes it easy to use.Supports Diverse HTTP Methods: It handles requests such as GET, POST, PUT, DELETE, PATCH, OPTIONS, and more.Flexible Configuration: Easily manage API request headers, parameters, and body settings.Test Automation with Scripts: Write JavaScript code within the Tests tab to automate API response validation.Integration with CI/CD: Postman's CLI tool, Newman, seamlessly integrates with CI/CD pipelines, enabling automated API testing in development workflows.API Documentation and Sharing: Create and share API documentation with team members or clients effortlessly. Performance API Testing on Postman As of mid-2024, Postman introduced a new feature allowing users to perform API performance testing quickly and conveniently. With just a few simple steps, you can evaluate your API’s performance under high load and ensure its strength. Step 1: Select the Collection for Performance Testing Open Postman and navigate to the Collections tab on the left sidebar.Choose the Collection or Folder you want to test. Step 2: Launch the Collection Runner After selecting your desired Collection or Folder, click Run Collection to open the Collection Runner window.In the Runner, select the APIs you want to include in the performance test.Switch to the Performance tab and choose a simulation method:Fixed: Simulates a fixed number of users.Ramp Up: Starts with a few users and gradually increases.Spike: Introduces a sudden surge in traffic followed by a reduction.Peak: Increases traffic to a high level and sustains it for a period. Step 3: Adjust Virtual Users and Test Duration Configure the Virtual Users and Test Duration settings to simulate the desired load.Start with smaller values, then gradually increase them to gain a clear understanding of your API's performance under varying conditions. Step 4: Run the Test Click Run to start the performance test.During the test, Postman will send API requests and provide real-time data on:Response Time: The API's duration to respond to a request.Error Rate: The percentage of failed requests.Throughput: The number of API requests the system can handle per second. Step 5: Analyze the Report Once the test is complete, Postman generates a detailed report, including: Response Time: Tracks the duration it takes for APIs to process requests.Error Rate: Highlights any issues encountered during testing.Throughput: Measures the system's capacity to process requests under load. Use these metrics to evaluate whether your API performs efficiently under heavy traffic. These insights will guide you in optimizing your API for better performance. Leverage Customization for Realistic User Simulation Postman allows you to customize request data for each virtual user. You can upload a CSV or JSON file with unique datasets if you want different data for each user. This feature enables a more accurate simulation of real-world user behavior. After each test run, Postman provides an easy-to-understand report highlighting the areas for improvement. You can track performance changes and compare test results to identify weaknesses and refine your API. Test and Optimize Your API with Postman With Postman’s new performance testing feature, API optimization has never been easier. It helps you quickly identify and address potential issues to ensure your system is always ready to handle user demands effectively and reliably.   For more details and step-by-step guidance, check out the following resources on the Postman website:   OverviewRun a performance testView performance test metricsDebug performance test errorsInject data into virtual users Start your API performance optimization journey with Postman and prepare your system to meet every demand seamlessly. >>> Explore more articles about performance testing: SupremeTech’s Expertise in the Process of Performance Testing

              23/12/2024

              31

              Vu Nguyen Q.

              Knowledge

              +1

              • Software Development

               Exploring API Performance Testing with Postman

              23/12/2024

              31

              Vu Nguyen Q.

              Customize software background

              Want to customize a software for your business?

              Meet with us! Schedule a meeting with us!