2024-06-24 23:34:10 +00:00
|
|
|
package storage
|
|
|
|
|
|
|
|
import (
|
2024-06-26 01:45:04 +00:00
|
|
|
"context"
|
|
|
|
"fmt"
|
2024-06-25 00:19:53 +00:00
|
|
|
"log"
|
2024-06-24 23:34:10 +00:00
|
|
|
"os"
|
|
|
|
|
|
|
|
"git.obamna.ru/erius/ozon-task/graph/model"
|
|
|
|
"git.obamna.ru/erius/ozon-task/internal/storage/db"
|
|
|
|
)
|
|
|
|
|
2024-06-26 01:45:04 +00:00
|
|
|
type IDNotFoundError struct {
|
|
|
|
objName string
|
|
|
|
id uint
|
|
|
|
}
|
|
|
|
|
|
|
|
func (e *IDNotFoundError) Error() string {
|
|
|
|
return fmt.Sprintf("%s with id %d doesn't exist", e.objName, e.id)
|
|
|
|
}
|
|
|
|
|
|
|
|
// storage types enum
|
2024-06-24 23:34:10 +00:00
|
|
|
const (
|
|
|
|
inMemory = "inmemory"
|
|
|
|
postgres = "postgres"
|
|
|
|
)
|
|
|
|
|
2024-06-26 01:45:04 +00:00
|
|
|
var storage, storageSpecified = os.LookupEnv("APP_STORAGE")
|
2024-06-24 23:34:10 +00:00
|
|
|
|
|
|
|
type Storage interface {
|
|
|
|
AddPost(input *model.PostInput) (*model.AddResult, error)
|
2024-06-26 01:45:04 +00:00
|
|
|
|
|
|
|
// assumes that input.ParentCommentID is not nil
|
|
|
|
AddReplyToComment(input *model.CommentInput) (*model.AddResult, error)
|
|
|
|
|
|
|
|
// assumes that input.ParentPostID is not nil
|
|
|
|
AddCommentToPost(input *model.CommentInput) (*model.AddResult, error)
|
|
|
|
|
|
|
|
// passing query context to analyze requested fields and prevent overfetching
|
|
|
|
GetPost(id uint, ctx context.Context) (*model.Post, error)
|
|
|
|
GetComment(id uint, ctx context.Context) (*model.Comment, error)
|
|
|
|
|
|
|
|
// returns paginated data in the form of model.*Connection (passing context to prevent overfetching)
|
2024-06-27 01:28:18 +00:00
|
|
|
GetPosts(first uint, cursor *uint, ctx context.Context) (*model.PostsConnection, error)
|
|
|
|
GetComments(post *model.Post, first uint, cursor *uint, ctx context.Context) (*model.CommentsConnection, error)
|
|
|
|
GetReplies(comment *model.Comment, first uint, cursor *uint, ctx context.Context) (*model.CommentsConnection, error)
|
2024-06-24 23:34:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func InitStorage() (Storage, error) {
|
2024-06-26 01:45:04 +00:00
|
|
|
if !storageSpecified {
|
|
|
|
log.Println("APP_STORAGE isn't specified, falling back to default in-memory storage", storage)
|
|
|
|
return InitInMemory(), nil
|
|
|
|
}
|
2024-06-25 00:19:53 +00:00
|
|
|
log.Printf("initializing storage of type %s...", storage)
|
2024-06-24 23:34:10 +00:00
|
|
|
switch storage {
|
|
|
|
case inMemory:
|
|
|
|
return InitInMemory(), nil
|
|
|
|
case postgres:
|
|
|
|
return db.InitPostgres()
|
|
|
|
default:
|
2024-06-26 01:45:04 +00:00
|
|
|
return nil, fmt.Errorf("storage of type %s doesn't exists, change the value of APP_STORAGE env variable", storage)
|
2024-06-24 23:34:10 +00:00
|
|
|
}
|
|
|
|
}
|