Files
crossnokaye-interview-assig…/services/inventory/inventory.go
2023-08-15 14:45:40 -05:00

89 lines
2.5 KiB
Go

package inventoryapi
import (
"context"
inventory "crossnokaye-interview-assignment/services/inventory/gen/inventory"
"fmt"
"log"
)
// inventory service example implementation.
// The example methods log the requests and return zero values.
type inventorysrvc struct {
logger *log.Logger
inventories *map[string]*[]string //key = characterId, value = array of itemIds
}
// NewInventory returns the inventory service implementation.
func NewInventory(logger *log.Logger) inventory.Service {
inventoryMap := make(map[string]*[]string)
return &inventorysrvc{logger, &inventoryMap}
}
// AddItem implements addItem.
func (s *inventorysrvc) AddItem(ctx context.Context, p *inventory.InventoryRecord) (err error) {
s.logger.Print("inventory.addItem")
itemList := (*s.inventories)[p.CharacterName]
if itemList == nil {
itemList = s.initCharacterInventory(p.CharacterName)
}
newItemList := append(*itemList, p.ItemName)
(*s.inventories)[p.CharacterName] = &newItemList
return
}
// RemoveItem implements removeItem.
func (s *inventorysrvc) RemoveItem(ctx context.Context, p *inventory.InventoryRecord) (err error) {
s.logger.Print("inventory.removeItem")
itemList := (*s.inventories)[p.CharacterName]
if itemList == nil {
s.logger.Printf("inventory for character with name '%s' not found", p.CharacterName)
return inventory.MakeNotFound(fmt.Errorf("inventory for character with name '%s' not found", p.CharacterName))
}
idx := indexOf(p.ItemName, *itemList)
if idx != -1 {
newItemList := remove(*itemList, idx)
(*s.inventories)[p.CharacterName] = &newItemList
} else {
s.logger.Printf("character with name '%s' does not have item '%s' in inventory", p.CharacterName, p.ItemName)
return inventory.MakeNotFound(fmt.Errorf("character with name '%s' does not have item '%s' in inventory",
p.CharacterName, p.ItemName))
}
return
}
func (s *inventorysrvc) ListInventory(ctx context.Context, payload *inventory.ListInventoryPayload) (res []string, err error) {
if (*s.inventories)[*payload.CharacterName] == nil {
return nil, nil
}
res = *((*s.inventories)[*payload.CharacterName])
return
}
func (s *inventorysrvc) initCharacterInventory(characterName string) (itemList *[]string) {
list := make([]string, 0)
itemList = &list
(*s.inventories)[characterName] = itemList
return
}
func indexOf(element string, data []string) int {
for k, v := range data {
if element == v {
return k
}
}
return -1 //not found.
}
func remove(s []string, i int) []string {
s[i] = s[len(s)-1]
return s[:len(s)-1]
}