Files
2023-08-15 14:45:40 -05:00

88 lines
2.7 KiB
Go

package characterapi
import (
"context"
character "crossnokaye-interview-assignment/services/character/gen/character"
"fmt"
"log"
)
// character service example implementation.
// The example methods log the requests and return zero values.
type charactersrvc struct {
logger *log.Logger
characters *map[string]*character.Character
}
// NewCharacter returns the character service implementation.
func NewCharacter(logger *log.Logger) character.Service {
characterMap := make(map[string]*character.Character)
return &charactersrvc{logger, &characterMap}
}
// GetCharacter implements getCharacter.
func (s *charactersrvc) GetCharacter(ctx context.Context, p *character.GetCharacterPayload) (res *character.Character, err error) {
s.logger.Print("character.getCharacter")
itemToGet := (*s.characters)[*p.Name]
if itemToGet == nil {
s.logger.Printf("character with id '%s' not found", *p.Name)
return nil, character.MakeNotFound(fmt.Errorf("character with id '%s' not found", *p.Name))
}
res = (*s.characters)[*p.Name]
return
}
func (s *charactersrvc) ListCharacters(ctx context.Context) (res []*character.Character, err error) {
for _, value := range *s.characters {
res = append(res, value)
}
return
}
// CreateCharacter implements createCharacter.
func (s *charactersrvc) CreateCharacter(ctx context.Context, p *character.Character) (res *character.Character, err error) {
s.logger.Print("character.createCharacter")
existingCharacter := (*s.characters)[p.Name]
if existingCharacter != nil {
s.logger.Printf("character with name %s already exists", p.Name)
return nil, character.MakeAlreadyExists(fmt.Errorf("character with name %s already exists", p.Name))
}
(*s.characters)[p.Name] = p
res = (*s.characters)[p.Name]
return
}
// UpdateCharacter implements updateCharacter.
func (s *charactersrvc) UpdateCharacter(ctx context.Context, p *character.Character) (res *character.Character, err error) {
s.logger.Print("character.updateCharacter")
itemToUpdate := (*s.characters)[p.Name]
if itemToUpdate == nil {
s.logger.Printf("character with id '%s' not found", p.Name)
return nil, character.MakeNotFound(fmt.Errorf("character with id '%s' not found", p.Name))
}
(*s.characters)[p.Name] = p
res = (*s.characters)[p.Name]
return
}
// DeleteCharacter implements deleteCharacter.
func (s *charactersrvc) DeleteCharacter(ctx context.Context, p *character.DeleteCharacterPayload) (err error) {
s.logger.Print("character.deleteCharacter")
itemToDelete := (*s.characters)[*p.Name]
if itemToDelete == nil {
s.logger.Printf("character with id '%s' not found", *p.Name)
return character.MakeNotFound(fmt.Errorf("character with id '%s' not found", *p.Name))
}
delete(*s.characters, *p.Name)
return
}