Generate Module
Overview
Yokai provides a fxgenerate module, allowing your application to generate UUIDs.
It wraps the generate module, based on Google UUID.
Installation
The fxgenerate module is automatically loaded by Yokai's core.
When you use a Yokai application template, you have nothing to install, it's ready to use.
Usage
This module makes available the UuidGenerator in Yokai dependency injection system.
It is built on top of Google UUID, see its documentation for more details about available methods.
To access it, you just need to inject it where needed, for example:
internal/service/example.go
package service
import (
"fmt"
"github.com/ankorstore/yokai/generate/uuid"
)
type ExampleService struct {
generator uuid.UuidGenerator
}
func NewExampleService(generator uuid.UuidGenerator) *ExampleService {
return &ExampleService{
generator: generator,
}
}
func (s *ExampleService) DoSomething() {
// uuid: dcb5d8b3-4517-4957-a42c-604d11758561
fmt.Printf("uuid: %s", s.generator.Generate())
}
Testing
This module provides the possibility to make the UuidGenerator generate deterministic values (for testing purposes).
For this, you need to:
- first provide the deterministic value to be used for generation, annotated with
name:"generate-test-uuid-value" - then override the
UuidGeneratorFactorywith the provided TestUuidGeneratorFactory
internal/service/example_test.go
package internal_test
import (
"testing"
"github.com/ankorstore/yokai/fxgenerate/fxgeneratetest/uuid"
"github.com/foo/bar/internal"
"github.com/foo/bar/internal/service"
"github.com/stretchr/testify/assert"
"go.uber.org/fx"
)
func TestExampleServiceDoSomething(t *testing.T) {
var exampleService *service.ExampleService
internal.RunTest(
t,
fx.Populate(&exampleService),
// provide and annotate the deterministic value
fx.Provide(
fx.Annotate(
func() string {
return "some value"
},
fx.ResultTags(`name:"generate-test-uuid-value"`),
),
),
// override the UuidGeneratorFactory with the TestUuidGeneratorFactory
fx.Decorate(uuid.NewFxTestUuidGeneratorFactory),
)
//assertion
assert.Equal(t, "uuid: some value", exampleService.DoSomething())
}