Sumor Cloud のツール。
詳細なドキュメント
MySQLなどのデータベースコネクタ。エンティティに基づいています。
npm i @sumor/database --save
Node.js バージョン16.x以上が必要です。
このパッケージはESモジュールで書かれているため、package.jsonファイルで以下のコードを変更してください。
{
  "type": "module"
}
import database from '@sumor/database'
const config = {
  host: 'localhost',
  user: 'root',
  password: 'password',
  database: 'database',
  port: 3306
}
await database.install(config, {
  entity: {
    Car: {
      property: {
        brand: {
          type: 'string',
          length: 100
        },
        model: {
          type: 'string',
          length: 100
        }
      }
    }
  },
  view: {}
})
// 接続プールを持つクライアントを取得
const client = await database.client(config)
// 接続を取得
const db = await client.connect()
// 操作ユーザーを設定
db.setUser('tester')
// レコードを作成
const car1Id = await db.insert('Car', {
  brand: 'BMW',
  model: 'X5'
})
const car2Id = await db.insert('Car', {
  brand: 'BMW',
  model: 'X6'
})
// レコードを読む
const car = await db.single('Car', { id: carId })
// car = {id: car1Id, brand: 'BMW', model: 'X5'}
// レコードをクエリ
const cars = await db.query('Car', {
  brand: 'BMW'
})
// cars = [{id: car1Id, brand: 'BMW', model: 'X5'}, {id: car2Id, brand: 'BMW', model: 'X6'}]
// レコードを数える
const count = await db.count('Car', {
  brand: 'BMW'
})
// count = 2
// レコードを更新
await db.update(
  'Car',
  { id: car1Id },
  {
    brand: 'BMW',
    model: 'X5M'
  }
)
// レコードを確認
await db.ensure('Car', ['brand'], {
  brand: 'BMW',
  model: 'X5C'
})
// brandが既に 'BMW' という値を持つレコードが存在する場合、レコードは挿入されません
// レコードを変更
await db.modify('Car', ['brand'], {
  brand: 'BMW',
  model: 'X5C'
})
// brandが既に 'BMW' という値を持つレコードが存在する場合、レコードのモデルを更新します
// レコードを削除
await db.delete('Car', { id: car1Id })
// 接続を切断
await db.commit()
// ロールバック
await db.rollback()
// 接続を切断
await db.release()
// サーバーをシャットダウンする際にクライアントを破棄
await client.destroy()
// オプションでレコードをクエリ
const cars = await db.select(
  'Car',
  {
    brand: 'BMW'
  },
  {
    term: 'X5',
    termRange: ['model'],
    top: 10,
    skip: 0
  }
)