Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Get signed file URL endpoint proposal #49

Draft
wants to merge 25 commits into
base: master
Choose a base branch
from
Draft
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
added file redirect endpoint
janzheng committed Jun 25, 2021
commit 22998ae937d4001faeabc8da714772c1609fb535
8 changes: 6 additions & 2 deletions src/api/notion.ts
Original file line number Diff line number Diff line change
@@ -33,10 +33,13 @@ const fetchNotionData = async <T extends any>({
"content-type": "application/json",
...(notionToken && { cookie: `token_v2=${notionToken}` }),
},

body: JSON.stringify(body),
});

return res.json();

let json = await res.json()
// console.log('fetchNotionData:', json)
return json;
};

export const fetchPageById = async (pageId: string, notionToken?: string) => {
@@ -78,6 +81,7 @@ export const fetchTableData = async (
},
notionToken,
});
// console.log('fetchTableData:', table)
return table;
};

4 changes: 4 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -3,8 +3,10 @@ import { Router, Method } from "tiny-request-router";

import { pageRoute } from "./routes/page";
import { tableRoute } from "./routes/table";
import { collectionRoute } from "./routes/collection";
import { userRoute } from "./routes/user";
import { assetRoute } from "./routes/asset";
import { fileRoute } from "./routes/file";
import { searchRoute } from "./routes/search";
import { createResponse } from "./response";
import { getCacheKey } from "./get-cache-key";
@@ -25,9 +27,11 @@ const router = new Router<Handler>();
router.options("*", () => new Response(null, { headers: corsHeaders }));
router.get("/v1/page/:pageId", pageRoute);
router.get("/v1/table/:pageId", tableRoute);
router.get("/v1/collection/:pageId", collectionRoute);
router.get("/v1/user/:userId", userRoute);
router.get("/v1/search", searchRoute);
router.get("/v1/asset", assetRoute);
router.get("/v1/file", fileRoute);

router.get("*", async () =>
createResponse(
108 changes: 108 additions & 0 deletions src/routes/collection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import { fetchPageById, fetchTableData, fetchNotionUsers } from "../api/notion";
import { parsePageId, getNotionValue } from "../api/utils";
import {
RowContentType,
CollectionType,
RowType,
HandlerRequest,
} from "../api/types";
import { createResponse } from "../response";

export const getCollectionData = async (
collection: CollectionType,
collectionViewId: string,
notionToken?: string,
raw?: boolean
) => {
const table = await fetchTableData(
collection.value.id,
collectionViewId,
notionToken
);


const collectionRows = collection.value.schema;
const collectionColKeys = Object.keys(collectionRows);

const tableArr: RowType[] = table.result.blockIds.map(
(id: string) => table.recordMap.block[id]
);

const tableData = tableArr.filter(
(b) =>
b.value && b.value.properties && b.value.parent_id === collection.value.id
);

type Row = { id: string;[key: string]: RowContentType };

const rows: Row[] = [];

for (const td of tableData) {
let row: Row = { id: td.value.id };

for (const key of collectionColKeys) {
const val = td.value.properties[key];
if (val) {
const schema = collectionRows[key];
row[schema.name] = raw ? val : getNotionValue(val, schema.type, td);
if (schema.type === "person" && row[schema.name]) {
const users = await fetchNotionUsers(row[schema.name] as string[]);
row[schema.name] = users as any;
}
}
}
rows.push(row);
}

const name: String = collection.value.name.join('')

return { rows, schema: collectionRows, name };
};






export async function collectionRoute(req: HandlerRequest) {
const pageId = parsePageId(req.params.pageId);
const page = await fetchPageById(pageId!, req.notionToken);

if (!page.recordMap.collection)
return createResponse(
JSON.stringify({ error: "No table found on Notion page: " + pageId }),
{},
401
);

const collection = Object.keys(page.recordMap.collection).map(
(k) => page.recordMap.collection[k]
)[0];

const views: any[] = []

const collectionView: {
value: { id: CollectionType["value"]["id"] };
} = Object.keys(page.recordMap.collection_view).map((k) => {

views.push(page.recordMap.collection_view[k]['value'])
return page.recordMap.collection_view[k]
})[0];

const tableData = await getCollectionData(
collection,
collectionView.value.id,
req.notionToken
);

// console.log('table data:', JSON.stringify(collectionView.value))
// console.log('view:', JSON.stringify(page.recordMap))

// clean up the table order
const tableProps = views[0].format.table_properties
tableProps.map((tableCol, i) => {
tableProps[i] = { ...tableProps[i], ...tableData.schema[tableCol['property']] }
})

return createResponse({ ...tableData, columns: tableProps, sort: views[0].page_sort, collection: collection });
}
32 changes: 32 additions & 0 deletions src/routes/file.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { fetchNotionAsset } from "../api/notion";
import { HandlerRequest } from "../api/types";
import { createResponse } from "../response";

export async function fileRoute(req: HandlerRequest) {

let url = new URL(req.request.url)
let fileUrl = url.searchParams.get('url')
let blockId = url.searchParams.get('blockId')

if (!fileUrl || !blockId)
return createResponse(
{ error: 'Please supply a file URL and block ID: asset?url=[file-url]&blockId=[block ID]' },
{ "Content-Type": "application/json" },
400
);

const asset:any = await fetchNotionAsset(fileUrl, blockId);

if (asset && asset.signedUrls && asset.signedUrls[0])
return Response.redirect(
asset.signedUrls[0],
302
);

return createResponse(
{ error: 'File not found' },
{ "Content-Type": "application/json" },
400
);
}