fxelasticsearch

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 26, 2025 License: MIT Imports: 4 Imported by: 0

README

Fx Elasticsearch Module

ci go report codecov Deps PkgGoDev

Fx module for Elasticsearch.

Overview

This module provides to your Fx application an elasticsearch.Client, that you can inject anywhere to interact with Elasticsearch.

Installation

Install the module:

go get github.com/ankorstore/yokai-contrib/fxelasticsearch

Then activate it in your application bootstrapper:

// internal/bootstrap.go
package internal

import (
	"github.com/ankorstore/yokai-contrib/fxelasticsearch"
	"github.com/ankorstore/yokai/fxcore"
)

var Bootstrapper = fxcore.NewBootstrapper().WithOptions(
	// load modules
	fxelasticsearch.FxElasticsearchModule,
	// ...
)

Configuration

Configuration reference:

# ./configs/config.yaml
app:
  name: app
  env: dev
  version: 0.1.0
  debug: true
modules:
  elasticsearch:
    address: ${ELASTICSEARCH_ADDRESS}
    username: ${ELASTICSEARCH_USERNAME}
    password: ${ELASTICSEARCH_PASSWORD}

Notes:

  • The modules.elasticsearch.address configuration key is mandatory
  • The modules.elasticsearch.username and modules.elasticsearch.password configuration keys are optional
  • See Elasticsearch configuration documentation for more details

Testing

In test mode, an additional mock Elasticsearch client is provided with HTTP transport-level mocking capabilities.

Automatic Test Environment Support

When APP_ENV=test, the module automatically provides a default mock Elasticsearch client that returns empty successful responses. This allows your application to start and run basic tests without any additional setup.

Custom Mock Clients

For specific test scenarios, you can create custom mock clients with controlled responses:

package service_test

import (
	"context"
	"errors"
	"strings"
	"testing"

	"github.com/ankorstore/yokai-contrib/fxelasticsearch/fxelasticsearchtest"
	"github.com/stretchr/testify/assert"
)

func TestMyService_Search(t *testing.T) {
	// Define mock response
	mockResponse := `{
		"took": 5,
		"timed_out": false,
		"hits": {
			"total": {"value": 1},
			"hits": [
				{
					"_source": {"title": "Test Document", "content": "Test content"}
				}
			]
		}
	}`

	// Create mock Elasticsearch client
	esClient, err := fxelasticsearchtest.NewMockESClientWithSingleResponse(mockResponse, 200)
	assert.NoError(t, err)

	// Use the mock client in your service
	service := NewMyService(esClient)

	// Test your service methods that use Elasticsearch
	results, err := service.Search(context.Background(), "test-index", "test query")
	assert.NoError(t, err)
	assert.Len(t, results, 1)
	assert.Equal(t, "Test Document", results[0]["title"])
}

### Using Injected Mock Client in Tests

You can also use the automatically provided mock client in Fx-based tests:

```go
func TestWithFxInjection(t *testing.T) {
	t.Setenv("APP_ENV", "test")
	
	var esClient *elasticsearch.Client
	
	app := fxtest.New(
		t,
		fxconfig.FxConfigModule,
		fxelasticsearch.FxElasticsearchModule,
		fx.Populate(&esClient),
	)
	
	app.RequireStart()
	
	// The injected client is a mock that returns empty successful responses
	res, err := esClient.Search()
	assert.NoError(t, err)
	assert.Equal(t, 200, res.StatusCode)
	
	app.RequireStop()
}

See example.

Documentation

Index

Constants

View Source
const ModuleName = "elasticsearch"

ModuleName is the module name.

Variables

FxElasticsearchModule is the Fx elasticsearch module.

Functions

func NewFxElasticsearchClient

func NewFxElasticsearchClient(p FxElasticsearchClientParam) (*elasticsearch.Client, error)

NewFxElasticsearchClient returns a elasticsearch.Client. In test environment, it returns a default mock client with basic functionality. In production, it returns a real client connected to Elasticsearch.

For advanced testing scenarios, use NewMockESClient, NewMockESClientWithSingleResponse, or NewMockESClientWithError from this package to create custom mock clients.

Types

type DefaultElasticsearchClientFactory

type DefaultElasticsearchClientFactory struct {
	// contains filtered or unexported fields
}

func NewDefaultElasticsearchClientFactory

func NewDefaultElasticsearchClientFactory(config *config.Config) *DefaultElasticsearchClientFactory

func (*DefaultElasticsearchClientFactory) Create

func (f *DefaultElasticsearchClientFactory) Create() (*elasticsearch.Client, error)

type ElasticsearchClientFactory

type ElasticsearchClientFactory interface {
	Create() (*elasticsearch.Client, error)
}

type FxElasticsearchClientParam

type FxElasticsearchClientParam struct {
	fx.In
	Config  *config.Config
	Factory ElasticsearchClientFactory
}

FxElasticsearchClientParam allows injection of the required dependencies in [NewElasticsearchClient].

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL