Best practice approach for processing OData requests in JavaScript

There are many different ways to read and process OData requests in JavaScript. Over time, the following approach has turned out to be the best and most robust for me personally.

Function

📟 _read

example of a get entity request.

📟 readData

async function that calls the _read function in a try...catch statement and process the response of the request.

	/**
		 * @memberOf Sample
		 * @private
		 * @async
		 * @description Read data from backend
		 * @param {string} sKey
		 */
		_read: function (sKey) {
			var oServiceModel = this._oServiceModel;
			return new Promise((fnResolve, fnReject) => {

				var sPath = oServiceModel.createKey("/XYZSet", {
					Key: sKey
				});

				var oParameters = {
					success: fnResolve,
					error: fnReject //,
						//filters: [],
						// urlParameters: {
						// 	"$expand": "ASet"
						// }
				};

				oServiceModel.read(sPath, oParameters);

			});
		},
	/**
		 * @memberOf Sample
		 * @public
		 * @async
		 * @description Read the data.  
		 * <ol>
		 * <li>read data via {@link Sample.read}</li>
		 * <li>if there are errors convert them via {@link Sample.convertExceptionToMessages}</li>
		 * </ol>
		 * @param {string} sKey - key
		 */
		readData: async function (sKey) {
			var oResponse = {
				success: true,
				messages: []
			};

			//start the process/set busy indicator
			this.setProperty("/busy", true);

			try {
				let oReadResponse = await this.read(sObjectId, sObjectType, sObjectSubType); //read Data from Backend
				this.setProperty("/data", oReadResponse.results); //set data

			} catch (oException) {
				let aMessages = this.convertExceptionToMessages(oException); //convert exception to error message
				oResponse.success = false;
				oResponse.messages = aMessages;

			} finally {
				this.setProperty("/busy", false); //end the process/set busy indicator

			}

			return oResponse;
		},

Example

Work in progress

Advantages

  • easy way of processing the response
  • easy way of catching exceptions
  • easy way of handling busy states

Related Information

Leave a Reply

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