Question

Nested promise result in testAuth method.

  • 15 June 2020
  • 3 replies
  • 106 views

Userlevel 1

Hello.

Could someone explain me how to use nested promises in testAuth method?

I have multy-tenant site and have to verify if there are same users in different tenants by email. It is my first z.request in auth method. Then inside .then block of first promise I want to use returned data to login specific user.

Zapier instead of returning result of nested promise to auth URL returns me parent result of promise that checks users email in tenant.
Is it possible to have multiple nested API calls in Auth section of Zap?


This post has been closed for comments. Please create a new post if you need help or have a question about this topic.

3 replies

Userlevel 7
Badge +11

@topvova - Can you show us the bit of code you wrote? Thanks!

Userlevel 1

@ikbelkirasan 
 

const testAuth = (z, bundle) => {
// request companies by email
z.request({
url: `${SIGN_IN_URL}?email=${bundle.authData.email}`,
})
.then(response => {
if (response.json) { // list of companies (this is returned instead of last return)
let userCompany = null;

if (response.json.length === 1) {
// if only one company with that email - authorize user
userCompany = response.json[0];
} else {
// multiple companies, compare with user input (company name) and login
userCompany = response.json.find(company => bundle.authData.companyName === company.company_name);
}

const authOptions = {
method: 'POST',
url: `https://${userCompany.company_url}/api/v1/authentication/sign-in?uuid=${userCompany.unique_key}`,
body: {
email: bundle.authData.email,
password: bundle.authData.password,
}
};

return z.request(authOptions)
.then((response) => {
z.console.log('Authentication:', response);
return response; // need to return this
});
}
});
}

 

Userlevel 7
Badge +11

@topvova - Try the code snippet below, it is based on async/await which is easier to read than promise chains.

const testAuth = async (z, bundle) => {
// request companies by email
const { json: companies } = await z.request({
method: "GET",
url: SIGN_IN_URL,
params: {
email: bundle.authData.email,
},
});

// list of companies (this is returned instead of last return)
let userCompany = null;

if (companies.length === 1) {
// if only one company with that email - authorize user
userCompany = companies[0];
} else {
// multiple companies, compare with user input (company name) and login
userCompany = companies.find(
(company) => bundle.authData.companyName === company.company_name
);
}

if (!userCompany) {
throw new Error("Company not found");
}

const { json: userData } = await z.request({
method: "POST",
url: `https://${userCompany.company_url}/api/v1/authentication/sign-in`,
params: {
uuid: userCompany.unique_key,
},
body: {
email: bundle.authData.email,
password: bundle.authData.password,
},
});

return userData;
};