Skip to content

Instantly share code, notes, and snippets.

@Karytonn
Last active April 13, 2024 11:25
Show Gist options
  • Save Karytonn/fea56f2173bd48903e213945a046ca1f to your computer and use it in GitHub Desktop.
Save Karytonn/fea56f2173bd48903e213945a046ca1f to your computer and use it in GitHub Desktop.
Notion API with Deno Deploy
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 });
});
@Karytonn
Copy link
Author

Extrutura dos dados no Notion:

Screenshot 2024-02-11 at 19 12 05

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment