0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

TypeORM+Expressjsでお手軽バックエンドサーバ構築

Last updated at Posted at 2021-06-27

ソースコードはこちら

TypeORM+ExpressでMySQLに接続するRESTAPIを作成してみました。

実行手順

docker compose up
npm i
npm run start

ファイル構成

ファイル構成
.
├── src
│   ├── entity
│   │   └── User.ts
│   └── index.ts
├── docker
│   ├── data
│   └── my.cnf
├── docker-compose.yml
├── ormconfig.json
├── package-lock.json
├── package.json
└── tsconfig.json

typeorm initで作成したものをベースとしています。

index.ts

index.ts
import "reflect-metadata";
import {getConnectionOptions, createConnection, BaseEntity, getManager} from 'typeorm'
import {User} from "./entity/User";
import * as express from 'express'


let app = async () => {
    const app= express();
    const connection = await createConnection()
    const manager = await getManager();
    app.get('/', async (req, res) => {
        const user = new User()
        user.firstName = 'Qiita'
        user.lastName = "test"
        user.age=25
        user.name="test"
        await manager.save(user)
        const users = await manager.findOne(User,1);
        res.send(users)
    })
    app.listen(3000, () => console.log('Example app listening on port 3000!'))
}
app();

localhost:3000にアクセスするたびにuserが増えていきます。
reflect-metadataに関してはこちらの記事が参考になります。

User.ts

User.ts
import {Entity, PrimaryGeneratedColumn, Column} from "typeorm";

@Entity()
export class User {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    firstName: string;

    @Column()
    lastName: string;

    @Column()
    age: number;

    @Column()
    name: string;

}

テーブル定義はこのファイルで行います。

ormconfig.json

ormconfig.json
{
   "type": "mysql",
   "host": "127.0.0.1",
   "port": 3308,
   "username": "root",
   "password": "root",
   "database": "test_database",
   "synchronize": true,
   "logging": false,
   "entities": [
      "src/entity/**/*.ts"
   ],
   "migrations": [
      "src/migration/**/*.ts"
   ],
   "subscribers": [
      "src/subscriber/**/*.ts"
   ],
   "cli": {
      "entitiesDir": "src/entity",
      "migrationsDir": "src/migration",
      "subscribersDir": "src/subscriber"
   }
}

"synchronize": trueを設定する事によって、マイグレーションをしなくてもAPIを叩いたときにユーザーテーブルが自動に作成されます。開発時には便利ですが、本番環境ではfalseが推奨されています。

docker-compose.yml

docker-compose.yml
services:
  # MySQL
  db:
    image: mysql:5.7
    container_name: mysql_host
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_DATABASE: test_database
      MYSQL_USER: docker
      MYSQL_PASSWORD: docker
      TZ: 'Asia/Tokyo'
    command: mysqld --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci
    volumes:
      - ./docker/data:/var/lib/mysql
      - ./docker/my.cnf:/etc/mysql/conf.d/my.cnf
    ports:
      - 3308:3306

MySQL用のdocker-composeファイルです。

まとめ

多分これが一番お手軽だと思います。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?