forked from short-d/short
-
Notifications
You must be signed in to change notification settings - Fork 1
/
apikey.go
81 lines (72 loc) · 1.97 KB
/
apikey.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package sqldb
import (
"database/sql"
"errors"
"fmt"
"time"
"github.com/primedata-ai/short/backend/app/adapter/sqldb/table"
"github.com/primedata-ai/short/backend/app/entity"
"github.com/primedata-ai/short/backend/app/usecase/repository"
)
var _ repository.APIKey = (*APIKeySQL)(nil)
// APIKeySQL accesses APIKey from the database through SQL.
type APIKeySQL struct {
db *sql.DB
}
// GetAPIKey fetches APIKey from APIKey table using SQL.
func (a APIKeySQL) GetAPIKey(appID string, key string) (entity.APIKey, error) {
query := fmt.Sprintf(`
SELECT "%s", "%s"
FROM "%s" WHERE "%s"=$1 AND "%s"=$2;
`,
table.APIKey.ColumnDisabled,
table.APIKey.ColumnCreatedAt,
table.APIKey.TableName,
table.APIKey.ColumnAppID,
table.APIKey.ColumnKey,
)
apiKey := entity.APIKey{}
err := a.db.QueryRow(query, appID, key).Scan(&apiKey.IsDisabled, &apiKey.CreatedAt)
if err == nil {
apiKey.AppID = appID
apiKey.Key = key
return apiKey, nil
}
if errors.Is(err, sql.ErrNoRows) {
return entity.APIKey{},
repository.ErrEntryNotFound(
fmt.Sprintf("appID(%s) and key(%s) not found", appID, key))
}
return entity.APIKey{}, err
}
// CreateAPIKey appends a new APIKey entry to APIKey table using SQL.
func (a APIKeySQL) CreateAPIKey(input entity.APIKeyInput) (entity.APIKey, error) {
stmt := fmt.Sprintf(`
INSERT INTO "%s"("%s", "%s", "%s", "%s")
VALUES ($1, $2, $3, $4);
`,
table.APIKey.TableName,
table.APIKey.ColumnAppID,
table.APIKey.ColumnKey,
table.APIKey.ColumnDisabled,
table.APIKey.ColumnCreatedAt,
)
isDisabled := input.GetIsDisabled(false)
_, err := a.db.Exec(
stmt,
input.GetAppID(""),
input.GetKey(""),
SQLBool(isDisabled),
input.GetCreatedAt(time.Time{}),
)
return entity.APIKey{
AppID: input.GetAppID(""),
Key: input.GetKey(""),
IsDisabled: isDisabled,
CreatedAt: input.GetCreatedAt(time.Time{}),
}, err
}
// NewAPIKeySQL creates database access object for APIKey.
func NewAPIKeySQL(db *sql.DB) APIKeySQL {
return APIKeySQL{db: db}
}