LoginSignup
4
0

More than 3 years have passed since last update.

[Elixir]Qiitaの自分の記事をエクスポートする

Last updated at Posted at 2020-07-22

はじめに

  • 「Qiita夏祭り2020 オンライン」ライブ配信 に参加しました
  • パネルディスカッションの中で「あると便利だよね〜」と話にでていたエクスポートの件をElixirを使って書いてみました
  • 最大10,000件までエクスポートできます(たぶんね)
    • 自分の記事がそんなに多くないので本当に動くのかどうかは未確認 :sweat_smile:
    • 2020/12/20現在、私の記事は140件ほどあるので試してみたところ、ページネーションのところがちゃんと動くことを確認しました
  • Elixir1.11.2-otp-23を使っています

0. インストールとプロジェクトの作成

  • まずはElixirをインストールしましょう
  • インストールができましたら以下のコマンドでプロジェクトを作ります
$ mix new qiita_export
$ cd qiita_export

1. 依存関係の解決

mix.exs
  defp deps do
    [
      {:httpoison, "~> 1.6"}, # add
      {:jason, "~> 1.2"} # add
    ]
  end
$ mix deps.get

2. ソースコードを書く

lib/qiita/api.ex
defmodule Qiita.Api do
  @token "secret"
  @per_page 100
  @headers [Authorization: "Bearer #{@token}", Accept: "Application/json; Charset=utf-8"]

  def items_count(id \\ "torifukukaiou") do
    HTTPoison.get("https://qiita.com/api/v2/users/#{id}")
    |> decode_response()
    |> Jason.decode!()
    |> Map.get("items_count")
  end

  def items_by_page(page) do
    "https://qiita.com/api/v2/authenticated_user/items?page=#{page}&per_page=#{@per_page}"
    |> HTTPoison.get(@headers)
    |> decode_response()
    |> Jason.decode!()
  end

  def max_page(items_count) when rem(items_count, @per_page) == 0 do
    div(items_count, @per_page) |> min(100)
  end

  def max_page(items_count) do
    (div(items_count, @per_page) + 1) |> min(100)
  end

  defp decode_response({:ok, %HTTPoison.Response{body: body, status_code: 200}}) do
    body
  end

  defp decode_response(_), do: raise("")
end
qiita_export.ex
defmodule QiitaExport do
  @user_id "torifukukaiou"
  def run do
    max_page = Qiita.Api.items_count(@user_id) |> Qiita.Api.max_page()

    1..max_page
    |> Enum.each(fn page ->
      Qiita.Api.items_by_page(page)
      |> Enum.each(fn %{"body" => body, "title" => title} ->
        File.write!(filename(title), body)
      end)
    end)
  end

  defp filename(title) do
    title
    |> String.replace("/", "_") # ファイル名に使えない文字があったらここで調整
    |> Kernel.<>(".md")
  end
end
  • (.mdでいいんだよね? :thinking: )

3. 実行 :rocket::rocket::rocket:

$ iex -S mix

iex> QiitaExport.run
:ok

Wrapping Up

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0