プラグインの作成

コールバック

GORMは、そのコア機能を実現するためにコールバックを利用しています。これらのコールバックは、CreateQueryUpdateDeleteRowRawなど、様々なデータベース操作のフックを提供し、GORMの動作を幅広くカスタマイズできます。

コールバックは、セッション単位ではなく、グローバルな*gorm.DBレベルで登録されます。つまり、異なるコールバックの動作が必要な場合は、別の*gorm.DBインスタンスを初期化する必要があります。

コールバックの登録

特定の操作に対するコールバックを登録できます。例えば、カスタムの画像クロッピング機能を追加するには

func cropImage(db *gorm.DB) {
if db.Statement.Schema != nil {
// crop image fields and upload them to CDN, dummy code
for _, field := range db.Statement.Schema.Fields {
switch db.Statement.ReflectValue.Kind() {
case reflect.Slice, reflect.Array:
for i := 0; i < db.Statement.ReflectValue.Len(); i++ {
// Get value from field
if fieldValue, isZero := field.ValueOf(db.Statement.Context, db.Statement.ReflectValue.Index(i)); !isZero {
if crop, ok := fieldValue.(CropInterface); ok {
crop.Crop()
}
}
}
case reflect.Struct:
// Get value from field
if fieldValue, isZero := field.ValueOf(db.Statement.Context, db.Statement.ReflectValue); !isZero {
if crop, ok := fieldValue.(CropInterface); ok {
crop.Crop()
}
}

// Set value to field
err := field.Set(db.Statement.Context, db.Statement.ReflectValue, "newValue")
}
}

// All fields for current model
db.Statement.Schema.Fields

// All primary key fields for current model
db.Statement.Schema.PrimaryFields

// Prioritized primary key field: field with DB name `id` or the first defined primary key
db.Statement.Schema.PrioritizedPrimaryField

// All relationships for current model
db.Statement.Schema.Relationships

// Find field with field name or db name
field := db.Statement.Schema.LookUpField("Name")

// processing
}
}

// Register the callback for the Create operation
db.Callback().Create().Register("crop_image", cropImage)

コールバックの削除

コールバックが不要になった場合は、削除できます。

// Remove the 'gorm:create' callback from Create operations
db.Callback().Create().Remove("gorm:create")

コールバックの置換

同じ名前のコールバックは、新しい関数で置き換えることができます。

// Replace the 'gorm:create' callback with a new function
db.Callback().Create().Replace("gorm:create", newCreateFunction)

コールバックの順序

コールバックは、特定の順序で登録することで、操作ライフサイクルの適切なタイミングで実行されるようにできます。

// Register to execute before the 'gorm:create' callback
db.Callback().Create().Before("gorm:create").Register("update_created_at", updateCreated)

// Register to execute after the 'gorm:create' callback
db.Callback().Create().After("gorm:create").Register("update_created_at", updateCreated)

// Register to execute after the 'gorm:query' callback
db.Callback().Query().After("gorm:query").Register("my_plugin:after_query", afterQuery)

// Register to execute after the 'gorm:delete' callback
db.Callback().Delete().After("gorm:delete").Register("my_plugin:after_delete", afterDelete)

// Register to execute before the 'gorm:update' callback
db.Callback().Update().Before("gorm:update").Register("my_plugin:before_update", beforeUpdate)

// Register to execute before 'gorm:create' and after 'gorm:before_create'
db.Callback().Create().Before("gorm:create").After("gorm:before_create").Register("my_plugin:before_create", beforeCreate)

// Register to execute before any other callbacks
db.Callback().Create().Before("*").Register("update_created_at", updateCreated)

// Register to execute after any other callbacks
db.Callback().Create().After("*").Register("update_created_at", updateCreated)

プリ定義されたコールバック

GORMには、標準機能を駆動するプリ定義されたコールバックのセットが用意されています。カスタムプラグインや追加のコールバック関数を作成する前に、これらの定義済みのコールバックを確認することをお勧めします。

プラグイン

GORMのプラグインシステムにより、コア機能を容易に拡張およびカスタマイズし、モジュール式のアーキテクチャを維持しながらアプリケーションの機能を強化できます。

Pluginインターフェース

GORMのプラグインを作成するには、Pluginインターフェースを実装する構造体を定義する必要があります。

type Plugin interface {
Name() string
Initialize(*gorm.DB) error
}
  • Nameメソッド: プラグインの一意の文字列識別子を返します。
  • Initializeメソッド: プラグインの設定ロジックを含みます。このメソッドは、プラグインが初めてGORMに登録されたときに呼び出されます。

プラグインの登録

プラグインがPluginインターフェースに準拠したら、GORMインスタンスに登録できます。

// Example of registering a plugin
db.Use(MyCustomPlugin{})

登録済みプラグインへのアクセス

プラグインが登録されると、GORMの設定に保存されます。登録済みプラグインには、Pluginsマップからアクセスできます。

// Access a registered plugin by its name
plugin := db.Config.Plugins[pluginName]

実践例

GORMプラグインの例として、PrometheusモニタリングをGORMと統合するPrometheusプラグインがあります。

// Registering the Prometheus plugin
db.Use(prometheus.New(prometheus.Config{
// Configuration options here
}))

Prometheusプラグインのドキュメントには、その実装と使用方法に関する詳細な情報が記載されています。

プラチナスポンサー

ゴールドスポンサー

プラチナスポンサー

ゴールドスポンサー