articles-api/service/shortener/model.go

72 lines
1.3 KiB
Go
Raw Normal View History

package shortener
import (
"errors"
)
// Model represents an actual tiny url entry in the database.
type Model struct {
2019-05-02 18:50:58 +00:00
tiny string
long string
}
// storage contains entries
var storage []*Model = make([]*Model, 0)
2019-05-02 18:50:58 +00:00
// NewModel builds a tiny model from arguments
func NewModel(tiny string, long string) *Model {
return &Model{
2019-05-02 18:50:58 +00:00
tiny: tiny,
long: long,
}
}
// Search for model in storage
func (mod *Model) Search() error {
for _, row := range storage {
if row.tiny == mod.tiny {
mod.tiny = row.tiny
mod.long = row.long
return nil
}
}
return errors.New("not found")
}
// Create the model in storage
func (mod *Model) Create() error {
// fail if already exists
if mod.Search() == nil {
return errors.New("already exists")
}
storage = append(storage, mod)
2019-05-02 18:50:58 +00:00
return nil
}
// Update the model in storage
func (mod *Model) Update() error {
for _, row := range storage {
if row.tiny == mod.tiny {
row.tiny = mod.tiny
row.long = mod.long
return nil
}
}
2019-05-02 18:50:58 +00:00
return errors.New("not found")
2019-05-02 18:50:58 +00:00
}
// Delete the model from storage
func (mod *Model) Delete() error {
for i, row := range storage {
if row.tiny == mod.tiny && row.long == mod.long {
storage = append(storage[:i], storage[i+1:]...)
return nil
}
}
return errors.New("not found")
}