Last active
April 13, 2024 11:25
-
-
Save Karytonn/fea56f2173bd48903e213945a046ca1f to your computer and use it in GitHub Desktop.
Notion API with Deno Deploy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { serve } from "https://deno.land/[email protected]/http/server.ts"; // from Deno | |
interface Link { | |
id: number; | |
label: string; | |
url: string; | |
target: string; | |
} | |
const NOTION_DATABASE_ID = Deno.env.get("NOTION_DATABASE_ID") | |
const NOTION_TOKEN = Deno.env.get("NOTION_TOKEN") | |
const headers = new Headers({ | |
'Content-Type': 'application/json; charset=utf-8', | |
}) | |
serve(async (req) => { | |
headers.set('Access-Control-Allow-Origin', '*'); | |
headers.set('Access-Control-Allow-Headers', '*'); | |
headers.set('Access-Control-Allow-Methods', 'GET'); | |
let LINKS: Link[] = []; | |
if(req.url.endsWith("api/linkbio") && req.method == "GET") { | |
const API_URL = `https://api.notion.com/v1/databases/${NOTION_DATABASE_ID}/query`; | |
const TOKEN = `Bearer ${NOTION_TOKEN}`; | |
try { | |
LINKS = await fetch(API_URL, { | |
method: 'POST', | |
headers: { | |
'Authorization': TOKEN, | |
'Notion-Version': '2022-06-28', | |
'Content-Type': 'application/json' | |
}, | |
body: JSON.stringify( | |
{ | |
"filter": { | |
"property": "type", | |
"select": { | |
"equals": "CTA" | |
} | |
}, | |
"sorts": [ | |
{ | |
"property": "id", | |
"direction": "ascending" | |
} | |
] | |
} | |
) | |
}) | |
.then((response) => response.json()) | |
.then((data) => { | |
// Sanitiza a resposta do Notion devolvendo somente as dados necessários | |
const filteredData = data.results?.map((item: any): Link => { | |
return { | |
id: item.properties?.id?.number, | |
label: item.properties?.Label?.rich_text[0].plain_text, | |
url: item.properties?.url?.url, | |
target: item.properties?.target?.select?.name | |
}; | |
}) | |
return filteredData; | |
}); | |
} catch (error) { | |
return new Response(JSON.stringify( error ), { headers }); | |
} | |
// Retorna os dados via API | |
try { | |
return new Response(JSON.stringify(LINKS), { headers }); | |
} catch (error) { | |
console.error(error); | |
return new Response(JSON.stringify( error ), { headers } ); | |
} | |
} | |
return new Response(JSON.stringify ( { error : "Unauthorized access!" } ), { headers }); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Extrutura dos dados no Notion: