## 経緯
[[Bruno]]を使ったテストは基本全てAPIベースである。参照系APIは問題ないが、更新系APIはDBなどの結果を確認したいケースも出てくる。APIを作成して取得したい。
## 前提
- ローカルで実行できればOK
- DBはローカルで[[Docker]]を利用する
- 今回は[[MySQL]]を使う
- [[Bruno]]は[[Windows 11]]にインストールされている
- [[Docker]]は[[WSL]]内で起動する
- [[Bruno]]のコレクション読み込みプロジェクトは[[WSL]]内
- できればデータは[[JSON]]で取得したい
## MySQLコンテナの作成
[[Docker ComposeでMySQLコンテナを作成]]する。
## Brunoプロジェクトの作成
`~/tmp/bruno-mysql-test` を作成。
```console
.
└── bruno.json
```
`test`という名前のリクエストを作成する。
- URLは `http://localhost:8000?table=users`
モードを聞かれるので `Developer Mode` を選択する。
## Denoのサーバースクリプト作成
> [!todo]
> 動くやり方に変更する
`table`を指定するとすべてselectするシンプルなスクリプト。
```
.
├── bruno.json
├── conf.d
│ └── my.cnf
├── docker-compose.yml
├── docker-entrypoint-initdb.d
│ └── init.sql
├── src
│ └── main.ts
└── test.bru
```
`src/main.ts`
```ts
import { Client } from "https://deno.land/x/mysql/mod.ts";
const client = await new Client().connect({
hostname: "db",
port: 3306,
username: "user",
db: "bruno",
password: "password",
});
async function handler(request: Request): Promise<Response> {
const url = new URL(request.url);
const table = url.searchParams.get("table");
const result = await client.execute(`select * from ??`, [table]);
return Response.json(result.rows);
}
Deno.serve(handler);
```
`docker-entrypoint-initdb.d/init.sql`
```sql
CREATE USER 'user'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'user'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;
CREATE DATABASE IF NOT EXISTS bruno;
USE bruno;
CREATE TABLE users (
id int NOT NULL,
name varchar(255) NOT NULL
) ENGINE=InnoDB;
INSERT INTO users VALUES (1,'one'),(2,'two'),(3,'three');
```
`conf.d/my.cnf`
```ini
[mysqld]
character-set-server=utf8mb4
collation-server=utf8mb4_bin
explicit-defaults-for-timestamp=1
general-log=1
general-log-file=/var/log/mysql/mysqld.log
local-infile=1
[mysql]
default-character-set=utf8mb4
local-infile=1
```
`docker-compose.yml`
```yaml
version: "3.1"
services:
db:
image: mysql:8
container_name: mysql-sample
restart: always
ports:
- 13306:3306
volumes:
- ./conf.d:/etc/mysql/conf.d
- ./docker-entrypoint-initdb.d:/docker-entrypoint-initdb.d
environment:
MYSQL_ROOT_PASSWORD: example
dbserver:
image: denoland/deno:2.1.0
container_name: mysql-sample-server
restart: always
ports:
- 18000:8000
depends_on:
- db
volumes:
- ./src:/app
command: ["run", "--allow-net", "/app/main.ts"]
```