Home > Blockchain >  Stream DB data as soon as table is changed with gRPC
Stream DB data as soon as table is changed with gRPC

Time:01-16

I am making Task List using Go, gRPC and Postgres.

How can I automatically stream the data as soon as PostItem is called to insert the new data? Do I need to subscribe the Postgres or can I accomplish this without subscription or pub-sub?


// ProtoBuf schema

syntax = "proto3";

package tasklist;

import "google/protobuf/empty.proto";

service TodoList {
  rpc GetTasks(google.protobuf.Empty) returns (stream GetTasksResponse) {}
  rpc PostItem(PostItemRequest) returns (PostTaskRequest) {}
}


message Task {
  int64 id = 1;
  string name = 2;
}

message GetTasksResponse {
  Task task = 1;
}

message PostTaskRequest {
  Task Task = 1;
}

message PostItemResponse {
  bool result = 1;
}


// Postgres Table Schema

create table Task (
  id integer not null PRIMARY KEY,
  name varchar(10) not null
);

// Go

func (s *server) GetTasks(_ *empty.Empty, stream pb.TaskList_GetTasksServer) error {
    // How can I steam data as soon as `PostTask` is called to update db? <- <-
    for _, r := range s.requests {
        // stream data
    }
}

func (s *server) PostTask(ctx context.Context, r *pb.PostTaskRequest) (*pb.PostTaskResponse, error) {
    // update Postgres here
    return &pb.PostItemResponse{Result: true}, nil
}

CodePudding user response:

I guess s.requests is something like chan Task. So after successful // update Postgres here you might send your request in chan.

func (s *server) PostTask(ctx context.Context, r *pb.PostTaskRequest) (*pb.PostTaskResponse, error) {
    postTask := toDomain(r)
    err := s.service.UpdateTask(ctx, postTask)
    if err != nil {
        return nil, status.Error(codes.Internal, err.Error())
    }
    s.requests <- postTask
    return &pb.PostItemResponse{Result: true}, nil
}
  • Related