TypeORM , node.js で操作

4 min read

概要:

TypeORMを、node.jsから使う例になります。


環境

  • TypeORM
  • node 14.17
  • Typescript

参考

https://typeorm.io/

参考のコード

https://github.com/kuc-arc-f/typeorm1

準備

npm install --save-dev typescript ts-node

npm i --save typeorm sqlite3

yarn typeorm init --database sqlite3

  • ormconfig.json, tsconfig.json が、生成されました

  • ormconfig.json: sqlite、dbfile の設定

type, database 追加しました

{
   "synchronize": true,
   "logging": false,
   "type": "sqlite",
   "database": "data/dev.sqlite",    
   "entities": [
      "src/entity/**/*.ts"
   ],
   "migrations": [
      "src/migration/**/*.ts"
   ],
   "subscribers": [
      "src/subscriber/**/*.ts"
   ],
   "cli": {
      "entitiesDir": "src/entity",
      "migrationsDir": "src/migration",
      "subscribersDir": "src/subscriber"
   }
}

  • Entity追加, /src/entity/Task.ts
Task.ts
import {
  Entity,
  Column,
  PrimaryGeneratedColumn,
  CreateDateColumn,
  UpdateDateColumn,
} from 'typeorm';

@Entity()
export class Task {
  @PrimaryGeneratedColumn()
  readonly id: number;

  @Column('varchar', { length: 255, nullable: false })
  title: string;

  @Column('text', { nullable: true })
  content: string;

  @CreateDateColumn()
  readonly created_at?: Date;

  @UpdateDateColumn()
  readonly updated_at?: Date;
}

  • migration
yarn ts-node node_modules/.bin/typeorm migration:generate -n Task

yarn ts-node node_modules/.bin/typeorm migration:run

  • 実行, 下記のような ts-node で。実行
npx ts-node src/index.ts

  • add, list : /src/t2.ts

connection.manager.save で、保存できました

manager.findで、検索できました

t2.ts
async function test(){
  const connection =  await createConnection();
  const task = new Task();
  task.title = "t2";
  task.content = "2";
  await connection.manager.save(task);
console.log(task);
  console.log("Saved id: " + task.id);
  console.log("Loading users from the database...");
  const tasks = await connection.manager.find(Task);
console.log(tasks);
}
//
test();

  • delete

getRepository 使用する例です、.remove で削除できました。

t4del.ts
async function test(){
  const connection =  await createConnection();
  const task = new Task();
  const taskRepository = getRepository(Task);
  const taskOne = await taskRepository.findOne(2);
  await taskRepository.remove(taskOne);
  const tasks = await connection.manager.find(Task);
  console.log(tasks);
}
test();

mysql版を追加

  • mysql の設定を追加しました

  • 参考の設定

https://github.com/kuc-arc-f/typeorm_2mysql
  • 準備
npm i --save typeorm mysql

yarn typeorm init --database mysql
  • db作成

ormconfig.json に、db設定が必要みたいです。

CREATE DATABASE next13 DEFAULT CHARACTER SET utf8;
grant all on next13.* to 'user1'@'localhost' identified by 'password';

ormconfig.json: username, password, databaseを設定

{
   "type": "mysql",
   "host": "localhost",
   "port": 3306,
   "username": "user1",
   "password": "password",
   "database": "next13",
   "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"
   }
}

  • テスト。 add ,select
t2.ts
async function test(){
  const connection =  await createConnection();
  const task = new Task();
  task.title = "t2";
  task.content = "2";
  await connection.manager.save(task);
console.log(task);
  console.log("Saved id: " + task.id);
  console.log("Loading users from the database...");
  const tasks = await connection.manager.find(Task);
  await connection.close();
console.log(tasks);
}
//
test();

....

Discussion

ログインするとコメントできます