This repository was archived by the owner on Aug 19, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathdatabase.go
More file actions
80 lines (67 loc) · 1.54 KB
/
database.go
File metadata and controls
80 lines (67 loc) · 1.54 KB
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
68
69
70
71
72
73
74
75
76
77
78
79
80
// Package database provides methods for interacting with Repl.it Database.
// It just works if used within a repl.
package database
import (
"sync"
"time"
)
var defaultClient = struct {
sync.Mutex
c *client
o sync.Once
creationTime time.Time
}{}
const (
refreshInterval = 1 * time.Hour
)
func getClient() (*client, error) {
defaultClient.Lock()
defer defaultClient.Unlock()
// if the client hasn't been updated in 1h, refresh it
if time.Since(defaultClient.creationTime) >= refreshInterval {
defaultClient.c = nil
}
if defaultClient.c == nil {
c, err := newClient()
if err != nil {
return nil, err
}
defaultClient.c = c
defaultClient.creationTime = time.Now()
}
return defaultClient.c, nil
}
// Get returns the value for the provided key. It returns ErrNotFound if the key
// does not exist.
func Get(key string) (string, error) {
c, err := getClient()
if err != nil {
return "", err
}
return c.Get(key)
}
// Set creates or updates the provided key with the provided value.
func Set(key, value string) error {
c, err := getClient()
if err != nil {
return err
}
return c.Set(key, value)
}
// Delete removes the provided key.
func Delete(key string) error {
c, err := getClient()
if err != nil {
return err
}
return c.Delete(key)
}
// ListKeys returns a slice of all keys that begin with the provided prefix.
// They are sorted in lexicographic order.
func ListKeys(prefix string) ([]string, error) {
c, err := getClient()
if err != nil {
return nil, err
}
return c.ListKeys(prefix)
}