Skip to content

Commit

Permalink
Udate code
Browse files Browse the repository at this point in the history
  • Loading branch information
machulav committed Oct 28, 2024
1 parent 64c16f7 commit 7a25a77
Showing 1 changed file with 29 additions and 35 deletions.
64 changes: 29 additions & 35 deletions src/actions/askCodaTable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,9 @@ const actionDefinition: ActionDefinition = {
},
outputParameters: [
{
key: 'qaContent',
name: 'Q&A Content',
description: 'The Q&A content retrieved from the Coda table',
key: 'content',
name: 'Content',
description: 'The content retrieved from the Coda table',
type: 'string',
validation: {
required: true,
Expand All @@ -54,26 +54,21 @@ const actionDefinition: ActionDefinition = {
export default actionDefinition;

export async function handler({ input }: ActionContext): Promise<OutputObject> {
try {
const { docId, pageName } = extractIdsFromUrl(input.codaUrl);
const pageId = await getPageId(docId, pageName, input.codaApiKey);
const tableIds = await fetchTableIds(docId, pageId, input.codaApiKey);
let qaContent = await fetchQAContent(docId, tableIds, input.codaApiKey);

if (input.instructions) {
qaContent = `Instructions for the following content: ${input.instructions}\n\n${qaContent}`;
}
const { docId, pageName } = extractIdsFromUrl(input.codaUrl);
const pageId = await getPageId(docId, pageName, input.codaApiKey);
const tableIds = await fetchTableIds(docId, pageId, input.codaApiKey);
let content = await fetchQAContent(docId, tableIds, input.codaApiKey);

return {
qaContent: qaContent,
};
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
throw new Error(`Failed to process the request: ${errorMessage}`);
if (input.instructions) {
content = `Instructions for the following content: ${input.instructions}\n\n${content}`;
}

return {
content: content,
};
}

function extractIdsFromUrl(url: string): { docId: string, pageName: string } {
function extractIdsFromUrl(url: string): { docId: string; pageName: string } {
const urlObj = new URL(url);
const pathParts = urlObj.pathname.split('/').filter(Boolean);

Expand All @@ -87,9 +82,9 @@ function extractIdsFromUrl(url: string): { docId: string, pageName: string } {
if (pathParts[0] === 'd') {
const docIdParts = pathParts[1].split('_');
if (docIdParts.length > 1) {
docId = docIdParts[docIdParts.length - 1]; // Get the last part after splitting by '_'
docId = docId.startsWith('d') ? docId.slice(1) : docId; // Remove leading 'd' if present
pageName = pathParts[2] || ''; // Page name is the third part, if present
docId = docIdParts[docIdParts.length - 1]; // Get the last part after splitting by '_'
docId = docId.startsWith('d') ? docId.slice(1) : docId; // Remove leading 'd' if present
pageName = pathParts[2] || ''; // Page name is the third part, if present
} else {
throw new Error('Unable to extract Doc ID from the provided URL');
}
Expand All @@ -103,7 +98,7 @@ function extractIdsFromUrl(url: string): { docId: string, pageName: string } {
async function getPageId(docId: string, urlPageName: string, apiKey: string): Promise<string> {
const url = `https://coda.io/apis/v1/docs/${docId}/pages`;
const response = await axios.get(url, {
headers: { 'Authorization': `Bearer ${apiKey}` },
headers: { Authorization: `Bearer ${apiKey}` },
});

// Function to normalize strings for comparison
Expand All @@ -112,9 +107,8 @@ async function getPageId(docId: string, urlPageName: string, apiKey: string): Pr
// Extract the main part of the URL page name (before the underscore)
const mainUrlPageName = urlPageName.split('_')[0];

const page = response.data.items.find((p: any) =>
normalize(p.name) === normalize(mainUrlPageName) ||
p.browserLink.includes(urlPageName)
const page = response.data.items.find(
(p: any) => normalize(p.name) === normalize(mainUrlPageName) || p.browserLink.includes(urlPageName),
);

if (!page) {
Expand All @@ -126,11 +120,11 @@ async function getPageId(docId: string, urlPageName: string, apiKey: string): Pr

async function fetchTableIds(docId: string, pageId: string, apiKey: string): Promise<string[]> {
const url = `https://coda.io/apis/v1/docs/${docId}/tables?pageId=${pageId}`;

const response = await axios.get(url, {
headers: { 'Authorization': `Bearer ${apiKey}` },
headers: { Authorization: `Bearer ${apiKey}` },
});

const filteredTables = response.data.items.filter((table: any) => table.parent?.id === pageId);

return filteredTables.map((table: any) => table.id);
Expand All @@ -143,26 +137,26 @@ async function fetchQAContent(docId: string, tableIds: string[], apiKey: string)
// Fetch column information
const columnsUrl = `https://coda.io/apis/v1/docs/${docId}/tables/${tableId}/columns`;
const columnsResponse = await axios.get(columnsUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
headers: { Authorization: `Bearer ${apiKey}` },
});

const columnMap = new Map(columnsResponse.data.items.map((col: any) => [col.id, col.name as string]));

let nextPageToken: string | null = null;
do {
const rowsUrl: string = `https://coda.io/apis/v1/docs/${docId}/tables/${tableId}/rows?limit=100${nextPageToken ? `&pageToken=${nextPageToken}` : ''}`;
const rowsResponse = await axios.get(rowsUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
headers: { Authorization: `Bearer ${apiKey}` },
});

const rows = rowsResponse.data.items;
nextPageToken = rowsResponse.data.nextPageToken || null;

if (rows.length > 0) {
const columnIds = Object.keys(rows[0].values).slice(0, 10); // Get up to first 10 column IDs
const columnIds = Object.keys(rows[0].values).slice(0, 10); // Get up to first 10 column IDs

rows.forEach((row: { values: Record<string, any> }) => {
const values = columnIds.map(id => {
const values = columnIds.map((id) => {
const columnName = columnMap.get(id) || id;
const value = row.values[id];
return `${columnName}: ${value}`;
Expand All @@ -174,7 +168,7 @@ async function fetchQAContent(docId: string, tableIds: string[], apiKey: string)

// Optionally, we can add a note about empty tables or skipped rows to the qaContent
if (qaContent === '') {
qaContent += "Note: No rows found in this table.\n\n";
qaContent += 'Note: No rows found in this table.\n\n';
}
}

Expand Down

0 comments on commit 7a25a77

Please sign in to comment.