2

I'm looking to enforce a validation of sort to be implemented in LWC that consumes an external API.

  • The validation call is suppose to check user access (an APEX based external API validation).
  • Then if validation call returns true, then execute any other API function (an APEX method to carry out the operation), otherwise throw/alert user.

Tried looking into Chaining Promises in LWC, and it seems to work fine, except I have to repeat code for each method that I need to be validating first, and there could be 50+ something different methods (with and without parameters).

Here is what I've tried implementing but I want to make it generic:

async _apexMethod_1() {
    try {
        let res;
        let user_info = await getUserInfo();
        if (user_info.authenticated === true) {
            res =  await apexMethod_1_Call({param_1: user_info.user_unique_code});
        } else {
            this.errorMessage = MESSAGES.UNAUTHORISED_USER;
        }
        return res;
    } catch(err) {
        alert(err);
    }
}

here, getUserInfo and apexMethod_1_Call are APEX Methods imported earlier in LWC component, so both are returning promises.

But, since I've to repeat this getUserInfo call before every call I want to generalize it so that I don't have to make multiple functions to call individual APEX methods. But rather, if I can make this a generic _apexMethod( callBackMethod(params) ) function where I can pass the callback APEX method as parameter and execute and return the APEX promise from the call or consume the promise response within the callback itself declaration.

1 Answer 1

1

You can start off with the dispatcher:

async callApex(method) {
    let userInfo;
    try {
        userInfo = await getUserInfo();
    } catch(error) {
        this.handleApexCallError(error);
        return;
    }
    if(!userInfo.authenticated) {
        this.userNotAuthorized();
        return;
    }
    method(userInfo);
}

Where method is implemented like:

async callApexMethod1(userInfo) {
    try {
        let result = await apexMethod_1_Call({param1: userInfo.user_unique_code});
    } catch(error) {
        // This error happened because of error to apexMethod_1_Call
    }
}

Which reduces the actual usage call to just:

example() {
    this.callApex(this.callApexMethod1);
}

Other variants are possible, of course, but hopefully I've conveyed the main idea that you can pass functions around dynamically.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .