Loader
When using Proto Loader, we only need to provide parameters when creating an instance.
import { ProtoLoader } from 'grpcity'
const loader = new ProtoLoader({ location, files })
Why are the parameters location
and files
used?
location
refers to the directory containing proto files, including the proto files referenced by services, such asmodel.proto
,empty.proto
, and other independently referenced files.files
specify the specificservice.proto
files, informing the underlying service that its definition comes from these files.
Benefits:
- Service loading is clear, indicating which services will be used.
- Proto directory structure is customizable without affecting loading.
Directory Retrieval
For ESM, use the following:
import { ProtoLoader } from 'grpcity'
import path from 'node:path'
import { fileURLToPath } from 'node:url'
// __dirname for esm
const __dirname = path.dirname(fileURLToPath(import.meta.url))
For CommonJS, __dirname
is global, and you can use it directly where needed.
A Single Directory
In most cases, you only need to load the proto directory once and specify multiple services, as shown below:
export default new ProtoLoader({
location: path.join(__dirname, './proto'),
files: [
'path/to/service-a.proto',
'path/to/service-b.proto'
]
})
Multiple Directories
Sometimes, when making service calls across businesses, you may need to load multiple proto directories. Our gRPCity
already supports loading multiple proto directories, as shown below:
export default new ProtoLoader([
{
location: path.join(__dirname, './proto1'),
files: [
'path/to/service-a.proto'
]
},
{
location: path.join(__dirname, './proto2'),
files: [
'path/to/service-b.proto'
]
},
])
Initialization
Why does the loader need to be initialized with init()?
init()
is the actual execution of loading proto. It is also the position to customize parameters and environment configurations, making it more independent and can be placed as the first step in the service framework process, requiring only one execution.
await loader.init(options)
Explanation of options
, which includes the following parameters:
- isDev: (optional) Boolean value, indicating whether it is in development mode.
- packagePrefix: (optional) String, the service name prefix, such as:
dev
,stage
, etc. - loadOptions: (optional) Proto load options.
For more information on loadOptions
, please refer to this article: Config
Example
Note that when using packagePrefix
, both the server and client need to be consistent.
For the test environment, configure as follows:
await loader.init({
isDev: true,
packagePrefix: 'test'
})
For the stage environment, configure as follows:
await loader.init({
isDev: true,
packagePrefix: 'stage'
})
For the production environment, simply ignore these two configuration items, as shown below:
await loader.init()