Add basic model

pull/8/head
isthisnagee 3 years ago
parent 4994ecf63c
commit 19d5d5f3c8

@ -0,0 +1,41 @@
/// Defines objects that interact with the db
package model
import (
"isthisnagee.com/tools/diary/db"
)
type DiaryEntry struct {
Id int `json:"id"`
Title string `json:"title"`
CreatedAt int `json:"created_at"`
Version int `json:"version"`
}
type App struct {
*db.DbCtx
}
func (app *App) NewDiaryEntry(title string) *DiaryEntry {
var diary_entry DiaryEntry
var result, err = app.Db.Exec("INSERT INTO diary_log (title) values (?);", title)
if err != nil {
panic(err)
}
id, err := result.LastInsertId()
if err != nil {
panic(err)
}
if err := app.Db.QueryRow(
"SELECT id, title, created_at, version FROM diary_log where id=?",
id,
).Scan(&diary_entry.Id, &diary_entry.Title, &diary_entry.CreatedAt, &diary_entry.Version); err != nil {
panic(err)
}
return &diary_entry
}

@ -0,0 +1,43 @@
package model
import (
"isthisnagee.com/tools/diary/db"
"testing"
)
func assert_string(t *testing.T, expected string, actual string) {
if actual != expected {
t.Fatalf("(%s, %s)", expected, actual)
}
}
func assert_exists(t *testing.T, actual interface{}) {
if actual == nil {
t.Fatalf("Unexpected nil: %s", actual)
}
}
func setup() App {
var db_ctx, err = db.Init(":memory:")
if err != nil {
panic(err)
}
return App{db_ctx}
}
func teardown(app App) {
app.Db.Close()
}
func TestNewDiaryEntry(t *testing.T) {
var app = setup()
var result = app.NewDiaryEntry("Met with Nagee @ 1PM")
assert_string(t, "Met with Nagee @ 1PM", result.Title)
assert_exists(t, result.Id)
assert_exists(t, result.CreatedAt)
assert_exists(t, result.Version)
teardown(app)
}
Loading…
Cancel
Save