NestJs Exclude Field That is Null: A Comprehensive Guide
Image by Maribell - hkhazo.biz.id

NestJs Exclude Field That is Null: A Comprehensive Guide

Posted on

Are you tired of dealing with null values in your NestJs API responses? Do you want to provide a better user experience by excluding fields that have no value? Look no further! In this article, we’ll dive into the world of NestJs and explore the best practices for excluding fields that are null.

Why Exclude Null Fields?

Before we dive into the implementation, let’s talk about why excluding null fields is important. When working with APIs, it’s common to encounter null values in the response. These null values can lead to confusion for the consumer of the API, especially if they’re not expecting them. By excluding null fields, you can provide a cleaner and more concise response that’s easier to work with.

Benefits of Excluding Null Fields

  • Improved User Experience: By excluding null fields, you can provide a better user experience by reducing the amount of unnecessary data in the response.
  • Faster Response Times: Excluding null fields can reduce the size of the response, leading to faster response times and improved performance.
  • Easier Data Processing: Excluding null fields can make it easier for consumers to process the data, as they don’t have to worry about handling null values.

Using the `@Expose()` Decorator

One way to exclude null fields in NestJs is by using the `@Expose()` decorator. This decorator is part of the `class-transformer` package, which is a popular package for working with classes and objects in NestJs.


import { Expose } from 'class-transformer';

export class User {
  @Expose()
  id: number;

  @Expose()
  name: string;

  @Expose()
  email: string;

  // This field will be excluded if it's null
  @Expose({ toClassOnly: true })
  address: string;
}

In the example above, we’ve added the `@Expose()` decorator to the `User` class. The `toClassOnly` option is set to `true`, which means that the `address` field will only be included in the response if it has a value. If the `address` field is null, it will be excluded from the response.

Using the `classToPlain()` Function

Another way to exclude null fields is by using the `classToPlain()` function from the `class-transformer` package. This function converts a class to a plain object, excluding any properties that are null.


import { classToPlain } from 'class-transformer';

const user = new User();
user.id = 1;
user.name = 'John Doe';
user.email = 'john.doe@example.com';

const plainUser = classToPlain(user, { excludeNulls: true });

console.log(plainUser);
// {
//   id: 1,
//   name: 'John Doe',
//   email: 'john.doe@example.com'
// }

In the example above, we’ve created a `User` object and used the `classToPlain()` function to convert it to a plain object. We’ve also passed the `excludeNulls` option as `true`, which tells the function to exclude any properties that are null. The resulting plain object excludes any null fields.

Implementing a Custom Exclusion Strategy

If you need more control over which fields are excluded, you can implement a custom exclusion strategy. This can be done by creating a custom function that takes an object as an argument and returns a new object with the null fields excluded.


function excludeNullFields(obj: any) {
  const newObj = {};
  for (const key in obj) {
    if (obj.hasOwnProperty(key) && obj[key] !== null) {
      newObj[key] = obj[key];
    }
  }
  return newObj;
}

const user = new User();
user.id = 1;
user.name = 'John Doe';
user.email = 'john.doe@example.com';
user.address = null;

const excludedUser = excludeNullFields(user);

console.log(excludedUser);
// {
//   id: 1,
//   name: 'John Doe',
//   email: 'john.doe@example.com'
// }

In the example above, we’ve created a custom `excludeNullFields()` function that takes an object as an argument. The function loops through the object’s properties and excludes any properties that are null. The resulting object is returned without any null fields.

Using NestJs Built-in Serialization

NestJs provides a built-in serialization mechanism that can be used to exclude null fields. This mechanism can be enabled by setting the `excludeNulls` option in the `main.ts` file.


import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.enableCors();
  app.setGlobalPrefix('api');

  // Enable serialization with null exclusion
  app.useGlobalPipes(new ValidationPipe({
    transform: true,
    whitelist: true,
    excludeNulls: true,
  }));

  await app.listen(3000, () => {
    console.log('Listening on port 3000');
  });
}
bootstrap();

In the example above, we’ve enabled serialization with null exclusion by setting the `excludeNulls` option to `true` in the `ValidationPipe`. This will exclude any null fields from the response.

Best Practices

To get the most out of excluding null fields in NestJs, follow these best practices:

  1. Use Consistent Naming Conventions: Use consistent naming conventions for your fields and properties to avoid confusion.
  2. Document Your API: Document your API to ensure that consumers know which fields are excluded.
  3. Test Your API: Test your API to ensure that the null fields are being excluded correctly.
  4. Use Custom Exclusion Strategies Wisely: Use custom exclusion strategies wisely and only when necessary, as they can add complexity to your code.

Conclusion

In conclusion, excluding null fields in NestJs is an essential technique for providing a better user experience and improving performance. By using the `@Expose()` decorator, `classToPlain()` function, or custom exclusion strategies, you can exclude null fields and provide a cleaner response. Remember to follow best practices and test your API to ensure that the null fields are being excluded correctly.

Method Description
`@Expose()` Decorator Use the `@Expose()` decorator to exclude null fields from the response.
`classToPlain()` Function Use the `classToPlain()` function to convert a class to a plain object, excluding null fields.
Custom Exclusion Strategy Implement a custom exclusion strategy using a function that takes an object as an argument and returns a new object with the null fields excluded.
NestJs Built-in Serialization Use NestJs built-in serialization mechanism with null exclusion enabled.

By following the techniques outlined in this article, you’ll be well on your way to providing a better user experience and improving performance in your NestJs API.

Frequently Asked Question

Get the inside scoop on how to exclude fields that are null in NestJS!

How can I exclude fields that are null in a NestJS response?

You can use the `exclude` property in the `@Transform()` decorator to exclude fields that are null. For example: `@Transform(({ value }) => { return { …value, nullableField: value.nullableField ?? undefined }; })`. This will remove the `nullableField` if it’s null.

Can I exclude fields that are null using the `class-transformer` package?

Yes, you can use the `excludeIf` option in the `@Expose()` decorator from the `class-transformer` package to exclude fields that are null. For example: `@Expose({ groups: [‘user’], exceptIf: (value) => value === null })`. This will exclude the field if its value is null.

How can I exclude fields that are null recursively in a NestJS response?

You can use a recursive function to exclude fields that are null. For example: `function excludeNullFields(obj: any) { Object.keys(obj).forEach(key => { if (obj[key] === null) delete obj[key]; else if (typeof obj[key] === ‘object’) excludeNullFields(obj[key]); }); return obj; }`. This function will recursively remove fields that are null from the object.

Can I exclude fields that are null using the ` nestjsx-crud` package?

Yes, the `nestjsx-crud` package provides an `excludeNull` option that can be used to exclude fields that are null. For example: `@Crud({ excludeNull: true })`. This will exclude fields that are null from the response.

How can I exclude fields that are null in a NestJS response using the `JsonSerializer`?

You can use the `serialize` method of the `JsonSerializer` to exclude fields that are null. For example: `serialize(obj: any) { return JSON.parse(JSON.stringify(obj, (key, value) => value === null ? undefined : value)); }`. This will exclude fields that are null from the response.