DEV Community

Cover image for 80-Nodejs Course 2023: Resources: Default values
Hasan Zohdy
Hasan Zohdy

Posted on

80-Nodejs Course 2023: Resources: Default values

Sometimes, values are not fully passed, so we need to set default value for them if they were missing in the given resource data.

Default values

Default values are basically values that will be used if the given resource data doesn't have the key that we want to use.

How it works

So we're going just to define a property called defaults, this is just a plain object that contains a key to be used as output, and the value of that key will be the default value.

That's it!

Example

Now open our user-resource.ts file and add the following code:

// src/app/users/resources/user-resource.ts
import Resource from 'core/resources/resource';
import { uploadsUrl } from 'core/utils/urls';

export default class UserResource extends Resource {
  /**
   * Output shape
   */
  protected output: any = {
    id: 'number',
    name: 'string',
    email: 'string',
    age: 'number',
    avatar: uploadsUrl,
    createdBy: UserResource,
 };

  /**
   * Defaults when key is missing from resource
   */
  protected defaults = {
    name: "John Doe",
    image: "users/my-image.jpg",
  };
}
Enter fullscreen mode Exit fullscreen mode

We defined here a new property called defaults, and we defined a key name and its default value is John Doe, and we defined a key image and its default value is users/my-image.jpg.

But of course it won't work as we didn't implement it as usual, so let's do it.

Implementation

Now open our base resource class, we'll add that defaults property to be initially defined with empty object, then in our transforming method, we'll add another check, if the key doesn't exist in the resource, we'll check if it exists in the defaults property, if it exists, we'll use it, otherwise we'll use the missingKey symbol.

// src/core/resources/resource.ts
import { get } from "@mongez/reinforcements";

// this will be used to skip the output property if it is missing from the given resource
const missingKey = Symbol("missing");

export default class Resource {
  /**
   * Output shape
   */
  protected output: any = {};

  /**
   * Defaults when key is missing from resource
   */
  protected defaults: any = {};

  /**
   * Constructor
   */
  public constructor(protected resource: any = {}) {
    //
  }

  /**
   * {@inheritDoc}
   */
  public toJSON() {
    // final output
    const data: Record<string, any> = {};

    // loop through the output property
    for (const key in this.output) {
      // get the value type
      const valueType = this.output[key];
      // get the value, and also make sure to skip the output property if it is missing from the given resource

      // check that other                 👇🏻 get to check if the key exists in the defaults object
      let value = get(this.resource, key, get(this.defaults, key, missingKey));

      // skip the output property if it is missing from the given resource
      if (value === missingKey) {
        continue;
      }

      if (typeof valueType === "string") {
        // cast the value
        value = this.cast(value, valueType);
      } else if (valueType.prototype instanceOf Resource) {
        // if the value type is a resource, then pass the value to it
        value = new valueType(value).toJSON();
      } else if (typeof valueType === "function") {
        // call the custom output handler
        value = valueType(value);
      }

      // just for now sett the output value to the data
      data[key] = value;
    }

    return data;
  }
}
Enter fullscreen mode Exit fullscreen mode

All what we changed here is the third argument of get function, instead of passing missingKey symbol, we're going to pass another get function but this time it will be search in the defaults property, if the key exists in the defaults property, it will return the value, otherwise it will return the missingKey symbol.

Now try that in your code, you'll see that the name and image keys will be added to the output with their default values if you didn't pass them in the resource data.

🎨 Conclusion

In this lesson, we learned how to set default values for the output keys if they were missing in the given resource data.

☕♨️ Buy me a Coffee ♨️☕

If you enjoy my articles and see it useful to you, you may buy me a coffee, it will help me to keep going and keep creating more content.

🚀 Project Repository

You can find the latest updates of this project on Github

😍 Join our community

Join our community on Discord to get help and support (Node Js 2023 Channel).

🎞️ Video Course (Arabic Voice)

If you want to learn this course in video format, you can find it on Youtube, the course is in Arabic language.

📚 Bonus Content 📚

You may have a look at these articles, it will definitely boost your knowledge and productivity.

General Topics

Packages & Libraries

React Js Packages

Courses (Articles)

Top comments (0)