RPC and protobuf contracts
Prerequisite: node-service-communication-and-contracts. Objective: Model typed catalog request. Each example is independent. Tested with Node.js 22.16.0 on Linux. Save as main.mjs in a fresh disposable directory and run node main.mjs. These are static code blocks; external system behavior is not established by a local model.
How it works
A unary GetBook operation accepts one request and returns one response. A .proto file defines numbered fields and their types, and tooling generates or dynamically loads client and server bindings. Field numbers identify binary fields; JavaScript property names alone do not describe the wire encoding. The server validates business constraints and authorizes the caller independently of decoding. A local object model below is deliberately not a Protobuf encoder.
Model a unary contract
import assert from 'node:assert/strict';const books=new Map([['b1',{id:'b1',title:'River'}]]);function getBook(request){if(typeof request.id!=='string'||!request.id)throw Error('INVALID_ARGUMENT');return books.get(request.id)??null;}assert.throws(()=>getBook({id:''}),/INVALID_ARGUMENT/);console.log(getBook({id:'b1'}).title,getBook({id:'missing'}));Expected output:
River nullA valid ID returns a record or null; the service adapter would map absence to NOT_FOUND.
Separate field identity from name
import assert from 'node:assert/strict';const fields=[{number:1,name:'id'},{number:2,name:'title'}];assert.equal(new Set(fields.map(f=>f.number)).size,fields.length);console.log(fields.map(f=>`${f.number}:${f.name}`).join(' '));Expected output:
1:id 2:titleThis is a schema metadata worksheet, not serialization.
Common mistake
Do not assume a successfully decoded request is authorized or that a missing scalar is distinguishable from its default without explicit presence semantics.
Practice
Extend the model to reject an empty book ID and verify missing and valid records independently.
Reference candidate: node-rpc-and-protobuf-contracts-lookup (route unverified). Documentation anchors: https://protobuf.dev/programming-guides/proto3/, https://grpc.io/docs/what-is-grpc/core-concepts/. External versions and full integration are pending.
Administrative staged lab: staged-deployment-labs/rpc/catalog.proto. Read its README for prerequisites, execution boundaries and cleanup. Not a verified public route.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
RPC and protobuf contracts — knowledge check
Apply the lesson to a fresh scenario and explain the evidence boundary.
What identifies a field in binary Protobuf?
A decoded ID is empty. What should the service do?
What does unary mean?