Skip to content

Instantly share code, notes, and snippets.

@benvp
Created December 23, 2021 05:34
Show Gist options
  • Save benvp/f226893384fa97aeeeeab52083b1b14c to your computer and use it in GitHub Desktop.
Save benvp/f226893384fa97aeeeeab52083b1b14c to your computer and use it in GitHub Desktop.
Notion HTTP client
defmodule Benvp.Notion.Client.HTTP do
alias Benvp.Notion.Schema
alias Benvp.Notion.Parser
@base_url "https://api.notion.com/v1"
@notion_version "2021-08-16"
def get_page(id) do
case get(@base_url <> "/pages/#{id}") do
{:ok, %Finch.Response{status: 200} = res} ->
page =
res.body
|> Jason.decode!()
|> Parser.parse_page()
{:ok, page}
other_response ->
handle_error(other_response)
end
end
def get_block(block_id) do
case get(@base_url <> "/blocks/#{block_id}") do
{:ok, %Finch.Response{status: 200} = res} ->
block =
res.body
|> Jason.decode!()
|> Parser.parse_block()
{:ok, block}
other_response ->
handle_error(other_response)
end
end
def get_block_children(block_id) do
case get(@base_url <> "/blocks/#{block_id}/children") do
{:ok, %Finch.Response{status: 200} = res} ->
blocks =
res.body
|> Jason.decode!()
|> Map.get("results")
|> Enum.map(&Parser.parse_block/1)
{:ok, blocks}
other_response ->
handle_error(other_response)
end
end
def get_all_block_children(block_id) when is_binary(block_id) do
with {:ok, children} <- get_block_children(block_id) do
get_all_block_children(children)
end
end
def get_all_block_children(blocks) when is_list(blocks),
do: Enum.map(blocks, &get_all_block_children/1)
def get_all_block_children(block) do
if block.has_children do
with {:ok, children} <- get_block_children(block.id) do
content =
block
|> Map.get(block.type)
|> Map.put(:children, Enum.map(children, &get_all_block_children/1))
Map.put(block, block.type, content)
end
else
block
end
end
defp get(url, headers \\ []) do
default_headers = [
{"Authorization", "Bearer #{get_token()}"},
{"Notion-Version", @notion_version},
{"Content-Type", "application/json"},
{"Accept", "application/json"}
]
Finch.build(:get, url, default_headers ++ headers)
|> Finch.request(Benvp.Finch)
end
defp get_token() do
Application.get_env(:benvp, :notion_access_token)
end
defp handle_error(response) do
case response do
{:ok, %Finch.Response{} = res} ->
error =
res.body
|> Jason.decode!()
|> Schema.Error.new()
{:error, error}
{:error, _reason} = error ->
error
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment