Melkeydev / go-blueprint

Go-blueprint allows users to spin up a quick Go project using a popular framework
https://docs.go-blueprint.dev/
MIT License
3.77k stars 237 forks source link

[Feature Request] Modify Model DB Interface for CRUD Operations #253

Open Melkeydev opened 3 months ago

Melkeydev commented 3 months ago

Tell us about your feature request

Modify the DB interface to show people how to make crud operations

Disclaimer

nahaktarun commented 1 month ago

Hi @Melkeydev I want to take this issue and want to work on it. Can you please help to provide more information about the issue.

Ujstor commented 3 weeks ago

@nahaktarun @Melkeydev wouldn’t mind if you worked on this. Let me know, and I can assign it to you.

Ujstor commented 3 weeks ago

The idea is to provide a basic example of how to interact with the database, how abstraction is done, and how functions that interact with the database are later referenced in other packages. There have been many questions around this topic.

This is just an example of how I envision this; it can be done in other ways.

database/models.go

package database

type Todo struct {
    Id uint64 `json:"id"`
    Todo string `json:"todo"`
}

func (s *service) CreateTodo(todo string) error {

    statment := `INSERT INTO todos(todo, done) values($1, $2);`
    _, err := s.db.Query(statment, todo)
    return err
}

func (s *service) GetTodo(id uint64) (Todo, error) {
    statement := `SELECT todo, done FROM todos WHERE id=$1;`

    var todo Todo
    todo.Id = id

    row := s.db.QueryRow(statement, id)
    err := row.Scan(&todo.Todo)
    if err != nil {
        return todo, err
    }

    return todo, nil
}

database.go

type Service interface {
       Health() map[string]string
    CreateTodo(todo string) error
        GetTodo(id uint64) (Todo, error)
}

server/server.go

type Server struct {
    port int
    db   database.Service
}

A database migration tool would also be nice for creating a test table in the database:

-- +goose Up
CREATE TABLE "todos" (
    "id" SERIAL NOT NULL,
    "todo" VARCHAR(255),
    PRIMARY KEY ("id")
);

-- +goose Down
DROP TABLE "todos";

We can also add simple API endpoints in routes.go that can be hit with curl to add , retrieve, delete etc. data from db.

Now, the tricky part is that it needs to be done for all databases specified in the --driver flag. Additionally, good documentation needs to be written.

Tests would be nice, but they're not mandatory.


Update

I was thinking, and we should maybe include this as an advanced flag. The blueprint's core features are currently in a good spot, not too bloated. CRUD endpoints can be placed in a separate file within the server package for better readability. I am open for suggestions and ideas.

Samarthasbhat commented 2 days ago

Hi @Ujstor Do we need to add CRUD operations for the TODO? Can you explain more about API endpoints in the routes.go?