Search code examples
javascriptnode.jsmodel-view-controllermodelsalesforce-commerce-cloud

How can I extend a class in Node JS by my custom constructor?


I have the following in a Node Js model. This file exists in another project that cannot be changed but is locally available to the other projects.

module.exports = {
    base: require('*/cartridge/models/product/decorators/base'),
    availability: require('*/cartridge/models/product/decorators/availability')
};

All the methods here act like constructors of the class Product. Now I want to add another attribute that should be available when I try to access Product.badge. For this, I have tried to extend the above model in the following way:

var indexBase = require('*/cartridge/models/product/decorators/index');

indexBase.badge = require('*/cartridge/models/product/decorators/badge');

module.exports = indexBase;

But it seems throw an error, I have tried to log the Badge Type, but I still cannot access the badge type here.

I am calling the above object as the following:

var decorators = require('*/cartridge/models/product/decorators/index');
decorators.badge(product, variantProduct);

I want to know how can I extend an existing class as I want to add a custom constructor?

Here only the syntax is based on Node Js but this code is written for SFRA in Salesforce B2C Commerce.


Solution

  • All you need to do is in the index.js file:

    var indexBase = module.superModule;
    

    instead of:

    var indexBase = require('*/cartridge/models/product/decorators/index');
    

    and it will work perfectly fine.