LoginSignup
2
2

More than 1 year has passed since last update.

Supabaseに作った郵便番号テーブルを参照する(Vue、Nuxt)

Last updated at Posted at 2023-01-14

下記の記事では、Supabaseに作成したデータベースに日本郵政のホームページから郵便番号データをダウンロードして、登録するところまで行いました。

Web画面からそれを使うアプリケーションを作成してみます。

アプリケーションの雛形

アプリケーションの雛形は、Supabaseのチュートリアルにある、Nuxt3のものを使っています。
下記のページの内容を一通り実施します。

郵便番号テーブル定義

RSLをONにして、SELECTは誰でもできるようにしています。


CREATE TABLE IF NOT EXISTS postcode(
  id serial  primary key,
  postcode varchar(8),
  ken varchar(6),
  address1 varchar(50),
  address2 varchar(50),
  updated_at timestamp with time zone not null default now()
);

create index on postcode (postcode);

alter table postcode
  enable row level security;

create policy "Users can select postcode." on postcode
  for select using (true);

郵便番号テーブルへのデータ登録

下記の記事です
https://qiita.com/adchan/items/7b11091de8612dfb623b

Webアプリケーションの実装

<script setup>
const supabase = useSupabaseClient()
const postcode = ref('')
const address = ref('')

async function searchAddress() {
    const { data, error } = await supabase
        .from('postcode')
        .select(`ken, address1, address2`)
        .eq('postcode', postcode.value)
        .single()
    if (error) {
        alert("住所情報が取得できません")
        return
    }
    if (data) {
        address.value = `${data.ken}${data.address1}${data.address2}`
    }
}

</script>
<template>
        <div>
            <label for="postcode">PostCode</label>
            <input id="postcode" type="text" v-model="postcode" />
            <button @click="searchAddress" :disabled="postcode === ''">住所変換</button>
        </div>
        <div>
            <label for="address">住所</label>
            <input id="address" type="text" v-model="address" />
        </div>
</template>

実践で使うには、2つ以上の住所が返ってくるケースなど考える必要があります。

APIの実装の手間が無く、非常に短時間に実装できました。
RDBをやっていた人にとっては、FirebaseのFirestoreよりは、とっつきやすいと思います。

SupabaseClientでSELECT時のエラーコードについて

SELECT時にデータが無い時は、下記のようなJSONが返ってきます。
code?って思ったのですが、下記ページのpostgrestのコードのようです。

{
code: "PGRST116",
details: "Results contain 0 rows, application/vnd.pgrst.object+json requires 1 row",
hint: null,
message: "JSON object requested, multiple (or no) rows returned"
}

2
2
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
2
2