Fetch an empty structure of an entity in an OData service

Did you asked yourself, how to get an empty structure, with empty strings and booleans set to false from your OData service to use it later in a local JSON model.

To achieve this, we need here again the service metadata from our OData model.

/**
 * Fetches an empty structure from the metadata.
 * @param {object} oModel The model object, for example the oData service.
 * @param {string} sEntityName The name of the entity, which should be fetched in a structure.
 * @returns {object} An object, where the property names are the keys and their initial value is assined.
 */
fetchEmptyStructure: function (oModel, sEntityName) {
    const oMetadata = oModel.getServiceMetadata();
    
    let oEntity;
    for (let oCEntity of oMetadata.dataServices.schema[0].entityType) {
        if (oCEntity.name === sEntityName) {
            oEntity = oCEntity;
            break;
        }
    }
    
    if (oEntity) {
        let oStructure = {};
        for (let oCProperty of oEntity.property) {
            if (oCProperty.type === "Edm.String") {
                oStructure[oCProperty.name] = "";
            } else if (oCProperty.type === "Edm.Boolean") {
                oStructure[oCProperty.name] = false;
                
                // ...
                // Handle decimals, numbers or dates as custom or leave it undefined
                // ...
                
            } else {
                oStructure[oCProperty.name] = undefined;
            }
        }
        return oStructure;
    } else {
        // Entity not found in the service.
        return false;
    }
},

Test case

To test our code from above, we have triggered the method below in the onAfterRendering method with a delay of 2 seconds. This 2 second allows the framework to initially load the metadata, which it always does at the start.

onAfterRendering: function () {
      setTimeout(()=> {
          const oMetadata = this.fetchEmptyStructure(this.getView().getModel(), "Product");
          console.log(oMetadata); // For the console output
          console.log(JSON.stringify(oMetadata)); // For the JSON output.
      }, 2000);
  },

Result

As the result, we get a following structure:

{
  "ProductName": "",
  "QuantityPerUnit": "",
  "Discontinued": false
}

Since the undefined properties will not be shown, the code from above still assigns here these keys, which you can see in the console.

The console output (F12 developer tools from the browser).

Foto von Kelly Sikkema auf Unsplash


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Ads Blocker Image Powered by Code Help Pro

Ad blocker detected

We have detected that you are using extensions to block ads. Please support us by disabling your ad blocker.

Powered By
Best Wordpress Adblock Detecting Plugin | CHP Adblock