前回
DataSourceの作成
エンティティが完成したら、DataSourceを作成します。
src/data-source.ts
import "reflect-metadata"; import { DataSource } from "typeorm"; import { Photo } from "./entity/Photo"; export const AppDataSource = new DataSource({ type: "mysql", host: "localhost", port: 3306, username: "test", password: "test", database: "test", synchronize: true, logging: true, entities: [Photo], migrations: [], subscribers: [], });
src/index.ts
import { AppDataSource } from "./data-source"; AppDataSource.initialize() .then(() => {}) .catch((error) => { console.log(error); });
Photoをentitiesに設定しています。
また、synchronizeオプションにより、アプリケーションを実行するたびにエンティティがデータベースと同期されます。
アプリケーションを実行
npm start
を実行して、アプリケーションを実行することができます。
$ docker-compose up -d $ npm start
データベースを見てみます。
$ docker-compose exec mysql bash
bash-4.4# mysql -u test -p Enter password: Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 10 Server version: 8.0.32 MySQL Community Server - GPL Copyright (c) 2000, 2023, Oracle and/or its affiliates. Oracle is a registered trademark of Oracle Corporation and/or its affiliates. Other names may be trademarks of their respective owners. Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
mysql> show databases; +--------------------+ | Database | +--------------------+ | information_schema | | performance_schema | | test | +--------------------+ 3 rows in set (0.00 sec)
mysql> use test Reading table information for completion of table and column names You can turn off this feature to get a quicker startup with -A Database changed mysql> show tables -> ; +----------------+ | Tables_in_test | +----------------+ | photo | | user | +----------------+ 2 rows in set (0.01 sec)
mysql> show columns from photo; +-------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +-------------+--------------+------+-----+---------+----------------+ | id | int | NO | PRI | NULL | auto_increment | | name | varchar(100) | NO | | NULL | | | description | text | NO | | NULL | | | filename | varchar(255) | NO | | NULL | | | views | double | NO | | NULL | | | isPublished | tinyint | NO | | NULL | | +-------------+--------------+------+-----+---------+----------------+ 6 rows in set (0.00 sec)
テーブルが作成されています。
まとめ
ここまでで、
- DataSourceの作成について
- アプリケーションを実行について
を学びました。
次回はphotoの作成を掘り下げようと思います。
コード
今回のコードは、以下に格納しました。