Install Protocol Buffer Compiler.
MacOS
ref. https://grpc.io/docs/protoc-installation/
$ brew install protobuf
$ which protoc
Windows
ref. https://qiita.com/nzer0/items/7208c880693e63ca247a#win
protoc
commands generate code for client side, server side and type definition of Typescript. Let's execute commands as shown below and check files will be generated.
- make a directory for output.
$ mkdir .generated
- install npm packages
$ npm install
- generate code with using protoc command.
$ protoc -I=proto --ts_out=.generated ChatService.proto
If got an error of protoc-gen-ts is not found
, add proto-gen-ts
's path.
#!/bin/bash
# Path to this plugin
PROTOC_GEN_TS_PATH="./node_modules/.bin/protoc-gen-ts"
# Directory to write generated code to (.js and .d.ts files)
OUT_DIR="./.generated"
mkdir -p ${OUT_DIR}
protoc \
--plugin="protoc-gen-ts=${PROTOC_GEN_TS_PATH}" \
--ts_out="${OUT_DIR}" \
./proto/ChatService.proto
Let's add the count of reactions field to ChatService. You can see the data types of protobuf from here.
https://protobuf.dev/programming-guides/proto3/
- add a new field to
ChatService
message ChatMessage {
string message = 1;
// add here.
// e.g. int64 count_of_reactions = 2;
}
- compile again with the
protoc
command. - check generated code and difference previous one.
go to next > practice_2