This repository has been archived by the owner on Apr 22, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 83
/
db.go
67 lines (58 loc) · 1.45 KB
/
db.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// Copyright 2016 Claudemiro Alves Feitosa Neto. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package ipe
import (
"errors"
"sync"
)
// db represents a app database
// For now it there is only one memory database implementation
// but in the future I can write a sql implementation
type db interface {
GetAppByAppID(appID string) (*app, error)
GetAppByKey(key string) (*app, error)
AddApp(*app) error
}
// memdb is an in memory implementation of db interface
type memdb struct {
IDMutex sync.Mutex
KeyMutex sync.Mutex
AppsByAppID map[string]*app
AppsByKey map[string]*app
}
func newMemdb() *memdb {
return &memdb{
AppsByAppID: make(map[string]*app),
AppsByKey: make(map[string]*app),
}
}
func (db *memdb) AddApp(a *app) error {
db.IDMutex.Lock()
db.AppsByAppID[a.AppID] = a
db.IDMutex.Unlock()
db.KeyMutex.Lock()
db.AppsByKey[a.Key] = a
db.KeyMutex.Unlock()
return nil
}
// GetAppByAppID returns an App with by appID
func (db *memdb) GetAppByAppID(appID string) (*app, error) {
db.IDMutex.Lock()
a, ok := db.AppsByAppID[appID]
db.IDMutex.Unlock()
if ok {
return a, nil
}
return nil, errors.New("App not found")
}
// GetAppByKey returns an App with by key
func (db *memdb) GetAppByKey(key string) (*app, error) {
db.KeyMutex.Lock()
a, ok := db.AppsByKey[key]
db.KeyMutex.Unlock()
if ok {
return a, nil
}
return nil, errors.New("App not found")
}