-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
d852628
commit cd2b825
Showing
2 changed files
with
60 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
package db | ||
|
||
import ( | ||
"time" | ||
|
||
"gorm.io/gorm" | ||
) | ||
|
||
// TURL is the table of tiny-url | ||
type TURL struct { | ||
gorm.Model | ||
LongURL string `gorm:"type:varchar;not null;unique" json:"long_url"` | ||
} | ||
|
||
// TinyURL is the interface of tiny-url table | ||
type TinyURL interface { | ||
Insert(shortID uint, longURL string) error | ||
GetByShortID(shortID uint) (*TURL, error) | ||
} | ||
|
||
// tinyURL is the implementation of TinyURL | ||
type tinyURL struct { | ||
conn *gorm.DB | ||
} | ||
|
||
// NewTinyURL returns a new TinyURL | ||
func NewTinyURL(dsn string) (TinyURL, error) { | ||
conn, err := NewDB(dsn) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
return &tinyURL{conn: conn}, nil | ||
} | ||
|
||
func (db *tinyURL) Insert(shortID uint, longURL string) error { | ||
t := TURL{ | ||
Model: gorm.Model{ | ||
ID: shortID, | ||
CreatedAt: time.Now(), | ||
}, | ||
LongURL: longURL, | ||
} | ||
|
||
return db.conn.Create(&t).Error | ||
} | ||
|
||
func (db *tinyURL) GetByShortID(shortID uint) (*TURL, error) { | ||
var t TURL | ||
if err := db.conn.First(&t, shortID).Error; err != nil { | ||
return nil, err | ||
} | ||
|
||
return &t, nil | ||
} |