LoginSignup
0
2

More than 1 year has passed since last update.

ReactからSqlite3を参照して一覧データを返すAPIを作る

Last updated at Posted at 2022-07-09

DynamoDBの方が慣れていますがSqlite3を使ってDBからデータを取得して返す仕組みを実装します。以下を参考にさせていただきました。

やりたいこと

・リクエストを受けてDBの特定テーブルを参照する
・参照結果をJSONの形に整形してレスポンスで返す

環境の確認

Sqlite3はMacに最初から導入済みのものを利用します

$ sqlite3 -version
3.37.0

Sqlite3の準備

test.db
CREATE TABLE Test(
  id TEXT PRIMARY KEY,
  name TEXT,
  create_at TEXT
);

insert into Test values ('1','test', datetime('now', 'localtime'));
insert into Test values ('2','テスト', datetime('now', 'localtime'));
insert into Test values ('3','テスト3', datetime('now', 'localtime'));
insert into Test values ('4','テスト4', datetime('now', 'localtime'));

API部分の修正

リクエストを受けてテーブルからデータを取得してJSONの形で返す仕様で、typeでテーブル定義を作りORMapしています。

hello.tsx
type Test = {
  id:string,
  name:string,
  create_at:string,
}

export default function hello(req, res) {;
  const sqlite3 = require('sqlite3');
  const db = new sqlite3.Database('./test.db');
  const result = new Promise((resolve, reject) => {
    db.serialize(() => {
      db.all(`select * from Test`, (err, tests) => {
          if (err) return reject(err)
          return resolve(tests)
      })
      db.close();
    })
  })
  result.then((responsetest) => {
      res.status(200).json(responsetest);
    }
  )
}

画面

image.png
表示項目を増やして上記画面になっています

今回はAPIのDB接続部分の話なのでそれ以外は省略します。画面の表示部分は過去の記事か以下などを参照していただければと存じます。
https://github.com/kusakari-kai/rgforcommunication/blob/main/pages/index.tsx
https://github.com/kusakari-kai/rgforcommunication/blob/main/pages/wlist.tsx

今回NodeやTypeScriptを使っていて非同期か同期かの違いで挙動を確認するのに時間がかかりました。特にDB接続や外部へのHTTP通信などは非同期で動きコールバックで結果を受け取るような仕様になっていますし、非同期の処理において対処する方法がいくつかあるので最適な方法を選択できるように選択できる基準と実績を作っておきたい。

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