Debian Codegraph @

examples/storage/storage_user.go

raw
1 package storage
2
3 import (
4 "errors"
5 "fmt"
6 "net/http"
7
8 "github.com/manyminds/api2go"
9 "github.com/manyminds/api2go/examples/model"
10 )
11
12 // NewUserStorage initializes the storage
13 func NewUserStorage() *UserStorage {
14 return &UserStorage{make(map[string]*model.User), 1}
15 }
16
17 // UserStorage stores all users
18 type UserStorage struct {
19 users map[string]*model.User
20 idCount int
21 }
22
23 // GetAll returns the user map (because we need the ID as key too)
24 func (s UserStorage) GetAll() map[string]*model.User {
25 return s.users
26 }
27
28 // GetOne user
29 func (s UserStorage) GetOne(id string) (model.User, error) {
30 user, ok := s.users[id]
31 if ok {
32 return *user, nil
33 }
34 errMessage := fmt.Sprintf("User for id %s not found", id)
35 return model.User{}, api2go.NewHTTPError(errors.New(errMessage), errMessage, http.StatusNotFound)
36 }
37
38 // Insert a user
39 func (s *UserStorage) Insert(c model.User) string {
40 id := fmt.Sprintf("%d", s.idCount)
41 c.ID = id
42 s.users[id] = &c
43 s.idCount++
44 return id
45 }
46
47 // Delete one :(
48 func (s *UserStorage) Delete(id string) error {
49 _, exists := s.users[id]
50 if !exists {
51 return fmt.Errorf("User with id %s does not exist", id)
52 }
53 delete(s.users, id)
54
55 return nil
56 }
57
58 // Update a user
59 func (s *UserStorage) Update(c model.User) error {
60 _, exists := s.users[c.ID]
61 if !exists {
62 return fmt.Errorf("User with id %s does not exist", c.ID)
63 }
64 s.users[c.ID] = &c
65
66 return nil
67 }