Implementing a dump RPC
Course: GRPC - chapter 2
What if we could auto generate a client that a Node.js server can use and call a function on another service without worrying about the underlying axios / fetch call
rpc.ts (autogenerated)
import axios from "axios";interface Todo { id: string; title: string; description: string; completed: boolean;}
async function getTodos(): Promise<Todo[]> { const response = await axios.get(" https://sum-server.100xdevs.com/todos");
let todos = response.data.todos; return todos;}index.ts
import { getTodos } from "./rpc"const todos = await getTodos();console.log(todos);Benefits
Section titled “Benefits”- Better types - The
getTodosfunction has an associated type of the data being returned. - We are still using json, but we will fix that soon (json is slow)
- We dont need to use axios anymore, all we have to do is call a function
- If we can get
autogeneratedcode for all languages (go, rust), then this becomes language agnostice
Sample clients in other languages
Section titled “Sample clients in other languages”use reqwest::Error; // Add reqwest = { version = "0.11", features = ["blocking", "json"] } in Cargo.toml
#[derive(Debug)]struct Todo { id: String, title: String, description: String, completed: bool,}
async fn get_todos() -> Result<Vec<Todo>, Error> { let response = reqwest::get("https://sum-server.100xdevs.com/todos").await?;
let todos: Vec<Todo> = response.json().await?; Ok(todos)}import ( "encoding/json" "fmt" "io/ioutil" "net/http")
type Todo struct { ID string `json:"id"` Title string `json:"title"` Description string `json:"description"` Completed bool `json:"completed"`}
func getTodos() ([]Todo, error) { response, err := http.Get("https://sum-server.100xdevs.com/todos") if err != nil { return nil, err } defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body) if err != nil { return nil, err }
var todos struct { Todos []Todo `json:"todos"` } if err := json.Unmarshal(body, &todos); err != nil { return nil, err }
return todos.Todos, nil}