Skip to main content

I am attempting to create a zap that in step 1 uses the “new file” in a sharefile directory.  
I want step 2 to be using code by zapier to connect to the sharefile api and read the uploaded csv file as a stream.  When I do this, I get the error ‘access denied’ however, executing my code in a stand-along vanilla javascript project I am able to do such.

 

Has anyone had success in doing this with code by zapier?

 

const sharefileApiUrl = "https://company-name.sf-api.com";
const sharefileClientId = "alkljasfljaslfkjasfas";
const sharefileClientSecret = "kljasdflkjaskljfklsajfklas";
const sharefileUsername = "test@test.com";
const sharefilePassword = "";
const sharefileDir = "/Test Folder/Test_Data/";

let fileData = await searchDirectoryForFile(inputData.fileName);
let jsonArray = await readShareFileContents(fileData.Id);
const formattedData = processJsonArray(jsonArray);


async function searchDirectoryForFile(filename) {

const accessToken = await getAccessToken();

try {
const parentIdResponse = await fetch(`${sharefileApiUrl}/sf/v3/Items/ByPath?path=${encodeURIComponent(sharefileDir)}`, {
method: 'GET',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Accept': 'application/json',
},
});

const parentIdData = await parentIdResponse.json();
if (!parentIdData.Id) {
console.log('Invalid parent folder path.');
return ];
}

const parentId = parentIdData.Id;
const searchUrl = `${sharefileApiUrl}/sf/v3/Items(${parentId})/Children?includeSubfolders=true&$filter=contains(Name, '${filename}')`;

const response = await fetch(searchUrl, {
method: 'GET',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Accept': 'application/json',
},
});

const data = await response.json();
let jsonArray = ];

if (data.value && data.value.length > 0) {
jsonArray = data.value.map(item => ({
id: item.Id,
name: item.Name,
path: item.Parent,
}));

console.log('JSON Array:', JSON.stringify(jsonArray, null, 2));

return jsonArray;
} else {
console.log('No matching files found.');
return ];
}
} catch (error) {
console.error('Error Error Johnathan:', error);
return ];
}
}

async function getAccessToken() {
const tokenUrl = `${sharefileApiUrl}/oauth/token`;

const response = await fetch(tokenUrl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams({
'grant_type': 'password',
'client_id': sharefileClientId,
'client_secret': sharefileClientSecret,
'username': sharefileUsername,
'password': sharefilePassword
})
});

const data = await response.json();
return data.access_token;
}

async function readShareFileContents(fileId) {
var accessToken = await getAccessToken();
const fileUrl = `${sharefileApiUrl}/sf/v3/Items(${fileId})/Download`;

const response = await fetch(fileUrl, {
method: 'GET',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Accept': 'application/json',
},
});

if (!response.ok) {
throw new Error(`File retrieval failed: ${response.statusText}`);
}

const reader = response.body.getReader();
const decoder = new TextDecoder();
let jsonString = '';

const stream = new ReadableStream({
start(controller) {
function push() {
reader.read().then(({ done, value }) => {
if (done) {
controller.close();
return;
}
jsonString += decoder.decode(value, { stream: true }); // Append streamed content
controller.enqueue(value);
push();
}).catch(error => {
console.error('Stream error:', error);
controller.error(error);
});
}
push();
}
});

await new Response(stream).text();
const jsonArray = JSON.parse(jsonString);

return jsonArray;
}


 

Be the first to reply!