├── .npmrc ├── .gitignore ├── src ├── lib │ ├── DependencyFilter.ts │ ├── Printer.ts │ ├── descriptor │ │ ├── partial │ │ │ ├── Enum.ts │ │ │ ├── Extensions.ts │ │ │ ├── OneOf.ts │ │ │ ├── FieldTypes.ts │ │ │ └── Message.ts │ │ ├── FileDescriptorMSG.ts │ │ └── FileDescriptorGRPC.ts │ ├── DependencyTypesMap.ts │ ├── EntryMap.ts │ └── Utility.ts └── index.ts ├── examples ├── bash │ ├── client.sh │ └── server.sh ├── tsconfig.json ├── build.sh ├── build_dev.sh ├── package.json ├── proto │ └── product.proto ├── build │ ├── server.js.map │ ├── server.js │ ├── proto │ │ ├── product_grpc_pb.js │ │ ├── product_pb.d.ts │ │ ├── product_grpc_pb.d.ts │ │ └── product_pb.js │ ├── client.js.map │ └── client.js ├── src │ ├── proto │ │ ├── product_grpc_pb.js │ │ ├── product_pb.d.ts │ │ ├── product_grpc_pb.d.ts │ │ └── product_pb.js │ ├── server.ts │ └── client.ts └── package-lock.json ├── bin ├── protoc-gen-ts-plugin ├── protoc-gen-ts-plugin.cmd ├── protoc-gen.js ├── protoc-gen-grpc.js └── protoc-gen-grpc-ts.js ├── tsconfig.json ├── LICENSE ├── package.json └── README.md /.npmrc: -------------------------------------------------------------------------------- 1 | save-exact=true 2 | package-lock=true -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea/ 2 | node_modules/ 3 | bin/google/ 4 | bin/*.exe 5 | bin/grpc_node_plugin 6 | bin/protoc 7 | -------------------------------------------------------------------------------- /src/lib/DependencyFilter.ts: -------------------------------------------------------------------------------- 1 | export const DependencyFilter: Array = [ 2 | 'google/api/annotations.proto' 3 | ]; 4 | -------------------------------------------------------------------------------- /examples/bash/client.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | BASEDIR=$(dirname "$0") 4 | cd ${BASEDIR}/../ 5 | 6 | DEBUG=* node ./build/client.js -------------------------------------------------------------------------------- /examples/bash/server.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | BASEDIR=$(dirname "$0") 4 | cd ${BASEDIR}/../ 5 | 6 | DEBUG=* node ./build/server.js -------------------------------------------------------------------------------- /bin/protoc-gen-ts-plugin: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | 3 | var LibPath = require('path'); 4 | 5 | require(LibPath.join(__dirname, '..', 'build', 'index.js')); 6 | -------------------------------------------------------------------------------- /bin/protoc-gen-ts-plugin.cmd: -------------------------------------------------------------------------------- 1 | @IF EXIST "%~dp0\node.exe" ( 2 | "%~dp0\node.exe" "%~dp0\..\build\index.js" %* 3 | ) ELSE ( 4 | @SETLOCAL 5 | @SET PATHEXT=%PATHEXT:;.JS;=;% 6 | node "%~dp0\..\build\index.js" %* 7 | ) -------------------------------------------------------------------------------- /examples/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES2017", 4 | "module": "commonjs", 5 | "sourceMap": true, 6 | "rootDir": "src", 7 | "outDir": "build", 8 | "experimentalDecorators": true, 9 | "emitDecoratorMetadata": true 10 | }, 11 | "include": [ 12 | "src/**/*.ts" 13 | ], 14 | "exclude": [ 15 | "node_modules" 16 | ] 17 | } -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES6", 4 | "module": "commonjs", 5 | "sourceMap": false, 6 | "allowJs": true, 7 | "rootDir": "src", 8 | "outDir": "build", 9 | "experimentalDecorators": true, 10 | "emitDecoratorMetadata": true 11 | }, 12 | "include": [ 13 | "src/**/*.ts", 14 | "typings/**/*.d.ts" 15 | ], 16 | "exclude": [ 17 | "node_modules" 18 | ] 19 | } -------------------------------------------------------------------------------- /examples/build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | PROTO_DEST=./proto 4 | OUTPUT_DEST=./src/proto 5 | BUILD_DEST=./build/proto 6 | 7 | mkdir -p ${OUTPUT_DEST} 8 | 9 | # JavaScript code generating 10 | protoc-gen-grpc \ 11 | --js_out=import_style=commonjs,binary:${OUTPUT_DEST} \ 12 | --grpc_out=grpc_js:${OUTPUT_DEST} \ 13 | --proto_path ${PROTO_DEST} \ 14 | ${PROTO_DEST}/*.proto 15 | 16 | protoc-gen-grpc-ts \ 17 | --ts_out=grpc_js:${OUTPUT_DEST} \ 18 | --proto_path ${PROTO_DEST} \ 19 | ${PROTO_DEST}/*.proto 20 | 21 | # TypeScript compiling 22 | mkdir -p ${BUILD_DEST} 23 | cp -r ${OUTPUT_DEST}/* ${BUILD_DEST} 24 | tsc -------------------------------------------------------------------------------- /examples/build_dev.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | PROTO_DEST=./proto 4 | OUTPUT_DEST=./src/proto 5 | BUILD_DEST=./build/proto 6 | 7 | mkdir -p ${OUTPUT_DEST} 8 | 9 | # JavaScript code generating 10 | node ../bin/protoc-gen-grpc.js \ 11 | --js_out=import_style=commonjs,binary:${OUTPUT_DEST} \ 12 | --grpc_out=grpc_js:${OUTPUT_DEST} \ 13 | --proto_path ${PROTO_DEST} \ 14 | ${PROTO_DEST}/*.proto 15 | 16 | node ../bin/protoc-gen-grpc-ts.js \ 17 | --ts_out=grpc_js:${OUTPUT_DEST} \ 18 | --proto_path ${PROTO_DEST} \ 19 | ${PROTO_DEST}/*.proto 20 | 21 | # TypeScript compiling 22 | mkdir -p ${BUILD_DEST} 23 | cp -r ${OUTPUT_DEST}/* ${BUILD_DEST} 24 | tsc -------------------------------------------------------------------------------- /examples/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "version": "2.0.1", 4 | "description": "gRPC generating example", 5 | "engines": { 6 | "node": ">=16" 7 | }, 8 | "main": "index.js", 9 | "directories": { 10 | "example": "example" 11 | }, 12 | "scripts": { 13 | "build": "sh ./build.sh", 14 | "test": "echo \"Error: no test specified\" && exit 1" 15 | }, 16 | "author": "fengjie", 17 | "license": "MIT", 18 | "dependencies": { 19 | "@grpc/grpc-js": "~1.12.6", 20 | "debug": "^4.4.0", 21 | "google-protobuf": "~3.21.2" 22 | }, 23 | "devDependencies": { 24 | "@types/debug": "^4.1.12", 25 | "@types/node": "^18.19.0", 26 | "typescript": "^4.3.2" 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/lib/Printer.ts: -------------------------------------------------------------------------------- 1 | import {Utility} from './Utility'; 2 | 3 | export class Printer { 4 | indentStr: string; 5 | output: string = ''; 6 | 7 | constructor(indentLevel: number) { 8 | this.indentStr = Utility.generateIndent(indentLevel); 9 | } 10 | 11 | printLn(str: string) { 12 | this.output += this.indentStr + str + '\n'; 13 | } 14 | 15 | print(str: string) { 16 | this.output += str; 17 | } 18 | 19 | printEmptyLn() { 20 | this.output += '\n'; 21 | } 22 | 23 | printIndentedLn(str: string) { 24 | this.output += this.indentStr + ' ' + str + '\n'; 25 | } 26 | 27 | getOutput(): string { 28 | return this.output; 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /src/lib/descriptor/partial/Enum.ts: -------------------------------------------------------------------------------- 1 | import {EnumDescriptorProto} from 'google-protobuf/google/protobuf/descriptor_pb'; 2 | import {Printer} from '../../Printer'; 3 | 4 | export namespace Enum { 5 | 6 | export function print(enumDescriptor: EnumDescriptorProto, indentLevel: number): string { 7 | 8 | const printer = new Printer(indentLevel); 9 | printer.printEmptyLn(); 10 | printer.printLn(`export enum ${enumDescriptor.getName()} {`); 11 | enumDescriptor.getValueList().forEach(value => { 12 | printer.printIndentedLn(`${value.getName().toUpperCase()} = ${value.getNumber()},`); 13 | }); 14 | printer.printLn(`}`); 15 | return printer.getOutput(); 16 | } 17 | 18 | } -------------------------------------------------------------------------------- /examples/proto/product.proto: -------------------------------------------------------------------------------- 1 | syntax = "proto3"; 2 | 3 | package com.product; 4 | 5 | message Product { 6 | int64 id = 1; 7 | string name = 2; 8 | string category = 3; 9 | } 10 | 11 | message GetProductRequest { 12 | int64 id = 1; 13 | } 14 | 15 | message GetProductViaCategoryRequest { 16 | string category = 1; 17 | } 18 | 19 | service ProductService { 20 | rpc GetProduct (GetProductRequest) returns (Product) {} 21 | rpc GetProductViaCategory (GetProductViaCategoryRequest) returns (stream Product) {} 22 | rpc GetBestProduct (stream GetProductRequest) returns (Product) {} 23 | rpc GetProducts (stream GetProductRequest) returns (stream Product) {} 24 | } 25 | 26 | message Shop { 27 | string name = 1; 28 | map list = 2; 29 | } -------------------------------------------------------------------------------- /src/lib/descriptor/partial/Extensions.ts: -------------------------------------------------------------------------------- 1 | import {FieldDescriptorProto} from 'google-protobuf/google/protobuf/descriptor_pb'; 2 | import {Printer} from '../../Printer'; 3 | import {EntryMap} from '../../EntryMap'; 4 | import {Utility} from '../../Utility'; 5 | import {FieldTypes} from './FieldTypes'; 6 | 7 | export namespace Extension { 8 | 9 | export function print(fileName: string, entryMap: EntryMap, fieldsDescriptor: FieldDescriptorProto, indentLevel: number): string { 10 | 11 | const extensionName = Utility.snakeToCamel(fieldsDescriptor.getName()); 12 | const fieldType = FieldTypes.getFieldType(fieldsDescriptor.getType(), fieldsDescriptor.getTypeName().slice(1), fileName, entryMap); 13 | 14 | const printer = new Printer(indentLevel + 1); 15 | printer.printEmptyLn(); 16 | printer.printLn(`export const ${extensionName}: jspb.ExtensionFieldInfo<${fieldType}>;`); 17 | return printer.output; 18 | } 19 | 20 | } -------------------------------------------------------------------------------- /src/lib/descriptor/partial/OneOf.ts: -------------------------------------------------------------------------------- 1 | import {FieldDescriptorProto, OneofDescriptorProto} from 'google-protobuf/google/protobuf/descriptor_pb'; 2 | import {Printer} from '../../Printer'; 3 | import {Utility} from '../../Utility'; 4 | 5 | export namespace OneOf { 6 | 7 | export function print(oneOfDescriptor: OneofDescriptorProto, fieldsDescriptor: Array, indentLevel: number): string { 8 | 9 | let oneOfName = Utility.oneOfName(oneOfDescriptor.getName()); 10 | let oneOfNameUpper = oneOfDescriptor.getName().toUpperCase(); 11 | 12 | const printer = new Printer(indentLevel); 13 | printer.printEmptyLn(); 14 | printer.printLn(`export enum ${oneOfName}Case {`); 15 | printer.printIndentedLn(`${oneOfNameUpper}_NOT_SET = 0,`); 16 | fieldsDescriptor.forEach(field => { 17 | printer.printIndentedLn(`${field.getName().toUpperCase()} = ${field.getNumber()},`); 18 | }); 19 | printer.printLn('}'); 20 | 21 | return printer.output; 22 | } 23 | 24 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019-2025 fengjie 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/lib/DependencyTypesMap.ts: -------------------------------------------------------------------------------- 1 | export const DependencyTypesMap: {[key: string]: string} = { 2 | 'google/protobuf/compiler/plugin.proto': 'google-protobuf/google/protobuf/compiler/plugin_pb', 3 | 'google/protobuf/any.proto': 'google-protobuf/google/protobuf/any_pb', 4 | 'google/protobuf/api.proto': 'google-protobuf/google/protobuf/api_pb', 5 | 'google/protobuf/descriptor.proto': 'google-protobuf/google/protobuf/descriptor_pb', 6 | 'google/protobuf/duration.proto': 'google-protobuf/google/protobuf/duration_pb', 7 | 'google/protobuf/empty.proto': 'google-protobuf/google/protobuf/empty_pb', 8 | 'google/protobuf/field_mask.proto': 'google-protobuf/google/protobuf/field_mask_pb', 9 | 'google/protobuf/source_context.proto': 'google-protobuf/google/protobuf/source_context_pb', 10 | 'google/protobuf/struct.proto': 'google-protobuf/google/protobuf/struct_pb', 11 | 'google/protobuf/timestamp.proto': 'google-protobuf/google/protobuf/timestamp_pb', 12 | 'google/protobuf/type.proto': 'google-protobuf/google/protobuf/type_pb', 13 | 'google/protobuf/wrappers.proto': 'google-protobuf/google/protobuf/wrappers_pb' 14 | }; 15 | -------------------------------------------------------------------------------- /bin/protoc-gen.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | /* 3 | * 4 | * Copyright 2015 gRPC authors. 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | * 18 | */ 19 | 20 | /** 21 | * This file is required because package.json cannot reference a file that 22 | * is not distributed with the package, and we use node-pre-gyp to distribute 23 | * the protoc binary 24 | */ 25 | 26 | 'use strict'; 27 | 28 | var path = require('path'); 29 | var execFile = require('child_process').execFile; 30 | 31 | var exe_ext = process.platform === 'win32' ? '.exe' : ''; 32 | 33 | var protoc = path.resolve(__dirname, 'protoc' + exe_ext); 34 | 35 | var args = process.argv.slice(2); 36 | 37 | var child_process = execFile(protoc, args, function(error, stdout, stderr) { 38 | if (error) { 39 | throw error; 40 | } 41 | }); 42 | 43 | child_process.stdout.pipe(process.stdout); 44 | child_process.stderr.pipe(process.stderr); 45 | -------------------------------------------------------------------------------- /bin/protoc-gen-grpc.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | /* 3 | * 4 | * Copyright 2015 gRPC authors. 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | * 18 | */ 19 | 20 | /** 21 | * This file is required because package.json cannot reference a file that 22 | * is not distributed with the package, and we use node-pre-gyp to distribute 23 | * the protoc binary 24 | */ 25 | 26 | 'use strict'; 27 | 28 | var path = require('path'); 29 | var execFile = require('child_process').execFile; 30 | 31 | var exe_ext = process.platform === 'win32' ? '.exe' : ''; 32 | 33 | var protoc = path.resolve(__dirname, 'protoc' + exe_ext); 34 | 35 | var plugin = path.resolve(__dirname, 'grpc_node_plugin' + exe_ext); 36 | 37 | var args = ['--plugin=protoc-gen-grpc=' + plugin].concat(process.argv.slice(2)); 38 | 39 | var child_process = execFile(protoc, args, function(error, stdout, stderr) { 40 | if (error) { 41 | throw error; 42 | } 43 | }); 44 | 45 | child_process.stdout.pipe(process.stdout); 46 | child_process.stderr.pipe(process.stderr); 47 | -------------------------------------------------------------------------------- /bin/protoc-gen-grpc-ts.js: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env node 2 | /* 3 | * 4 | * Copyright 2015 gRPC authors. 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | * 18 | */ 19 | 20 | /** 21 | * This file is required because package.json cannot reference a file that 22 | * is not distributed with the package, and we use node-pre-gyp to distribute 23 | * the protoc binary 24 | */ 25 | 26 | 'use strict'; 27 | 28 | var path = require('path'); 29 | var execSync = require('child_process').execSync; 30 | var execFile = require('child_process').execFile; 31 | 32 | var exe_ext = process.platform === 'win32' ? '.exe' : ''; 33 | 34 | var protoc = path.resolve(__dirname, 'protoc' + exe_ext); 35 | 36 | var plugin = (process.platform === 'win32') 37 | ? path.resolve(__dirname, 'protoc-gen-ts-plugin.cmd') 38 | : path.resolve(__dirname, 'protoc-gen-ts-plugin'); 39 | // : execSync('which protoc-gen-ts-plugin').toString().replace(/\n$/, '').replace(/\r$/, ''); 40 | 41 | var args = ['--plugin=protoc-gen-ts=' + plugin].concat(process.argv.slice(2)); 42 | 43 | var child_process = execFile(protoc, args, function(error, stdout, stderr) { 44 | if (error) { 45 | throw error; 46 | } 47 | }); 48 | 49 | child_process.stdout.pipe(process.stdout); 50 | child_process.stderr.pipe(process.stderr); 51 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "protoc-gen-grpc", 3 | "version": "3.0.0", 4 | "author": "fengjie", 5 | "description": "Protocol Buffers Compiler (protoc) plugin for generating grpc interfaces in TypeScript..", 6 | "homepage": "https://github.com/stultuss/protoc-gen-grpc-ts#readme", 7 | "repository": { 8 | "type": "git", 9 | "url": "git+https://github.com/stultuss/protoc-gen-grpc-ts.git" 10 | }, 11 | "bugs": "https://github.com/stultuss/protoc-gen-grpc-ts/issues", 12 | "keywords": [ 13 | "TypeScript", 14 | "Protobuf", 15 | "gRPC" 16 | ], 17 | "engines": { 18 | "node": ">=16" 19 | }, 20 | "main": "./build/index.js", 21 | "bin": { 22 | "protoc-gen-ts-plugin": "./bin/protoc-gen-ts-plugin", 23 | "protoc-gen": "./bin/protoc-gen.js", 24 | "protoc-gen-grpc": "./bin/protoc-gen-grpc.js", 25 | "protoc-gen-grpc-ts": "./bin/protoc-gen-grpc-ts.js" 26 | }, 27 | "scripts": { 28 | "install": "node-pre-gyp install", 29 | "build": "rimraf build && tsc", 30 | "clean": "rimraf build", 31 | "prepare": "npm run build", 32 | "test-js-out": "node ./bin/protoc-gen-grpc.js --js_out=import_style=commonjs,binary:./examples/src/proto --grpc_out=grpc_js:./examples/src/proto --proto_path ./examples/proto ./examples/proto/product.proto", 33 | "test-ts-out": "node ./bin/protoc-gen-grpc-ts.js --ts_out=grpc_js:./examples/src/proto --proto_path ./examples/proto ./examples/proto/product.proto" 34 | }, 35 | "license": "MIT", 36 | "dependencies": { 37 | "@grpc/grpc-js": "~1.12.6", 38 | "google-protobuf": "~3.21.2" 39 | }, 40 | "devDependencies": { 41 | "@mapbox/node-pre-gyp": "2.0.0", 42 | "@types/google-protobuf": "^3.15.12", 43 | "@types/node": "^18.19.0", 44 | "rimraf": "^5.0.5", 45 | "ts-node": "^10.9.2", 46 | "typescript": "^5.3.0" 47 | }, 48 | "binary": { 49 | "module_name": "grpc_tools", 50 | "host": "https://node-precompiled-binaries.grpc.io/", 51 | "remote_path": "grpc-tools/v1.13.0", 52 | "package_name": "{platform}-{arch}.tar.gz", 53 | "module_path": "bin" 54 | }, 55 | "bundleDependencies": [ 56 | "@mapbox/node-pre-gyp" 57 | ] 58 | } 59 | -------------------------------------------------------------------------------- /src/lib/descriptor/FileDescriptorMSG.ts: -------------------------------------------------------------------------------- 1 | import {FileDescriptorProto} from 'google-protobuf/google/protobuf/descriptor_pb'; 2 | 3 | import {EntryMap} from '../EntryMap'; 4 | import {Utility} from '../Utility'; 5 | import {Printer} from '../Printer'; 6 | import {DependencyTypesMap} from '../DependencyTypesMap'; 7 | 8 | import {Message} from './partial/Message'; 9 | import {Enum} from './partial/Enum'; 10 | import {Extension} from './partial/Extensions'; 11 | 12 | export namespace FileDescriptorMSG { 13 | 14 | export function print(fileDescriptor: FileDescriptorProto, entryMap: EntryMap) { 15 | const fileName = fileDescriptor.getName(); 16 | const packageName = fileDescriptor.getPackage(); 17 | 18 | const printer = new Printer(0); 19 | 20 | printer.printLn(`// package: ${packageName}`); 21 | printer.printLn(`// file: ${fileDescriptor.getName()}`); 22 | printer.printEmptyLn(); 23 | 24 | const upToRoot = Utility.getPathToRoot(fileName); 25 | 26 | printer.printLn(`import * as jspb from 'google-protobuf';`); 27 | 28 | fileDescriptor.getDependencyList().forEach((dependency: string) => { 29 | const pseudoNamespace = Utility.filePathToPseudoNamespace(dependency); 30 | if (dependency in DependencyTypesMap) { 31 | printer.printLn(`import * as ${pseudoNamespace} from '${DependencyTypesMap[dependency]}';`); 32 | } else { 33 | const filePath = Utility.filePathFromProtoWithoutExtension(dependency); 34 | printer.printLn(`import * as ${pseudoNamespace} from '${upToRoot}${filePath}';`); 35 | } 36 | }); 37 | 38 | fileDescriptor.getMessageTypeList().forEach(enumType => { 39 | printer.print(Message.print(fileName, entryMap, enumType, 0, fileDescriptor)); 40 | }); 41 | 42 | fileDescriptor.getExtensionList().forEach(extension => { 43 | printer.print(Extension.print(fileName, entryMap, extension, 0)); 44 | }); 45 | 46 | fileDescriptor.getEnumTypeList().forEach(enumType => { 47 | printer.print(Enum.print(enumType, 0)); 48 | }); 49 | 50 | printer.printEmptyLn(); 51 | 52 | return printer.getOutput(); 53 | } 54 | 55 | } -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This is the ProtoC compiler plugin. 3 | * 4 | * It only accepts stdin/stdout output according to the protocol 5 | * specified in [plugin.proto](https://github.com/google/protobuf/blob/master/src/google/protobuf/compiler/plugin.proto). 6 | * 7 | * source code copy from [ts-protoc-gen](https://github.com/improbable-eng/ts-protoc-gen/blob/master/src/index.ts) 8 | */ 9 | import {CodeGeneratorRequest, CodeGeneratorResponse} from 'google-protobuf/google/protobuf/compiler/plugin_pb'; 10 | import {FileDescriptorProto} from 'google-protobuf/google/protobuf/descriptor_pb'; 11 | import {Utility} from './lib/Utility'; 12 | import {EntryMap} from './lib/EntryMap'; 13 | 14 | import {FileDescriptorMSG} from './lib/descriptor/FileDescriptorMSG'; 15 | import {FileDescriptorGRPC} from './lib/descriptor/FileDescriptorGRPC'; 16 | 17 | Utility.withAllStdIn((input: Buffer) => { 18 | try { 19 | const binary = new Uint8Array(input.length); 20 | binary.set(input); 21 | 22 | const request = CodeGeneratorRequest.deserializeBinary(binary); 23 | const response = new CodeGeneratorResponse(); 24 | const isGrpcJs = ['generate_package_definition', 'grpc_js'].indexOf(request.getParameter()) !== -1; 25 | 26 | // Parse request proto file 27 | const fileNameToDescriptor: { [key: string]: FileDescriptorProto } = {}; 28 | const entryMap = new EntryMap(); 29 | request.getProtoFileList().forEach((fileDescriptor) => { 30 | fileNameToDescriptor[fileDescriptor.getName()] = fileDescriptor; 31 | entryMap.parseFileDescriptor(fileDescriptor); 32 | }); 33 | 34 | // Generate *_pb.d.ts && *_grpc_pb.d.ts 35 | request.getFileToGenerateList().forEach(fileName => { 36 | const outputFileName = Utility.filePathFromProtoWithoutExtension(fileName); 37 | const outputFile = new CodeGeneratorResponse.File(); 38 | outputFile.setName(outputFileName + '.d.ts'); 39 | outputFile.setContent(FileDescriptorMSG.print(fileNameToDescriptor[fileName], entryMap)); 40 | response.addFile(outputFile); 41 | 42 | const fileDescriptorOutput = FileDescriptorGRPC.print(fileNameToDescriptor[fileName], entryMap, isGrpcJs); 43 | if (fileDescriptorOutput !== '') { 44 | const thisServiceFileName = Utility.svcFilePathFromProtoWithoutExtension(fileName); 45 | const thisServiceFile = new CodeGeneratorResponse.File(); 46 | thisServiceFile.setName(thisServiceFileName + '.d.ts'); 47 | thisServiceFile.setContent(fileDescriptorOutput); 48 | response.addFile(thisServiceFile); 49 | } 50 | }); 51 | 52 | process.stdout.write(Buffer.from(response.serializeBinary())); 53 | } catch (err) { 54 | console.error('error: ' + err.stack + '\n'); 55 | process.exit(1); 56 | } 57 | }); -------------------------------------------------------------------------------- /examples/build/server.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":";;AAAA,+BAA+B;AAC/B,kBAAkB;AAClB,sCAAsC;AACtC,eAAe;AACf,gCAAgC;AAEhC,6DAAqF;AACrF,mDAA4F;AAE5F,MAAM,GAAG,GAAG,KAAK,CAAC,mBAAmB,CAAC,CAAC;AAEvC,MAAM,UAAU,GAA0B;IAEtC,UAAU,EAAE,CAAC,IAAsD,EAAE,QAAqC,EAAQ,EAAE;QAChH,GAAG,CAAC,yBAAyB,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC;QAExE,MAAM,EAAE,GAAG,IAAI,oBAAO,EAAE,CAAC;QACzB,EAAE,CAAC,KAAK,CAAC,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC;QAC/B,EAAE,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;QAC1B,EAAE,CAAC,WAAW,CAAC,iBAAiB,CAAC,CAAC;QAElC,GAAG,CAAC,sBAAsB,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC;QAC3D,QAAQ,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;IACvB,CAAC;IAED,qBAAqB,EAAE,CAAC,IAAsE,EAAQ,EAAE;QACpG,GAAG,CAAC,oCAAoC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC;QACnF,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,EAAE,EAAE,CAAC,EAAE,EAAE;YAC1B,MAAM,EAAE,GAAG,IAAI,oBAAO,EAAE,CAAC;YACzB,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YACZ,EAAE,CAAC,OAAO,CAAC,aAAa,GAAG,CAAC,CAAC,CAAC;YAC9B,EAAE,CAAC,WAAW,CAAC,eAAe,GAAG,IAAI,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC,CAAC;YAE7D,GAAG,CAAC,kCAAkC,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC;YACvE,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;SAClB;QACD,GAAG,CAAC,+BAA+B,CAAC,CAAC;QACrC,IAAI,CAAC,GAAG,EAAE,CAAC;IACf,CAAC;IAED,cAAc,EAAE,CAAC,IAA2D,EAAE,QAAqC,EAAQ,EAAE;QACzH,IAAI,OAA0B,CAAC;QAC/B,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,OAA0B,EAAE,EAAE;YAC3C,GAAG,CAAC,6BAA6B,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC;YACvE,OAAO,GAAG,OAAO,CAAC;QACtB,CAAC,CAAC,CAAC;QACH,IAAI,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;YAChB,MAAM,EAAE,GAAG,IAAI,oBAAO,EAAE,CAAC;YACzB,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC;YAC1B,EAAE,CAAC,OAAO,CAAC,aAAa,CAAC,CAAC;YAC1B,EAAE,CAAC,WAAW,CAAC,iBAAiB,CAAC,CAAC;YAElC,GAAG,CAAC,0BAA0B,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC;YAC/D,QAAQ,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC;QACvB,CAAC,CAAC,CAAC;QACH,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE;YACnB,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QACnB,CAAC,CAAC,CAAC;IACP,CAAC;IAED,WAAW,EAAE,CAAC,IAAyD,EAAQ,EAAE;QAC7E,IAAI,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,OAA0B,EAAE,EAAE;YAE3C,MAAM,EAAE,GAAG,IAAI,oBAAO,EAAE,CAAC;YACzB,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC;YAC1B,EAAE,CAAC,OAAO,CAAC,QAAQ,GAAG,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC;YACvC,EAAE,CAAC,WAAW,CAAC,YAAY,GAAG,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC;YAE/C,GAAG,CAAC,wBAAwB,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC;YAC7D,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QACnB,CAAC,CAAC,CAAC;QACH,IAAI,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;YAChB,GAAG,CAAC,qBAAqB,CAAC,CAAC;YAC3B,IAAI,CAAC,GAAG,EAAE,CAAC;QACf,CAAC,CAAC,CAAC;QACH,IAAI,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE;YACnB,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;QACnB,CAAC,CAAC,CAAC;IACP,CAAC;CACJ,CAAC;AAEF,SAAS,WAAW;IAChB,MAAM,MAAM,GAAG,IAAI,IAAI,CAAC,MAAM,EAAE,CAAC;IACjC,kBAAkB;IAClB,MAAM,CAAC,UAAU,CAAC,uCAAqB,EAAE,UAAU,CAAC,CAAC;IACrD,kBAAkB;IAClB,8DAA8D;IAC9D,MAAM,CAAC,SAAS,CAAC,iBAAiB,EAAE,IAAI,CAAC,iBAAiB,CAAC,cAAc,EAAE,EAAE,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE;QACrF,IAAI,CAAC;YAAE,MAAM,CAAC,CAAC;QACf,GAAG,CAAC,wCAAwC,IAAI,EAAE,CAAC,CAAC;IACxD,CAAC,CAAC,CAAC;AACP,CAAC;AAED,WAAW,EAAE,CAAC;AAEd,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,GAAG,EAAE,EAAE;IACpC,GAAG,CAAC,uCAAuC,GAAG,EAAE,CAAC,CAAC;AACtD,CAAC,CAAC,CAAC;AAEH,OAAO,CAAC,EAAE,CAAC,oBAAoB,EAAE,CAAC,GAAG,EAAE,EAAE;IACrC,GAAG,CAAC,wCAAwC,GAAG,EAAE,CAAC,CAAC;AACvD,CAAC,CAAC,CAAC"} -------------------------------------------------------------------------------- /src/lib/descriptor/partial/FieldTypes.ts: -------------------------------------------------------------------------------- 1 | import {FieldDescriptorProto} from 'google-protobuf/google/protobuf/descriptor_pb'; 2 | import {EntryMap, EnumEntry, MessageEntry} from '../../EntryMap'; 3 | import {Utility} from '../../Utility'; 4 | 5 | export const MESSAGE_TYPE = 11; 6 | export const BYTES_TYPE = 12; 7 | export const ENUM_TYPE = 14; 8 | 9 | const TypeNumToTypeString: {[key: number]: string} = {}; 10 | TypeNumToTypeString[1] = 'number'; // TYPE_DOUBLE 11 | TypeNumToTypeString[2] = 'number'; // TYPE_FLOAT 12 | TypeNumToTypeString[3] = 'number'; // TYPE_INT64 13 | TypeNumToTypeString[4] = 'number'; // TYPE_UINT64 14 | TypeNumToTypeString[5] = 'number'; // TYPE_INT32 15 | TypeNumToTypeString[6] = 'number'; // TYPE_FIXED64 16 | TypeNumToTypeString[7] = 'number'; // TYPE_FIXED32 17 | TypeNumToTypeString[8] = 'boolean'; // TYPE_BOOL 18 | TypeNumToTypeString[9] = 'string'; // TYPE_STRING 19 | TypeNumToTypeString[10] = 'Object'; // TYPE_GROUP 20 | TypeNumToTypeString[MESSAGE_TYPE] = 'Object'; // TYPE_MESSAGE - Length-delimited aggregate. 21 | TypeNumToTypeString[BYTES_TYPE] = 'Uint8Array'; // TYPE_BYTES 22 | TypeNumToTypeString[13] = 'number'; // TYPE_UINT32 23 | TypeNumToTypeString[ENUM_TYPE] = 'number'; // TYPE_ENUM 24 | TypeNumToTypeString[15] = 'number'; // TYPE_SFIXED32 25 | TypeNumToTypeString[16] = 'number'; // TYPE_SFIXED64 26 | TypeNumToTypeString[17] = 'number'; // TYPE_SINT32 - Uses ZigZag encoding. 27 | TypeNumToTypeString[18] = 'number'; // TYPE_SINT64 - Uses ZigZag encoding. 28 | 29 | export namespace FieldTypes { 30 | 31 | export function getTypeName(fieldTypeNum: number): string { 32 | return TypeNumToTypeString[fieldTypeNum]; 33 | } 34 | 35 | export function getFieldType(type: FieldDescriptorProto.Type, typeName: string, currentFileName: string, entryMap: EntryMap): string { 36 | let fieldType: string; 37 | let fromExport: MessageEntry | EnumEntry; 38 | let withinNamespace: string; 39 | 40 | switch (type) { 41 | case MESSAGE_TYPE: 42 | fromExport = entryMap.getMessageEntry(typeName); 43 | if (!fromExport) { 44 | throw new Error('Could not getFieldType for message: ' + typeName); 45 | } 46 | withinNamespace = Utility.withinNamespaceFromExportEntry(typeName, fromExport); 47 | if (fromExport.fileName === currentFileName) { 48 | fieldType = withinNamespace; 49 | } else { 50 | fieldType = Utility.filePathToPseudoNamespace(fromExport.fileName) + '.' + withinNamespace; 51 | } 52 | break; 53 | 54 | case ENUM_TYPE: 55 | fromExport = entryMap.getEnumEntry(typeName); 56 | if (!fromExport) { 57 | throw new Error('Could not getFieldType for enum: ' + typeName); 58 | } 59 | withinNamespace = Utility.withinNamespaceFromExportEntry(typeName, fromExport); 60 | if (fromExport.fileName === currentFileName) { 61 | fieldType = withinNamespace; 62 | } else { 63 | fieldType = Utility.filePathToPseudoNamespace(fromExport.fileName) + '.' + withinNamespace; 64 | } 65 | break; 66 | 67 | default: 68 | fieldType = TypeNumToTypeString[type]; 69 | break; 70 | } 71 | 72 | return fieldType; 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /examples/build/server.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const debug = require("debug"); 4 | // support grpc-js 5 | const grpc = require("@grpc/grpc-js"); 6 | // support grpc 7 | // import * as grpc from 'grpc'; 8 | const product_grpc_pb_1 = require("./proto/product_grpc_pb"); 9 | const product_pb_1 = require("./proto/product_pb"); 10 | const log = debug('[Demo:GrpcServer]'); 11 | const ServerImpl = { 12 | getProduct: (call, callback) => { 13 | log(`[getProduct] Request: ${JSON.stringify(call.request.toObject())}`); 14 | const vo = new product_pb_1.Product(); 15 | vo.setId(call.request.getId()); 16 | vo.setName('DefaultName'); 17 | vo.setCategory('DefaultCategory'); 18 | log(`[getProduct] Done: ${JSON.stringify(vo.toObject())}`); 19 | callback(null, vo); 20 | }, 21 | getProductViaCategory: (call) => { 22 | log(`[getProductViaCategory] Request: ${JSON.stringify(call.request.toObject())}`); 23 | for (let i = 1; i <= 10; i++) { 24 | const vo = new product_pb_1.Product(); 25 | vo.setId(i); 26 | vo.setName('DefaultName' + i); 27 | vo.setCategory('CategoryName=' + call.request.getCategory()); 28 | log(`[getProductViaCategory] Write: ${JSON.stringify(vo.toObject())}`); 29 | call.write(vo); 30 | } 31 | log('[getProductViaCategory] Done.'); 32 | call.end(); 33 | }, 34 | getBestProduct: (call, callback) => { 35 | let lastOne; 36 | call.on('data', (request) => { 37 | log(`[getBestProduct] Request: ${JSON.stringify(request.toObject())}`); 38 | lastOne = request; 39 | }); 40 | call.on('end', () => { 41 | const vo = new product_pb_1.Product(); 42 | vo.setId(lastOne.getId()); 43 | vo.setName('LastOneName'); 44 | vo.setCategory('LastOneCategory'); 45 | log(`[getBestProduct] Done: ${JSON.stringify(vo.toObject())}`); 46 | callback(null, vo); 47 | }); 48 | call.on('error', (e) => { 49 | console.log(e); 50 | }); 51 | }, 52 | getProducts: (call) => { 53 | call.on('data', (request) => { 54 | const vo = new product_pb_1.Product(); 55 | vo.setId(request.getId()); 56 | vo.setName('NameOf' + request.getId()); 57 | vo.setCategory('CategoryOf' + request.getId()); 58 | log(`[getProducts] Write: ${JSON.stringify(vo.toObject())}`); 59 | call.write(vo); 60 | }); 61 | call.on('end', () => { 62 | log('[getProducts] Done.'); 63 | call.end(); 64 | }); 65 | call.on('error', (e) => { 66 | console.log(e); 67 | }); 68 | } 69 | }; 70 | function startServer() { 71 | const server = new grpc.Server(); 72 | // support grpc-js 73 | server.addService(product_grpc_pb_1.ProductServiceService, ServerImpl); 74 | // support grpc-js 75 | // server.addService(ProductServiceService, new ServerImpl()); 76 | server.bindAsync('127.0.0.1:50051', grpc.ServerCredentials.createInsecure(), (e, port) => { 77 | if (e) 78 | throw e; 79 | log(`Server started, listening: 127.0.0.1:${port}`); 80 | }); 81 | } 82 | startServer(); 83 | process.on('uncaughtException', (err) => { 84 | log(`process on uncaughtException error: ${err}`); 85 | }); 86 | process.on('unhandledRejection', (err) => { 87 | log(`process on unhandledRejection error: ${err}`); 88 | }); 89 | //# sourceMappingURL=server.js.map -------------------------------------------------------------------------------- /examples/src/proto/product_grpc_pb.js: -------------------------------------------------------------------------------- 1 | // GENERATED CODE -- DO NOT EDIT! 2 | 3 | 'use strict'; 4 | var grpc = require('@grpc/grpc-js'); 5 | var product_pb = require('./product_pb.js'); 6 | 7 | function serialize_com_product_GetProductRequest(arg) { 8 | if (!(arg instanceof product_pb.GetProductRequest)) { 9 | throw new Error('Expected argument of type com.product.GetProductRequest'); 10 | } 11 | return Buffer.from(arg.serializeBinary()); 12 | } 13 | 14 | function deserialize_com_product_GetProductRequest(buffer_arg) { 15 | return product_pb.GetProductRequest.deserializeBinary(new Uint8Array(buffer_arg)); 16 | } 17 | 18 | function serialize_com_product_GetProductViaCategoryRequest(arg) { 19 | if (!(arg instanceof product_pb.GetProductViaCategoryRequest)) { 20 | throw new Error('Expected argument of type com.product.GetProductViaCategoryRequest'); 21 | } 22 | return Buffer.from(arg.serializeBinary()); 23 | } 24 | 25 | function deserialize_com_product_GetProductViaCategoryRequest(buffer_arg) { 26 | return product_pb.GetProductViaCategoryRequest.deserializeBinary(new Uint8Array(buffer_arg)); 27 | } 28 | 29 | function serialize_com_product_Product(arg) { 30 | if (!(arg instanceof product_pb.Product)) { 31 | throw new Error('Expected argument of type com.product.Product'); 32 | } 33 | return Buffer.from(arg.serializeBinary()); 34 | } 35 | 36 | function deserialize_com_product_Product(buffer_arg) { 37 | return product_pb.Product.deserializeBinary(new Uint8Array(buffer_arg)); 38 | } 39 | 40 | 41 | var ProductServiceService = exports.ProductServiceService = { 42 | getProduct: { 43 | path: '/com.product.ProductService/GetProduct', 44 | requestStream: false, 45 | responseStream: false, 46 | requestType: product_pb.GetProductRequest, 47 | responseType: product_pb.Product, 48 | requestSerialize: serialize_com_product_GetProductRequest, 49 | requestDeserialize: deserialize_com_product_GetProductRequest, 50 | responseSerialize: serialize_com_product_Product, 51 | responseDeserialize: deserialize_com_product_Product, 52 | }, 53 | getProductViaCategory: { 54 | path: '/com.product.ProductService/GetProductViaCategory', 55 | requestStream: false, 56 | responseStream: true, 57 | requestType: product_pb.GetProductViaCategoryRequest, 58 | responseType: product_pb.Product, 59 | requestSerialize: serialize_com_product_GetProductViaCategoryRequest, 60 | requestDeserialize: deserialize_com_product_GetProductViaCategoryRequest, 61 | responseSerialize: serialize_com_product_Product, 62 | responseDeserialize: deserialize_com_product_Product, 63 | }, 64 | getBestProduct: { 65 | path: '/com.product.ProductService/GetBestProduct', 66 | requestStream: true, 67 | responseStream: false, 68 | requestType: product_pb.GetProductRequest, 69 | responseType: product_pb.Product, 70 | requestSerialize: serialize_com_product_GetProductRequest, 71 | requestDeserialize: deserialize_com_product_GetProductRequest, 72 | responseSerialize: serialize_com_product_Product, 73 | responseDeserialize: deserialize_com_product_Product, 74 | }, 75 | getProducts: { 76 | path: '/com.product.ProductService/GetProducts', 77 | requestStream: true, 78 | responseStream: true, 79 | requestType: product_pb.GetProductRequest, 80 | responseType: product_pb.Product, 81 | requestSerialize: serialize_com_product_GetProductRequest, 82 | requestDeserialize: deserialize_com_product_GetProductRequest, 83 | responseSerialize: serialize_com_product_Product, 84 | responseDeserialize: deserialize_com_product_Product, 85 | }, 86 | }; 87 | 88 | exports.ProductServiceClient = grpc.makeGenericClientConstructor(ProductServiceService, 'ProductService'); 89 | -------------------------------------------------------------------------------- /examples/build/proto/product_grpc_pb.js: -------------------------------------------------------------------------------- 1 | // GENERATED CODE -- DO NOT EDIT! 2 | 3 | 'use strict'; 4 | var grpc = require('@grpc/grpc-js'); 5 | var product_pb = require('./product_pb.js'); 6 | 7 | function serialize_com_product_GetProductRequest(arg) { 8 | if (!(arg instanceof product_pb.GetProductRequest)) { 9 | throw new Error('Expected argument of type com.product.GetProductRequest'); 10 | } 11 | return Buffer.from(arg.serializeBinary()); 12 | } 13 | 14 | function deserialize_com_product_GetProductRequest(buffer_arg) { 15 | return product_pb.GetProductRequest.deserializeBinary(new Uint8Array(buffer_arg)); 16 | } 17 | 18 | function serialize_com_product_GetProductViaCategoryRequest(arg) { 19 | if (!(arg instanceof product_pb.GetProductViaCategoryRequest)) { 20 | throw new Error('Expected argument of type com.product.GetProductViaCategoryRequest'); 21 | } 22 | return Buffer.from(arg.serializeBinary()); 23 | } 24 | 25 | function deserialize_com_product_GetProductViaCategoryRequest(buffer_arg) { 26 | return product_pb.GetProductViaCategoryRequest.deserializeBinary(new Uint8Array(buffer_arg)); 27 | } 28 | 29 | function serialize_com_product_Product(arg) { 30 | if (!(arg instanceof product_pb.Product)) { 31 | throw new Error('Expected argument of type com.product.Product'); 32 | } 33 | return Buffer.from(arg.serializeBinary()); 34 | } 35 | 36 | function deserialize_com_product_Product(buffer_arg) { 37 | return product_pb.Product.deserializeBinary(new Uint8Array(buffer_arg)); 38 | } 39 | 40 | 41 | var ProductServiceService = exports.ProductServiceService = { 42 | getProduct: { 43 | path: '/com.product.ProductService/GetProduct', 44 | requestStream: false, 45 | responseStream: false, 46 | requestType: product_pb.GetProductRequest, 47 | responseType: product_pb.Product, 48 | requestSerialize: serialize_com_product_GetProductRequest, 49 | requestDeserialize: deserialize_com_product_GetProductRequest, 50 | responseSerialize: serialize_com_product_Product, 51 | responseDeserialize: deserialize_com_product_Product, 52 | }, 53 | getProductViaCategory: { 54 | path: '/com.product.ProductService/GetProductViaCategory', 55 | requestStream: false, 56 | responseStream: true, 57 | requestType: product_pb.GetProductViaCategoryRequest, 58 | responseType: product_pb.Product, 59 | requestSerialize: serialize_com_product_GetProductViaCategoryRequest, 60 | requestDeserialize: deserialize_com_product_GetProductViaCategoryRequest, 61 | responseSerialize: serialize_com_product_Product, 62 | responseDeserialize: deserialize_com_product_Product, 63 | }, 64 | getBestProduct: { 65 | path: '/com.product.ProductService/GetBestProduct', 66 | requestStream: true, 67 | responseStream: false, 68 | requestType: product_pb.GetProductRequest, 69 | responseType: product_pb.Product, 70 | requestSerialize: serialize_com_product_GetProductRequest, 71 | requestDeserialize: deserialize_com_product_GetProductRequest, 72 | responseSerialize: serialize_com_product_Product, 73 | responseDeserialize: deserialize_com_product_Product, 74 | }, 75 | getProducts: { 76 | path: '/com.product.ProductService/GetProducts', 77 | requestStream: true, 78 | responseStream: true, 79 | requestType: product_pb.GetProductRequest, 80 | responseType: product_pb.Product, 81 | requestSerialize: serialize_com_product_GetProductRequest, 82 | requestDeserialize: deserialize_com_product_GetProductRequest, 83 | responseSerialize: serialize_com_product_Product, 84 | responseDeserialize: deserialize_com_product_Product, 85 | }, 86 | }; 87 | 88 | exports.ProductServiceClient = grpc.makeGenericClientConstructor(ProductServiceService, 'ProductService'); 89 | -------------------------------------------------------------------------------- /examples/build/client.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"client.js","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":";;AAAA,+BAA+B;AAC/B,sCAAsC;AAEtC,6DAA6D;AAC7D,mDAA4F;AAE5F,MAAM,GAAG,GAAG,KAAK,CAAC,mBAAmB,CAAC,CAAC;AAEvC,MAAM,MAAM,GAAG,IAAI,sCAAoB,CAAC,iBAAiB,EAAE,IAAI,CAAC,WAAW,CAAC,cAAc,EAAE,CAAC,CAAC;AAE9F,MAAM,UAAU,GAAG,KAAK,EAAE,EAAU,EAAE,EAAE;IACpC,OAAO,IAAI,OAAO,CAAU,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QAC5C,MAAM,GAAG,GAAG,IAAI,8BAAiB,EAAE,CAAC;QACpC,GAAG,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;QAEd,GAAG,CAAC,yBAAyB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC;QAE/D,MAAM,CAAC,UAAU,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,IAAa,EAAE,EAAE;YACxC,IAAI,CAAC,EAAE;gBACH,KAAK,CAAC,mCAAmC,CAAC,CAAC,OAAO,iBAAiB,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC;gBAC9E,MAAM,CAAC,CAAC,CAAC,CAAC;gBACV,OAAO;aACV;YACD,GAAG,CAAC,0BAA0B,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC;YACjE,OAAO,CAAC,IAAI,CAAC,CAAC;QAClB,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACP,CAAC,CAAC;AAEF,MAAM,qBAAqB,GAAG,CAAC,QAAgB,EAAE,EAAE;IAC/C,OAAO,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACzC,MAAM,GAAG,GAAG,IAAI,yCAA4B,EAAE,CAAC;QAC/C,GAAG,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC;QAE1B,GAAG,CAAC,oCAAoC,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC;QAE1E,MAAM,MAAM,GAAuC,MAAM,CAAC,qBAAqB,CAAC,GAAG,CAAC,CAAC;QACrF,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,IAAa,EAAE,EAAE;YAChC,GAAG,CAAC,qCAAqC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC;QAChF,CAAC,CAAC,CAAC;QACH,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;YAClB,GAAG,CAAC,+BAA+B,CAAC,CAAC;YACrC,OAAO,EAAE,CAAC;QACd,CAAC,CAAC,CAAC;QACH,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE;YACrB,GAAG,CAAC,8CAA8C,CAAC,CAAC,OAAO,iBAAiB,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC;YACvF,MAAM,CAAC,CAAC,CAAC,CAAC;QACd,CAAC,CAAC,CAAC;IACP,CAAC,CAAC,CAAC;AACP,CAAC,CAAC;AAEF,MAAM,cAAc,GAAG,GAAG,EAAE;IACxB,OAAO,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACzC,MAAM,MAAM,GAAiD,MAAM,CAAC,cAAc,CAAC,CAAC,CAAC,EAAE,IAAa,EAAE,EAAE;YACpG,IAAI,CAAC,EAAE;gBACH,GAAG,CAAC,uCAAuC,CAAC,CAAC,OAAO,iBAAiB,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC;gBAChF,MAAM,CAAC,CAAC,CAAC,CAAC;gBACV,OAAO;aACV;YACD,GAAG,CAAC,8BAA8B,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC;YACrE,OAAO,EAAE,CAAC;QACd,CAAC,CAAC,CAAC;QAEH,KAAK,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,EAAE;YAC1B,MAAM,GAAG,GAAG,IAAI,8BAAiB,EAAE,CAAC;YACpC,GAAG,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YACb,GAAG,CAAC,8BAA8B,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC;YACpE,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;SACrB;QAED,MAAM,CAAC,GAAG,EAAE,CAAC;IACjB,CAAC,CAAC,CAAC;AACP,CAAC,CAAC;AAGF,MAAM,WAAW,GAAG,GAAG,EAAE;IACrB,OAAO,IAAI,OAAO,CAAO,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACzC,MAAM,MAAM,GAAwD,MAAM,CAAC,WAAW,EAAE,CAAC;QAEzF,MAAM,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,IAAa,EAAE,EAAE;YAChC,GAAG,CAAC,2BAA2B,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC;QACtE,CAAC,CAAC,CAAC;QACH,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,GAAG,EAAE;YAClB,GAAG,CAAC,qBAAqB,CAAC,CAAC;YAC3B,OAAO,EAAE,CAAC;QACd,CAAC,CAAC,CAAC;QACH,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,EAAE;YACrB,GAAG,CAAC,oCAAoC,CAAC,CAAC,OAAO,iBAAiB,CAAC,CAAC,KAAK,EAAE,CAAC,CAAC;YAC7E,MAAM,CAAC,CAAC,CAAC,CAAC;QACd,CAAC,CAAC,CAAC;QAEH,KAAK,IAAI,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,EAAE,EAAE,CAAC,EAAE,EAAE;YAC1B,MAAM,EAAE,GAAG,IAAI,8BAAiB,EAAE,CAAC;YACnC,EAAE,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YACZ,GAAG,CAAC,0BAA0B,IAAI,CAAC,SAAS,CAAC,EAAE,CAAC,QAAQ,EAAE,CAAC,EAAE,CAAC,CAAC;YAC/D,MAAM,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC;SACpB;QACD,MAAM,CAAC,GAAG,EAAE,CAAC;IACjB,CAAC,CAAC,CAAC;AACP,CAAC,CAAC;AAEF,KAAK,UAAU,IAAI;IACf,MAAM,UAAU,CAAC,CAAC,CAAC,CAAC;IACpB,MAAM,qBAAqB,CAAC,cAAc,CAAC,CAAC;IAC5C,MAAM,cAAc,EAAE,CAAC;IACvB,MAAM,WAAW,EAAE,CAAA;AACvB,CAAC;AAED,IAAI,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC;AAEtB,OAAO,CAAC,EAAE,CAAC,mBAAmB,EAAE,CAAC,GAAG,EAAE,EAAE;IACpC,GAAG,CAAC,uCAAuC,GAAG,EAAE,CAAC,CAAC;AACtD,CAAC,CAAC,CAAC;AAEH,OAAO,CAAC,EAAE,CAAC,oBAAoB,EAAE,CAAC,GAAG,EAAE,EAAE;IACrC,GAAG,CAAC,wCAAwC,GAAG,EAAE,CAAC,CAAC;AACvD,CAAC,CAAC,CAAC"} -------------------------------------------------------------------------------- /src/lib/EntryMap.ts: -------------------------------------------------------------------------------- 1 | import { 2 | DescriptorProto, 3 | EnumOptions, 4 | FieldDescriptorProto, 5 | FileDescriptorProto, 6 | MessageOptions 7 | } from 'google-protobuf/google/protobuf/descriptor_pb'; 8 | 9 | export type MessageEntry = { 10 | pkg: string, 11 | fileName: string, 12 | messageOptions: MessageOptions, 13 | mapFieldOptions?: { 14 | key: [FieldDescriptorProto.Type, string], 15 | value: [FieldDescriptorProto.Type, string], 16 | } 17 | } 18 | 19 | export type EnumEntry = { 20 | pkg: string, 21 | fileName: string, 22 | enumOptions: EnumOptions, 23 | } 24 | 25 | export class EntryMap { 26 | messageEntryMap: {[key: string]: MessageEntry} = {}; 27 | enumEntryMap: {[key: string]: EnumEntry} = {}; 28 | 29 | /** 30 | * 获取 MessageEntry 结构 31 | * 32 | * @param {string} scopeName 33 | * @return {MessageEntry | undefined} 34 | */ 35 | public getMessageEntry(scopeName: string): MessageEntry | undefined { 36 | return this.messageEntryMap[scopeName]; 37 | } 38 | 39 | /** 40 | * 获取 EnumEntry 41 | * 42 | * @param {string} scopeName 43 | * @return {EnumEntry | undefined} 44 | */ 45 | public getEnumEntry(scopeName: string): EnumEntry | undefined { 46 | return this.enumEntryMap[scopeName]; 47 | } 48 | 49 | /** 50 | * 将 fileDescriptor 中的内容进行解析,并填充到 messageEntry 和 enumEntry 中 51 | * 52 | * @param {FileDescriptorProto} fileDescriptor 53 | */ 54 | public parseFileDescriptor(fileDescriptor: FileDescriptorProto) { 55 | const scope = fileDescriptor.getPackage(); 56 | fileDescriptor.getMessageTypeList().forEach(messageType => { 57 | this.parseMessageNested(scope, fileDescriptor, messageType); 58 | }); 59 | 60 | fileDescriptor.getEnumTypeList().forEach(enumType => { 61 | this.enumEntryMap[scope + '.' + enumType.getName()] = { 62 | pkg: fileDescriptor.getPackage(), 63 | fileName: fileDescriptor.getName(), 64 | enumOptions: enumType.getOptions(), 65 | }; 66 | }); 67 | } 68 | 69 | /** 70 | * 解析 Message NestedType 71 | * 72 | * @param {string} scope 73 | * @param {FileDescriptorProto} fileDescriptor 74 | * @param {DescriptorProto} message 75 | */ 76 | private parseMessageNested(scope: string, fileDescriptor: FileDescriptorProto, message: DescriptorProto) { 77 | const messageEntry: MessageEntry = { 78 | pkg: fileDescriptor.getPackage(), 79 | fileName: fileDescriptor.getName(), 80 | messageOptions: message.getOptions(), 81 | mapFieldOptions: message.getOptions() && message.getOptions().getMapEntry() ? { 82 | key: [message.getFieldList()[0].getType(), message.getFieldList()[0].getTypeName().slice(1)], 83 | value: [message.getFieldList()[1].getType(), message.getFieldList()[1].getTypeName().slice(1)], 84 | } : undefined, 85 | }; 86 | 87 | const entryName = `${scope ? scope + '.' : ''}${message.getName()}`; 88 | this.messageEntryMap[entryName] = messageEntry; 89 | 90 | message.getNestedTypeList().forEach(nested => { 91 | this.parseMessageNested(scope + '.' + message.getName(), fileDescriptor, nested); 92 | }); 93 | 94 | message.getEnumTypeList().forEach(enumType => { 95 | const identifier = scope + '.' + message.getName() + '.' + enumType.getName(); 96 | this.enumEntryMap[identifier] = { 97 | pkg: fileDescriptor.getPackage(), 98 | fileName: fileDescriptor.getName(), 99 | enumOptions: enumType.getOptions(), 100 | }; 101 | }); 102 | } 103 | } -------------------------------------------------------------------------------- /examples/src/proto/product_pb.d.ts: -------------------------------------------------------------------------------- 1 | // package: com.product 2 | // file: product.proto 3 | 4 | import * as jspb from 'google-protobuf'; 5 | 6 | export class Product extends jspb.Message { 7 | getId(): number; 8 | setId(value: number): void; 9 | 10 | getName(): string; 11 | setName(value: string): void; 12 | 13 | getCategory(): string; 14 | setCategory(value: string): void; 15 | 16 | serializeBinary(): Uint8Array; 17 | toObject(includeInstance?: boolean): Product.AsObject; 18 | static toObject(includeInstance: boolean, msg: Product): Product.AsObject; 19 | static extensions: {[key: number]: jspb.ExtensionFieldInfo}; 20 | static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo}; 21 | static serializeBinaryToWriter(message: Product, writer: jspb.BinaryWriter): void; 22 | static deserializeBinary(bytes: Uint8Array): Product; 23 | static deserializeBinaryFromReader(message: Product, reader: jspb.BinaryReader): Product; 24 | } 25 | 26 | export namespace Product { 27 | export type AsObject = { 28 | id: number, 29 | name: string, 30 | category: string, 31 | } 32 | } 33 | 34 | export class GetProductRequest extends jspb.Message { 35 | getId(): number; 36 | setId(value: number): void; 37 | 38 | serializeBinary(): Uint8Array; 39 | toObject(includeInstance?: boolean): GetProductRequest.AsObject; 40 | static toObject(includeInstance: boolean, msg: GetProductRequest): GetProductRequest.AsObject; 41 | static extensions: {[key: number]: jspb.ExtensionFieldInfo}; 42 | static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo}; 43 | static serializeBinaryToWriter(message: GetProductRequest, writer: jspb.BinaryWriter): void; 44 | static deserializeBinary(bytes: Uint8Array): GetProductRequest; 45 | static deserializeBinaryFromReader(message: GetProductRequest, reader: jspb.BinaryReader): GetProductRequest; 46 | } 47 | 48 | export namespace GetProductRequest { 49 | export type AsObject = { 50 | id: number, 51 | } 52 | } 53 | 54 | export class GetProductViaCategoryRequest extends jspb.Message { 55 | getCategory(): string; 56 | setCategory(value: string): void; 57 | 58 | serializeBinary(): Uint8Array; 59 | toObject(includeInstance?: boolean): GetProductViaCategoryRequest.AsObject; 60 | static toObject(includeInstance: boolean, msg: GetProductViaCategoryRequest): GetProductViaCategoryRequest.AsObject; 61 | static extensions: {[key: number]: jspb.ExtensionFieldInfo}; 62 | static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo}; 63 | static serializeBinaryToWriter(message: GetProductViaCategoryRequest, writer: jspb.BinaryWriter): void; 64 | static deserializeBinary(bytes: Uint8Array): GetProductViaCategoryRequest; 65 | static deserializeBinaryFromReader(message: GetProductViaCategoryRequest, reader: jspb.BinaryReader): GetProductViaCategoryRequest; 66 | } 67 | 68 | export namespace GetProductViaCategoryRequest { 69 | export type AsObject = { 70 | category: string, 71 | } 72 | } 73 | 74 | export class Shop extends jspb.Message { 75 | getName(): string; 76 | setName(value: string): void; 77 | 78 | getListMap(): jspb.Map; 79 | clearListMap(): void; 80 | serializeBinary(): Uint8Array; 81 | toObject(includeInstance?: boolean): Shop.AsObject; 82 | static toObject(includeInstance: boolean, msg: Shop): Shop.AsObject; 83 | static extensions: {[key: number]: jspb.ExtensionFieldInfo}; 84 | static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo}; 85 | static serializeBinaryToWriter(message: Shop, writer: jspb.BinaryWriter): void; 86 | static deserializeBinary(bytes: Uint8Array): Shop; 87 | static deserializeBinaryFromReader(message: Shop, reader: jspb.BinaryReader): Shop; 88 | } 89 | 90 | export namespace Shop { 91 | export type AsObject = { 92 | name: string, 93 | listMap: Array<[number, Product.AsObject]>, 94 | } 95 | } 96 | 97 | -------------------------------------------------------------------------------- /examples/build/proto/product_pb.d.ts: -------------------------------------------------------------------------------- 1 | // package: com.product 2 | // file: product.proto 3 | 4 | import * as jspb from 'google-protobuf'; 5 | 6 | export class Product extends jspb.Message { 7 | getId(): number; 8 | setId(value: number): void; 9 | 10 | getName(): string; 11 | setName(value: string): void; 12 | 13 | getCategory(): string; 14 | setCategory(value: string): void; 15 | 16 | serializeBinary(): Uint8Array; 17 | toObject(includeInstance?: boolean): Product.AsObject; 18 | static toObject(includeInstance: boolean, msg: Product): Product.AsObject; 19 | static extensions: {[key: number]: jspb.ExtensionFieldInfo}; 20 | static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo}; 21 | static serializeBinaryToWriter(message: Product, writer: jspb.BinaryWriter): void; 22 | static deserializeBinary(bytes: Uint8Array): Product; 23 | static deserializeBinaryFromReader(message: Product, reader: jspb.BinaryReader): Product; 24 | } 25 | 26 | export namespace Product { 27 | export type AsObject = { 28 | id: number, 29 | name: string, 30 | category: string, 31 | } 32 | } 33 | 34 | export class GetProductRequest extends jspb.Message { 35 | getId(): number; 36 | setId(value: number): void; 37 | 38 | serializeBinary(): Uint8Array; 39 | toObject(includeInstance?: boolean): GetProductRequest.AsObject; 40 | static toObject(includeInstance: boolean, msg: GetProductRequest): GetProductRequest.AsObject; 41 | static extensions: {[key: number]: jspb.ExtensionFieldInfo}; 42 | static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo}; 43 | static serializeBinaryToWriter(message: GetProductRequest, writer: jspb.BinaryWriter): void; 44 | static deserializeBinary(bytes: Uint8Array): GetProductRequest; 45 | static deserializeBinaryFromReader(message: GetProductRequest, reader: jspb.BinaryReader): GetProductRequest; 46 | } 47 | 48 | export namespace GetProductRequest { 49 | export type AsObject = { 50 | id: number, 51 | } 52 | } 53 | 54 | export class GetProductViaCategoryRequest extends jspb.Message { 55 | getCategory(): string; 56 | setCategory(value: string): void; 57 | 58 | serializeBinary(): Uint8Array; 59 | toObject(includeInstance?: boolean): GetProductViaCategoryRequest.AsObject; 60 | static toObject(includeInstance: boolean, msg: GetProductViaCategoryRequest): GetProductViaCategoryRequest.AsObject; 61 | static extensions: {[key: number]: jspb.ExtensionFieldInfo}; 62 | static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo}; 63 | static serializeBinaryToWriter(message: GetProductViaCategoryRequest, writer: jspb.BinaryWriter): void; 64 | static deserializeBinary(bytes: Uint8Array): GetProductViaCategoryRequest; 65 | static deserializeBinaryFromReader(message: GetProductViaCategoryRequest, reader: jspb.BinaryReader): GetProductViaCategoryRequest; 66 | } 67 | 68 | export namespace GetProductViaCategoryRequest { 69 | export type AsObject = { 70 | category: string, 71 | } 72 | } 73 | 74 | export class Shop extends jspb.Message { 75 | getName(): string; 76 | setName(value: string): void; 77 | 78 | getListMap(): jspb.Map; 79 | clearListMap(): void; 80 | serializeBinary(): Uint8Array; 81 | toObject(includeInstance?: boolean): Shop.AsObject; 82 | static toObject(includeInstance: boolean, msg: Shop): Shop.AsObject; 83 | static extensions: {[key: number]: jspb.ExtensionFieldInfo}; 84 | static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo}; 85 | static serializeBinaryToWriter(message: Shop, writer: jspb.BinaryWriter): void; 86 | static deserializeBinary(bytes: Uint8Array): Shop; 87 | static deserializeBinaryFromReader(message: Shop, reader: jspb.BinaryReader): Shop; 88 | } 89 | 90 | export namespace Shop { 91 | export type AsObject = { 92 | name: string, 93 | listMap: Array<[number, Product.AsObject]>, 94 | } 95 | } 96 | 97 | -------------------------------------------------------------------------------- /examples/src/server.ts: -------------------------------------------------------------------------------- 1 | import * as debug from 'debug'; 2 | // support grpc-js 3 | import * as grpc from '@grpc/grpc-js'; 4 | // support grpc 5 | // import * as grpc from 'grpc'; 6 | 7 | import {IProductServiceServer, ProductServiceService} from './proto/product_grpc_pb'; 8 | import {GetProductRequest, GetProductViaCategoryRequest, Product} from './proto/product_pb'; 9 | 10 | const log = debug('[Demo:GrpcServer]'); 11 | 12 | const ServerImpl: IProductServiceServer = { 13 | 14 | getProduct: (call: grpc.ServerUnaryCall, callback: grpc.sendUnaryData): void => { 15 | log(`[getProduct] Request: ${JSON.stringify(call.request.toObject())}`); 16 | 17 | const vo = new Product(); 18 | vo.setId(call.request.getId()); 19 | vo.setName('DefaultName'); 20 | vo.setCategory('DefaultCategory'); 21 | 22 | log(`[getProduct] Done: ${JSON.stringify(vo.toObject())}`); 23 | callback(null, vo); 24 | }, 25 | 26 | getProductViaCategory: (call: grpc.ServerWritableStream): void => { 27 | log(`[getProductViaCategory] Request: ${JSON.stringify(call.request.toObject())}`); 28 | for (let i = 1; i <= 10; i++) { 29 | const vo = new Product(); 30 | vo.setId(i); 31 | vo.setName('DefaultName' + i); 32 | vo.setCategory('CategoryName=' + call.request.getCategory()); 33 | 34 | log(`[getProductViaCategory] Write: ${JSON.stringify(vo.toObject())}`); 35 | call.write(vo); 36 | } 37 | log('[getProductViaCategory] Done.'); 38 | call.end(); 39 | }, 40 | 41 | getBestProduct: (call: grpc.ServerReadableStream, callback: grpc.sendUnaryData): void => { 42 | let lastOne: GetProductRequest; 43 | call.on('data', (request: GetProductRequest) => { 44 | log(`[getBestProduct] Request: ${JSON.stringify(request.toObject())}`); 45 | lastOne = request; 46 | }); 47 | call.on('end', () => { 48 | const vo = new Product(); 49 | vo.setId(lastOne.getId()); 50 | vo.setName('LastOneName'); 51 | vo.setCategory('LastOneCategory'); 52 | 53 | log(`[getBestProduct] Done: ${JSON.stringify(vo.toObject())}`); 54 | callback(null, vo); 55 | }); 56 | call.on('error', (e) => { 57 | console.log(e); 58 | }); 59 | }, 60 | 61 | getProducts: (call: grpc.ServerDuplexStream): void => { 62 | call.on('data', (request: GetProductRequest) => { 63 | 64 | const vo = new Product(); 65 | vo.setId(request.getId()); 66 | vo.setName('NameOf' + request.getId()); 67 | vo.setCategory('CategoryOf' + request.getId()); 68 | 69 | log(`[getProducts] Write: ${JSON.stringify(vo.toObject())}`); 70 | call.write(vo); 71 | }); 72 | call.on('end', () => { 73 | log('[getProducts] Done.'); 74 | call.end(); 75 | }); 76 | call.on('error', (e) => { 77 | console.log(e); 78 | }); 79 | } 80 | }; 81 | 82 | function startServer() { 83 | const server = new grpc.Server(); 84 | // support grpc-js 85 | server.addService(ProductServiceService, ServerImpl); 86 | // support grpc-js 87 | // server.addService(ProductServiceService, new ServerImpl()); 88 | server.bindAsync('127.0.0.1:50051', grpc.ServerCredentials.createInsecure(), (e, port) => { 89 | if (e) throw e; 90 | log(`Server started, listening: 127.0.0.1:${port}`); 91 | }); 92 | } 93 | 94 | startServer(); 95 | 96 | process.on('uncaughtException', (err) => { 97 | log(`process on uncaughtException error: ${err}`); 98 | }); 99 | 100 | process.on('unhandledRejection', (err) => { 101 | log(`process on unhandledRejection error: ${err}`); 102 | }); 103 | -------------------------------------------------------------------------------- /examples/build/client.js: -------------------------------------------------------------------------------- 1 | "use strict"; 2 | Object.defineProperty(exports, "__esModule", { value: true }); 3 | const debug = require("debug"); 4 | const grpc = require("@grpc/grpc-js"); 5 | const product_grpc_pb_1 = require("./proto/product_grpc_pb"); 6 | const product_pb_1 = require("./proto/product_pb"); 7 | const log = debug('[Demo:GrpcClient]'); 8 | const client = new product_grpc_pb_1.ProductServiceClient('127.0.0.1:50051', grpc.credentials.createInsecure()); 9 | const getProduct = async (id) => { 10 | return new Promise((resolve, reject) => { 11 | const req = new product_pb_1.GetProductRequest(); 12 | req.setId(id); 13 | log(`[getProduct] Request: ${JSON.stringify(req.toObject())}`); 14 | client.getProduct(req, (e, data) => { 15 | if (e) { 16 | debug(`[getProduct] err:\nerr.message: ${e.message}\nerr.stack:\n${e.stack}`); 17 | reject(e); 18 | return; 19 | } 20 | log(`[getProduct] Response: ${JSON.stringify(data.toObject())}`); 21 | resolve(data); 22 | }); 23 | }); 24 | }; 25 | const getProductViaCategory = (category) => { 26 | return new Promise((resolve, reject) => { 27 | const req = new product_pb_1.GetProductViaCategoryRequest(); 28 | req.setCategory(category); 29 | log(`[getProductViaCategory] Request: ${JSON.stringify(req.toObject())}`); 30 | const stream = client.getProductViaCategory(req); 31 | stream.on('data', (data) => { 32 | log(`[getProductViaCategory] Response: ${JSON.stringify(data.toObject())}`); 33 | }); 34 | stream.on('end', () => { 35 | log('[getProductViaCategory] Done.'); 36 | resolve(); 37 | }); 38 | stream.on('error', (e) => { 39 | log(`[getProductViaCategory] err:\nerr.message: ${e.message}\nerr.stack:\n${e.stack}`); 40 | reject(e); 41 | }); 42 | }); 43 | }; 44 | const getBestProduct = () => { 45 | return new Promise((resolve, reject) => { 46 | const stream = client.getBestProduct((e, data) => { 47 | if (e) { 48 | log(`[getBestProduct] err:\nerr.message: ${e.message}\nerr.stack:\n${e.stack}`); 49 | reject(e); 50 | return; 51 | } 52 | log(`[getBestProduct] Response: ${JSON.stringify(data.toObject())}`); 53 | resolve(); 54 | }); 55 | for (let i = 15; i < 20; i++) { 56 | const req = new product_pb_1.GetProductRequest(); 57 | req.setId(i); 58 | log(`[getBestProduct] Response: ${JSON.stringify(req.toObject())}`); 59 | stream.write(req); 60 | } 61 | stream.end(); 62 | }); 63 | }; 64 | const getProducts = () => { 65 | return new Promise((resolve, reject) => { 66 | const stream = client.getProducts(); 67 | stream.on('data', (data) => { 68 | log(`[getProducts] Response: ${JSON.stringify(data.toObject())}`); 69 | }); 70 | stream.on('end', () => { 71 | log('[getProducts] Done.'); 72 | resolve(); 73 | }); 74 | stream.on('error', (e) => { 75 | log(`[getProducts] err:\nerr.message: ${e.message}\nerr.stack:\n${e.stack}`); 76 | reject(e); 77 | }); 78 | for (let i = 15; i < 20; i++) { 79 | const vo = new product_pb_1.GetProductRequest(); 80 | vo.setId(i); 81 | log(`[getProducts] Request: ${JSON.stringify(vo.toObject())}`); 82 | stream.write(vo); 83 | } 84 | stream.end(); 85 | }); 86 | }; 87 | async function main() { 88 | await getProduct(1); 89 | await getProductViaCategory('CategoryName'); 90 | await getBestProduct(); 91 | await getProducts(); 92 | } 93 | main().then((_) => _); 94 | process.on('uncaughtException', (err) => { 95 | log(`process on uncaughtException error: ${err}`); 96 | }); 97 | process.on('unhandledRejection', (err) => { 98 | log(`process on unhandledRejection error: ${err}`); 99 | }); 100 | //# sourceMappingURL=client.js.map -------------------------------------------------------------------------------- /examples/src/client.ts: -------------------------------------------------------------------------------- 1 | import * as debug from 'debug'; 2 | import * as grpc from '@grpc/grpc-js'; 3 | 4 | import {ProductServiceClient} from './proto/product_grpc_pb'; 5 | import {GetProductRequest, GetProductViaCategoryRequest, Product} from './proto/product_pb'; 6 | 7 | const log = debug('[Demo:GrpcClient]'); 8 | 9 | const client = new ProductServiceClient('127.0.0.1:50051', grpc.credentials.createInsecure()); 10 | 11 | const getProduct = async (id: number) => { 12 | return new Promise((resolve, reject) => { 13 | const req = new GetProductRequest(); 14 | req.setId(id); 15 | 16 | log(`[getProduct] Request: ${JSON.stringify(req.toObject())}`); 17 | 18 | client.getProduct(req, (e, data: Product) => { 19 | if (e) { 20 | debug(`[getProduct] err:\nerr.message: ${e.message}\nerr.stack:\n${e.stack}`); 21 | reject(e); 22 | return; 23 | } 24 | log(`[getProduct] Response: ${JSON.stringify(data.toObject())}`); 25 | resolve(data); 26 | }); 27 | }); 28 | }; 29 | 30 | const getProductViaCategory = (category: string) => { 31 | return new Promise((resolve, reject) => { 32 | const req = new GetProductViaCategoryRequest(); 33 | req.setCategory(category); 34 | 35 | log(`[getProductViaCategory] Request: ${JSON.stringify(req.toObject())}`); 36 | 37 | const stream: grpc.ClientReadableStream = client.getProductViaCategory(req); 38 | stream.on('data', (data: Product) => { 39 | log(`[getProductViaCategory] Response: ${JSON.stringify(data.toObject())}`); 40 | }); 41 | stream.on('end', () => { 42 | log('[getProductViaCategory] Done.'); 43 | resolve(); 44 | }); 45 | stream.on('error', (e) => { 46 | log(`[getProductViaCategory] err:\nerr.message: ${e.message}\nerr.stack:\n${e.stack}`); 47 | reject(e); 48 | }); 49 | }); 50 | }; 51 | 52 | const getBestProduct = () => { 53 | return new Promise((resolve, reject) => { 54 | const stream: grpc.ClientWritableStream = client.getBestProduct((e, data: Product) => { 55 | if (e) { 56 | log(`[getBestProduct] err:\nerr.message: ${e.message}\nerr.stack:\n${e.stack}`); 57 | reject(e); 58 | return; 59 | } 60 | log(`[getBestProduct] Response: ${JSON.stringify(data.toObject())}`); 61 | resolve(); 62 | }); 63 | 64 | for (let i = 15; i < 20; i++) { 65 | const req = new GetProductRequest(); 66 | req.setId(i); 67 | log(`[getBestProduct] Response: ${JSON.stringify(req.toObject())}`); 68 | stream.write(req); 69 | } 70 | 71 | stream.end(); 72 | }); 73 | }; 74 | 75 | 76 | const getProducts = () => { 77 | return new Promise((resolve, reject) => { 78 | const stream: grpc.ClientDuplexStream = client.getProducts(); 79 | 80 | stream.on('data', (data: Product) => { 81 | log(`[getProducts] Response: ${JSON.stringify(data.toObject())}`); 82 | }); 83 | stream.on('end', () => { 84 | log('[getProducts] Done.'); 85 | resolve(); 86 | }); 87 | stream.on('error', (e) => { 88 | log(`[getProducts] err:\nerr.message: ${e.message}\nerr.stack:\n${e.stack}`); 89 | reject(e); 90 | }); 91 | 92 | for (let i = 15; i < 20; i++) { 93 | const vo = new GetProductRequest(); 94 | vo.setId(i); 95 | log(`[getProducts] Request: ${JSON.stringify(vo.toObject())}`); 96 | stream.write(vo); 97 | } 98 | stream.end(); 99 | }); 100 | }; 101 | 102 | async function main() { 103 | await getProduct(1); 104 | await getProductViaCategory('CategoryName'); 105 | await getBestProduct(); 106 | await getProducts() 107 | } 108 | 109 | main().then((_) => _); 110 | 111 | process.on('uncaughtException', (err) => { 112 | log(`process on uncaughtException error: ${err}`); 113 | }); 114 | 115 | process.on('unhandledRejection', (err) => { 116 | log(`process on unhandledRejection error: ${err}`); 117 | }); 118 | -------------------------------------------------------------------------------- /src/lib/Utility.ts: -------------------------------------------------------------------------------- 1 | import {FileDescriptorProto} from 'google-protobuf/google/protobuf/descriptor_pb'; 2 | import {EnumEntry, MessageEntry} from './EntryMap'; 3 | 4 | const PROTO2_SYNTAX = 'proto2'; 5 | 6 | export namespace Utility { 7 | 8 | export function filePathToPseudoNamespace(filePath: string): string { 9 | return filePath.replace('.proto', '').replace(/\//g, '_').replace(/\./g, '_').replace(/\-/g, '_') + '_pb'; 10 | } 11 | 12 | export function snakeToCamel(str: string): string { 13 | return str.replace(/(\_\w)/g, function (m) { 14 | return m[1].toUpperCase(); 15 | }); 16 | } 17 | 18 | export function ucFirst(str: string): string { 19 | return str.charAt(0).toUpperCase() + str.slice(1); 20 | } 21 | 22 | export function lcFirst(str: string): string { 23 | return str.charAt(0).toLowerCase() + str.slice(1); 24 | } 25 | 26 | export function isProto2(fileDescriptor: FileDescriptorProto): boolean { 27 | // Empty syntax defaults to proto2 28 | return (fileDescriptor.getSyntax() === '' || fileDescriptor.getSyntax() === PROTO2_SYNTAX); 29 | } 30 | 31 | export function oneOfName(name: string) { 32 | return Utility.ucFirst(Utility.snakeToCamel(name)); 33 | } 34 | 35 | export function generateIndent(indentLevel: number): string { 36 | let indent = ''; 37 | for (let i = 0; i < indentLevel; i++) { 38 | indent += ' '; 39 | } 40 | return indent; 41 | } 42 | 43 | export function getPathToRoot(fileName: string) { 44 | const depth = fileName.split('/').length; 45 | return depth === 1 ? './' : new Array(depth).join('../'); 46 | } 47 | 48 | export function withinNamespaceFromExportEntry(name: string, exportEntry: MessageEntry | EnumEntry) { 49 | return exportEntry.pkg ? name.substring(exportEntry.pkg.length + 1) : name; 50 | } 51 | 52 | export function filePathFromProtoWithoutExtension(protoFilePath: string): string { 53 | return protoFilePath.replace('.proto', '_pb'); 54 | } 55 | 56 | export function svcFilePathFromProtoWithoutExtension(protoFilePath: string): string { 57 | return protoFilePath.replace('.proto', '_grpc_pb'); 58 | } 59 | 60 | export function withAllStdIn(callback: (buffer: Buffer) => void): void { 61 | const ret: Buffer[] = []; 62 | let len = 0; 63 | 64 | const stdin = process.stdin; 65 | stdin.on('readable', function () { 66 | let chunk; 67 | while ((chunk = stdin.read())) { 68 | if (!(chunk instanceof Buffer)) throw new Error('Did not receive buffer'); 69 | ret.push(chunk); 70 | len += chunk.length; 71 | } 72 | }); 73 | 74 | stdin.on('end', function () { 75 | callback(Buffer.concat(ret, len)); 76 | }); 77 | } 78 | 79 | // normaliseFieldObjectName modifies the field name that appears in the `asObject` representation 80 | // to match the logic found in `protobuf/compiler/js/js_generator.cc`. See: https://goo.gl/tX1dPQ 81 | export function normaliseFieldObjectName(name: string): string { 82 | switch (name) { 83 | case 'abstract': 84 | case 'boolean': 85 | case 'break': 86 | case 'byte': 87 | case 'case': 88 | case 'catch': 89 | case 'char': 90 | case 'class': 91 | case 'const': 92 | case 'continue': 93 | case 'debugger': 94 | case 'default': 95 | case 'delete': 96 | case 'do': 97 | case 'double': 98 | case 'else': 99 | case 'enum': 100 | case 'export': 101 | case 'extends': 102 | case 'false': 103 | case 'final': 104 | case 'finally': 105 | case 'float': 106 | case 'for': 107 | case 'function': 108 | case 'goto': 109 | case 'if': 110 | case 'implements': 111 | case 'import': 112 | case 'in': 113 | case 'instanceof': 114 | case 'int': 115 | case 'interface': 116 | case 'long': 117 | case 'native': 118 | case 'new': 119 | case 'null': 120 | case 'package': 121 | case 'private': 122 | case 'protected': 123 | case 'public': 124 | case 'return': 125 | case 'short': 126 | case 'static': 127 | case 'super': 128 | case 'switch': 129 | case 'synchronized': 130 | case 'this': 131 | case 'throw': 132 | case 'throws': 133 | case 'transient': 134 | case 'try': 135 | case 'typeof': 136 | case 'var': 137 | case 'void': 138 | case 'volatile': 139 | case 'while': 140 | case 'with': 141 | return `pb_${name}`; 142 | } 143 | return name; 144 | } 145 | } 146 | -------------------------------------------------------------------------------- /examples/build/proto/product_grpc_pb.d.ts: -------------------------------------------------------------------------------- 1 | // package: com.product 2 | // file: product.proto 3 | 4 | import * as grpc from '@grpc/grpc-js'; 5 | import * as product_pb from './product_pb'; 6 | 7 | interface IProductServiceService extends grpc.ServiceDefinition { 8 | getProduct: IProductServiceService_IGetProduct; 9 | getProductViaCategory: IProductServiceService_IGetProductViaCategory; 10 | getBestProduct: IProductServiceService_IGetBestProduct; 11 | getProducts: IProductServiceService_IGetProducts; 12 | } 13 | 14 | interface IProductServiceService_IGetProduct extends grpc.MethodDefinition { 15 | path: '/com.product.ProductService/GetProduct' 16 | requestStream: false 17 | responseStream: false 18 | requestSerialize: grpc.serialize; 19 | requestDeserialize: grpc.deserialize; 20 | responseSerialize: grpc.serialize; 21 | responseDeserialize: grpc.deserialize; 22 | } 23 | 24 | interface IProductServiceService_IGetProductViaCategory extends grpc.MethodDefinition { 25 | path: '/com.product.ProductService/GetProductViaCategory' 26 | requestStream: false 27 | responseStream: true 28 | requestSerialize: grpc.serialize; 29 | requestDeserialize: grpc.deserialize; 30 | responseSerialize: grpc.serialize; 31 | responseDeserialize: grpc.deserialize; 32 | } 33 | 34 | interface IProductServiceService_IGetBestProduct extends grpc.MethodDefinition { 35 | path: '/com.product.ProductService/GetBestProduct' 36 | requestStream: true 37 | responseStream: false 38 | requestSerialize: grpc.serialize; 39 | requestDeserialize: grpc.deserialize; 40 | responseSerialize: grpc.serialize; 41 | responseDeserialize: grpc.deserialize; 42 | } 43 | 44 | interface IProductServiceService_IGetProducts extends grpc.MethodDefinition { 45 | path: '/com.product.ProductService/GetProducts' 46 | requestStream: true 47 | responseStream: true 48 | requestSerialize: grpc.serialize; 49 | requestDeserialize: grpc.deserialize; 50 | responseSerialize: grpc.serialize; 51 | responseDeserialize: grpc.deserialize; 52 | } 53 | 54 | export const ProductServiceService: IProductServiceService; 55 | export interface IProductServiceServer extends grpc.UntypedServiceImplementation { 56 | getProduct: grpc.handleUnaryCall; 57 | getProductViaCategory: grpc.handleServerStreamingCall; 58 | getBestProduct: grpc.handleClientStreamingCall; 59 | getProducts: grpc.handleBidiStreamingCall; 60 | } 61 | 62 | export interface IProductServiceClient { 63 | getProduct(request: product_pb.GetProductRequest, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientUnaryCall; 64 | getProduct(request: product_pb.GetProductRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientUnaryCall; 65 | getProduct(request: product_pb.GetProductRequest, metadata: grpc.Metadata, options: Partial, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientUnaryCall; 66 | getProductViaCategory(request: product_pb.GetProductViaCategoryRequest, options?: Partial): grpc.ClientReadableStream; 67 | getProductViaCategory(request: product_pb.GetProductViaCategoryRequest, metadata?: grpc.Metadata, options?: Partial): grpc.ClientReadableStream; 68 | getBestProduct(callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 69 | getBestProduct(metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 70 | getBestProduct(options: Partial, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 71 | getBestProduct(metadata: grpc.Metadata, options: Partial, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 72 | getProducts(): grpc.ClientDuplexStream; 73 | getProducts(options: Partial): grpc.ClientDuplexStream; 74 | getProducts(metadata: grpc.Metadata, options?: Partial): grpc.ClientDuplexStream; 75 | } 76 | 77 | export class ProductServiceClient extends grpc.Client implements IProductServiceClient { 78 | constructor(address: string, credentials: grpc.ChannelCredentials, options?: Partial); 79 | public getProduct(request: product_pb.GetProductRequest, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientUnaryCall; 80 | public getProduct(request: product_pb.GetProductRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientUnaryCall; 81 | public getProduct(request: product_pb.GetProductRequest, metadata: grpc.Metadata, options: Partial, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientUnaryCall; 82 | public getProductViaCategory(request: product_pb.GetProductViaCategoryRequest, options?: Partial): grpc.ClientReadableStream; 83 | public getProductViaCategory(request: product_pb.GetProductViaCategoryRequest, metadata?: grpc.Metadata, options?: Partial): grpc.ClientReadableStream; 84 | public getBestProduct(callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 85 | public getBestProduct(metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 86 | public getBestProduct(options: Partial, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 87 | public getBestProduct(metadata: grpc.Metadata, options: Partial, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 88 | public getProducts(): grpc.ClientDuplexStream; 89 | public getProducts(options?: Partial): grpc.ClientDuplexStream; 90 | public getProducts(metadata?: grpc.Metadata, options?: Partial): grpc.ClientDuplexStream; 91 | } 92 | 93 | -------------------------------------------------------------------------------- /examples/src/proto/product_grpc_pb.d.ts: -------------------------------------------------------------------------------- 1 | // package: com.product 2 | // file: product.proto 3 | 4 | import * as grpc from '@grpc/grpc-js'; 5 | import * as product_pb from './product_pb'; 6 | 7 | interface IProductServiceService extends grpc.ServiceDefinition { 8 | getProduct: IProductServiceService_IGetProduct; 9 | getProductViaCategory: IProductServiceService_IGetProductViaCategory; 10 | getBestProduct: IProductServiceService_IGetBestProduct; 11 | getProducts: IProductServiceService_IGetProducts; 12 | } 13 | 14 | interface IProductServiceService_IGetProduct extends grpc.MethodDefinition { 15 | path: '/com.product.ProductService/GetProduct' 16 | requestStream: false 17 | responseStream: false 18 | requestSerialize: grpc.serialize; 19 | requestDeserialize: grpc.deserialize; 20 | responseSerialize: grpc.serialize; 21 | responseDeserialize: grpc.deserialize; 22 | } 23 | 24 | interface IProductServiceService_IGetProductViaCategory extends grpc.MethodDefinition { 25 | path: '/com.product.ProductService/GetProductViaCategory' 26 | requestStream: false 27 | responseStream: true 28 | requestSerialize: grpc.serialize; 29 | requestDeserialize: grpc.deserialize; 30 | responseSerialize: grpc.serialize; 31 | responseDeserialize: grpc.deserialize; 32 | } 33 | 34 | interface IProductServiceService_IGetBestProduct extends grpc.MethodDefinition { 35 | path: '/com.product.ProductService/GetBestProduct' 36 | requestStream: true 37 | responseStream: false 38 | requestSerialize: grpc.serialize; 39 | requestDeserialize: grpc.deserialize; 40 | responseSerialize: grpc.serialize; 41 | responseDeserialize: grpc.deserialize; 42 | } 43 | 44 | interface IProductServiceService_IGetProducts extends grpc.MethodDefinition { 45 | path: '/com.product.ProductService/GetProducts' 46 | requestStream: true 47 | responseStream: true 48 | requestSerialize: grpc.serialize; 49 | requestDeserialize: grpc.deserialize; 50 | responseSerialize: grpc.serialize; 51 | responseDeserialize: grpc.deserialize; 52 | } 53 | 54 | export const ProductServiceService: IProductServiceService; 55 | export interface IProductServiceServer extends grpc.UntypedServiceImplementation { 56 | getProduct: grpc.handleUnaryCall; 57 | getProductViaCategory: grpc.handleServerStreamingCall; 58 | getBestProduct: grpc.handleClientStreamingCall; 59 | getProducts: grpc.handleBidiStreamingCall; 60 | } 61 | 62 | export interface IProductServiceClient { 63 | getProduct(request: product_pb.GetProductRequest, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientUnaryCall; 64 | getProduct(request: product_pb.GetProductRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientUnaryCall; 65 | getProduct(request: product_pb.GetProductRequest, metadata: grpc.Metadata, options: Partial, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientUnaryCall; 66 | getProductViaCategory(request: product_pb.GetProductViaCategoryRequest, options?: Partial): grpc.ClientReadableStream; 67 | getProductViaCategory(request: product_pb.GetProductViaCategoryRequest, metadata?: grpc.Metadata, options?: Partial): grpc.ClientReadableStream; 68 | getBestProduct(callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 69 | getBestProduct(metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 70 | getBestProduct(options: Partial, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 71 | getBestProduct(metadata: grpc.Metadata, options: Partial, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 72 | getProducts(): grpc.ClientDuplexStream; 73 | getProducts(options: Partial): grpc.ClientDuplexStream; 74 | getProducts(metadata: grpc.Metadata, options?: Partial): grpc.ClientDuplexStream; 75 | } 76 | 77 | export class ProductServiceClient extends grpc.Client implements IProductServiceClient { 78 | constructor(address: string, credentials: grpc.ChannelCredentials, options?: Partial); 79 | public getProduct(request: product_pb.GetProductRequest, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientUnaryCall; 80 | public getProduct(request: product_pb.GetProductRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientUnaryCall; 81 | public getProduct(request: product_pb.GetProductRequest, metadata: grpc.Metadata, options: Partial, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientUnaryCall; 82 | public getProductViaCategory(request: product_pb.GetProductViaCategoryRequest, options?: Partial): grpc.ClientReadableStream; 83 | public getProductViaCategory(request: product_pb.GetProductViaCategoryRequest, metadata?: grpc.Metadata, options?: Partial): grpc.ClientReadableStream; 84 | public getBestProduct(callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 85 | public getBestProduct(metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 86 | public getBestProduct(options: Partial, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 87 | public getBestProduct(metadata: grpc.Metadata, options: Partial, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 88 | public getProducts(): grpc.ClientDuplexStream; 89 | public getProducts(options?: Partial): grpc.ClientDuplexStream; 90 | public getProducts(metadata?: grpc.Metadata, options?: Partial): grpc.ClientDuplexStream; 91 | } 92 | 93 | -------------------------------------------------------------------------------- /src/lib/descriptor/partial/Message.ts: -------------------------------------------------------------------------------- 1 | import { 2 | FieldDescriptorProto, 3 | FileDescriptorProto, 4 | DescriptorProto, 5 | OneofDescriptorProto 6 | } from 'google-protobuf/google/protobuf/descriptor_pb'; 7 | import {Printer} from '../../Printer'; 8 | import {EntryMap} from '../../EntryMap'; 9 | import {Utility} from '../../Utility'; 10 | import {BYTES_TYPE, ENUM_TYPE, MESSAGE_TYPE, FieldTypes} from './FieldTypes'; 11 | 12 | import {Enum} from './Enum'; 13 | import {OneOf} from './OneOf'; 14 | import {Extension} from './Extensions'; 15 | 16 | export const OBJECT_TYPE_NAME = 'AsObject'; 17 | 18 | export namespace Message { 19 | 20 | export interface MessageType { 21 | messageName: string; 22 | oneOfGroups: Array>; 23 | oneOfDeclList: Array; 24 | fields: Array; 25 | nestedTypes: Array; 26 | formattedEnumListStr: Array; 27 | formattedOneOfListStr: Array; 28 | formattedExtListStr: Array; 29 | } 30 | 31 | export const defaultMessageType = JSON.stringify({ 32 | messageName: '', 33 | oneOfGroups: [], 34 | oneOfDeclList: [], 35 | fields: [], 36 | nestedTypes: [], 37 | formattedEnumListStr: [], 38 | formattedOneOfListStr: [], 39 | formattedExtListStr: [], 40 | } as MessageType); 41 | 42 | export interface MessageFieldType { 43 | snakeCaseName: string; 44 | camelCaseName: string; 45 | camelUpperName: string; 46 | type: FieldDescriptorProto.Type; 47 | exportType: string; 48 | } 49 | 50 | export const defaultMessageFieldType = JSON.stringify({ 51 | snakeCaseName: '', 52 | camelCaseName: '', 53 | camelUpperName: '', 54 | type: undefined, 55 | exportType: '', 56 | } as MessageFieldType); 57 | 58 | export function hasFieldPresence(field: FieldDescriptorProto, fileDescriptor: FileDescriptorProto): boolean { 59 | if (field.getLabel() === FieldDescriptorProto.Label.LABEL_REPEATED) { 60 | return false; 61 | } 62 | 63 | if (field.hasOneofIndex()) { 64 | return true; 65 | } 66 | 67 | if (field.getType() === MESSAGE_TYPE) { 68 | return true; 69 | } 70 | 71 | return (Utility.isProto2(fileDescriptor)); 72 | } 73 | 74 | 75 | export function print(fileName: string, entryMap: EntryMap, descriptor: DescriptorProto, indentLevel: number, fileDescriptor: FileDescriptorProto) { 76 | 77 | let messageData = JSON.parse(defaultMessageType) as MessageType; 78 | 79 | messageData.messageName = descriptor.getName(); 80 | messageData.oneOfDeclList = descriptor.getOneofDeclList(); 81 | let messageOptions = descriptor.getOptions(); 82 | if (messageOptions !== undefined && messageOptions.getMapEntry()) { 83 | // this message type is the entry tuple for a map - don't output it 84 | return ''; 85 | } 86 | 87 | const printer = new Printer(indentLevel); 88 | printer.printEmptyLn(); 89 | printer.printLn(`export class ${messageData.messageName} extends jspb.Message {`); 90 | 91 | const printerToObjectType = new Printer(indentLevel + 1); 92 | printerToObjectType.printLn(`export type ${OBJECT_TYPE_NAME} = {`); 93 | 94 | const oneOfGroups: Array> = []; 95 | 96 | descriptor.getFieldList().forEach(field => { 97 | 98 | let fieldData = JSON.parse(defaultMessageFieldType) as MessageFieldType; 99 | 100 | if (field.hasOneofIndex()) { 101 | let oneOfIndex = field.getOneofIndex(); 102 | let existing = oneOfGroups[oneOfIndex]; 103 | if (existing === undefined) { 104 | existing = []; 105 | oneOfGroups[oneOfIndex] = existing; 106 | } 107 | existing.push(field); 108 | } 109 | 110 | fieldData.snakeCaseName = field.getName().toLowerCase(); 111 | fieldData.camelCaseName = Utility.snakeToCamel(fieldData.snakeCaseName); 112 | fieldData.camelUpperName = Utility.ucFirst(fieldData.camelCaseName); 113 | fieldData.type = field.getType(); 114 | 115 | let exportType; 116 | 117 | let fullTypeName = field.getTypeName().slice(1); 118 | let withinNamespace: string; 119 | switch (fieldData.type) { 120 | case MESSAGE_TYPE: 121 | const fieldMessageType = entryMap.getMessageEntry(fullTypeName); 122 | if (fieldMessageType === undefined) { 123 | throw new Error('No message export for: ' + fullTypeName); 124 | } 125 | 126 | if (fieldMessageType.messageOptions !== undefined && fieldMessageType.messageOptions.getMapEntry()) { 127 | let keyTuple = fieldMessageType.mapFieldOptions!.key; 128 | let keyType = keyTuple[0] as FieldDescriptorProto.Type; 129 | let keyTypeName = FieldTypes.getFieldType(keyType, keyTuple[1] as string, fileName, entryMap); 130 | let valueTuple = fieldMessageType.mapFieldOptions!.value; 131 | let valueType = valueTuple[0] as FieldDescriptorProto.Type; 132 | let valueTypeName = FieldTypes.getFieldType(valueType, valueTuple[1] as string, fileName, entryMap); 133 | if (valueType === BYTES_TYPE) { 134 | valueTypeName = 'Uint8Array | string'; 135 | } 136 | printer.printIndentedLn(`get${fieldData.camelUpperName}Map(): jspb.Map<${keyTypeName}, ${valueTypeName}>;`); 137 | printer.printIndentedLn(`clear${fieldData.camelUpperName}Map(): void;`); 138 | printerToObjectType.printIndentedLn(`${fieldData.camelCaseName}Map: Array<[${keyTypeName}${keyType === MESSAGE_TYPE ? '.AsObject' : ''}, ${valueTypeName}${valueType === MESSAGE_TYPE ? '.AsObject' : ''}]>,`); 139 | return; 140 | } 141 | 142 | withinNamespace = Utility.withinNamespaceFromExportEntry(fullTypeName, fieldMessageType); 143 | if (fieldMessageType.fileName === fileName) { 144 | exportType = withinNamespace; 145 | } else { 146 | exportType = Utility.filePathToPseudoNamespace(fieldMessageType.fileName) + '.' + withinNamespace; 147 | } 148 | fieldData.exportType = exportType; 149 | break; 150 | 151 | case ENUM_TYPE: 152 | let fieldEnumType = entryMap.getEnumEntry(fullTypeName); 153 | if (fieldEnumType === undefined) { 154 | throw new Error('No enum export for: ' + fullTypeName); 155 | } 156 | withinNamespace = Utility.withinNamespaceFromExportEntry(fullTypeName, fieldEnumType); 157 | if (fieldEnumType.fileName === fileName) { 158 | exportType = withinNamespace; 159 | } else { 160 | exportType = Utility.filePathToPseudoNamespace(fieldEnumType.fileName) + '.' + withinNamespace; 161 | } 162 | fieldData.exportType = exportType; 163 | break; 164 | 165 | default: 166 | fieldData.exportType = FieldTypes.getTypeName(fieldData.type); 167 | break; 168 | } 169 | 170 | let hasClearMethod = false; 171 | 172 | function printClearIfNotPresent() { 173 | if (!hasClearMethod) { 174 | hasClearMethod = true; 175 | printer.printIndentedLn(`clear${fieldData.camelUpperName}${field.getLabel() === FieldDescriptorProto.Label.LABEL_REPEATED ? 'List' : ''}(): void;`); 176 | } 177 | } 178 | 179 | function printRepeatedAddMethod(valueType: string) { 180 | const optionalValue = field.getType() === MESSAGE_TYPE; 181 | printer.printIndentedLn(`add${fieldData.camelUpperName}(value${optionalValue ? '?' : ''}: ${valueType}, index?: number): ${valueType};`); 182 | } 183 | 184 | if (Message.hasFieldPresence(field, fileDescriptor)) { 185 | printer.printIndentedLn(`has${fieldData.camelUpperName}(): boolean;`); 186 | printClearIfNotPresent(); 187 | } 188 | 189 | if (field.getLabel() === FieldDescriptorProto.Label.LABEL_REPEATED) {// is repeated 190 | printClearIfNotPresent(); 191 | 192 | if (fieldData.type === BYTES_TYPE) { 193 | printerToObjectType.printIndentedLn(`${fieldData.camelCaseName}List: Array,`); 194 | printer.printIndentedLn(`get${fieldData.camelUpperName}List(): Array;`); 195 | printer.printIndentedLn(`get${fieldData.camelUpperName}List_asU8(): Array;`); 196 | printer.printIndentedLn(`get${fieldData.camelUpperName}List_asB64(): Array;`); 197 | printer.printIndentedLn(`set${fieldData.camelUpperName}List(value: Array): void;`); 198 | printRepeatedAddMethod('Uint8Array | string'); 199 | } else { 200 | printerToObjectType.printIndentedLn(`${fieldData.camelCaseName}List: Array<${fieldData.exportType}${fieldData.type === MESSAGE_TYPE ? '.AsObject' : ''}>,`); 201 | printer.printIndentedLn(`get${fieldData.camelUpperName}List(): Array<${fieldData.exportType}>;`); 202 | printer.printIndentedLn(`set${fieldData.camelUpperName}List(value: Array<${fieldData.exportType}>): void;`); 203 | printRepeatedAddMethod(fieldData.exportType); 204 | } 205 | } else { 206 | if (fieldData.type === BYTES_TYPE) { 207 | printerToObjectType.printIndentedLn(`${fieldData.camelCaseName}: Uint8Array | string,`); 208 | printer.printIndentedLn(`get${fieldData.camelUpperName}(): Uint8Array | string;`); 209 | printer.printIndentedLn(`get${fieldData.camelUpperName}_asU8(): Uint8Array;`); 210 | printer.printIndentedLn(`get${fieldData.camelUpperName}_asB64(): string;`); 211 | printer.printIndentedLn(`set${fieldData.camelUpperName}(value: Uint8Array | string): void;`); 212 | } else { 213 | let fieldObjectType = fieldData.exportType; 214 | let canBeUndefined = false; 215 | if (fieldData.type === MESSAGE_TYPE) { 216 | fieldObjectType += '.AsObject'; 217 | if (!Utility.isProto2(fileDescriptor) || (field.getLabel() === FieldDescriptorProto.Label.LABEL_OPTIONAL)) { 218 | canBeUndefined = true; 219 | } 220 | } else { 221 | if (Utility.isProto2(fileDescriptor)) { 222 | canBeUndefined = true; 223 | } 224 | } 225 | const fieldObjectName = Utility.normaliseFieldObjectName(fieldData.camelCaseName); 226 | printerToObjectType.printIndentedLn(`${fieldObjectName}${canBeUndefined ? '?' : ''}: ${fieldObjectType},`); 227 | printer.printIndentedLn(`get${fieldData.camelUpperName}(): ${fieldData.exportType}${canBeUndefined ? ' | undefined' : ''};`); 228 | printer.printIndentedLn(`set${fieldData.camelUpperName}(value${fieldData.type === MESSAGE_TYPE ? '?' : ''}: ${fieldData.exportType}): void;`); 229 | } 230 | } 231 | 232 | printer.printEmptyLn(); 233 | }); 234 | 235 | printerToObjectType.printLn(`}`); 236 | 237 | descriptor.getOneofDeclList().forEach(oneOfDecl => { 238 | printer.printIndentedLn(`get${Utility.oneOfName(oneOfDecl.getName())}Case(): ${messageData.messageName}.${Utility.oneOfName(oneOfDecl.getName())}Case;`); 239 | }); 240 | 241 | printer.printIndentedLn(`serializeBinary(): Uint8Array;`); 242 | printer.printIndentedLn(`toObject(includeInstance?: boolean): ${messageData.messageName}.${OBJECT_TYPE_NAME};`); 243 | printer.printIndentedLn(`static toObject(includeInstance: boolean, msg: ${messageData.messageName}): ${messageData.messageName}.${OBJECT_TYPE_NAME};`); 244 | printer.printIndentedLn(`static extensions: {[key: number]: jspb.ExtensionFieldInfo};`); 245 | printer.printIndentedLn(`static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo};`); 246 | printer.printIndentedLn(`static serializeBinaryToWriter(message: ${messageData.messageName}, writer: jspb.BinaryWriter): void;`); 247 | printer.printIndentedLn(`static deserializeBinary(bytes: Uint8Array): ${messageData.messageName};`); 248 | printer.printIndentedLn(`static deserializeBinaryFromReader(message: ${messageData.messageName}, reader: jspb.BinaryReader): ${messageData.messageName};`); 249 | 250 | printer.printLn(`}`); 251 | printer.printEmptyLn(); 252 | 253 | printer.printLn(`export namespace ${messageData.messageName} {`); 254 | 255 | printer.print(printerToObjectType.getOutput()); 256 | 257 | descriptor.getNestedTypeList().forEach(nested => { 258 | const msgOutput = Message.print(fileName, entryMap, nested, indentLevel + 1, fileDescriptor); 259 | if (msgOutput !== '') { 260 | // If the message class is a Map entry then it isn't output, so don't print the namespace block 261 | printer.print(msgOutput); 262 | } 263 | }); 264 | descriptor.getEnumTypeList().forEach(enumType => { 265 | printer.print(`${Enum.print(enumType, indentLevel + 1)}`); 266 | }); 267 | descriptor.getOneofDeclList().forEach((oneOfDecl, index) => { 268 | printer.print(`${OneOf.print(oneOfDecl, oneOfGroups[index] || [], indentLevel + 1)}`); 269 | }); 270 | descriptor.getExtensionList().forEach(extension => { 271 | printer.print(Extension.print(fileName, entryMap, extension, indentLevel + 1)); 272 | }); 273 | 274 | printer.printLn(`}`); 275 | 276 | return printer.getOutput(); 277 | } 278 | } -------------------------------------------------------------------------------- /src/lib/descriptor/FileDescriptorGRPC.ts: -------------------------------------------------------------------------------- 1 | import { 2 | FileDescriptorProto, 3 | MethodDescriptorProto, 4 | ServiceDescriptorProto 5 | } from 'google-protobuf/google/protobuf/descriptor_pb'; 6 | 7 | import {EntryMap} from '../EntryMap'; 8 | import {Utility} from '../Utility'; 9 | import {Printer} from '../Printer'; 10 | import {DependencyTypesMap} from '../DependencyTypesMap'; 11 | import {DependencyFilter} from '../DependencyFilter'; 12 | 13 | import {FieldTypes, MESSAGE_TYPE} from './partial/FieldTypes'; 14 | 15 | export namespace FileDescriptorGRPC { 16 | 17 | export interface ServiceType { 18 | serviceName: string; 19 | methods: Array; 20 | } 21 | 22 | export const defaultServiceType = JSON.stringify({ 23 | serviceName: '', 24 | methods: [], 25 | } as ServiceType); 26 | 27 | export interface ServiceMethodType { 28 | packageName: string; 29 | serviceName: string; 30 | methodName: string; 31 | requestStream: boolean; 32 | responseStream: boolean; 33 | requestTypeName: string; 34 | responseTypeName: string; 35 | type: string; // 'ClientUnaryCall' || 'ClientWritableStream' || 'ClientReadableStream' || 'ClientDuplexStream' 36 | } 37 | 38 | export const defaultServiceMethodType = JSON.stringify({ 39 | packageName: '', 40 | serviceName: '', 41 | methodName: '', 42 | requestStream: false, 43 | responseStream: false, 44 | requestTypeName: '', 45 | responseTypeName: '', 46 | type: 'ClientUnaryCall', 47 | } as ServiceMethodType); 48 | 49 | export function print(fileDescriptor: FileDescriptorProto, entryMap: EntryMap, isGrpcJs: boolean): string { 50 | if (fileDescriptor.getServiceList().length === 0) { 51 | return ''; 52 | } 53 | 54 | const fileName = fileDescriptor.getName(); 55 | const packageName = fileDescriptor.getPackage(); 56 | const upToRoot = Utility.getPathToRoot(fileName); 57 | 58 | const printer = new Printer(0); 59 | printer.printLn(`// package: ${packageName}`); 60 | printer.printLn(`// file: ${fileDescriptor.getName()}`); 61 | printer.printEmptyLn(); 62 | 63 | // Need to import the non-service file that was generated for this .proto file 64 | if (isGrpcJs) { 65 | printer.printLn(`import * as grpc from '@grpc/grpc-js';`); 66 | } else { 67 | printer.printLn(`import * as grpc from 'grpc';`); 68 | } 69 | const asPseudoNamespace = Utility.filePathToPseudoNamespace(fileName); 70 | printer.printLn(`import * as ${asPseudoNamespace} from '${upToRoot}${Utility.filePathFromProtoWithoutExtension(fileName)}';`); 71 | 72 | fileDescriptor.getDependencyList().forEach((dependency: string) => { 73 | if (DependencyFilter.indexOf(dependency) !== -1) { 74 | return; // filtered 75 | } 76 | const pseudoNamespace = Utility.filePathToPseudoNamespace(dependency); 77 | if (dependency in DependencyTypesMap) { 78 | printer.printLn(`import * as ${pseudoNamespace} from '${DependencyTypesMap[dependency]}';`); 79 | } else { 80 | const filePath = Utility.filePathFromProtoWithoutExtension(dependency); 81 | printer.printLn(`import * as ${pseudoNamespace} from '${upToRoot + filePath}';`); 82 | } 83 | }); 84 | printer.printEmptyLn(); 85 | 86 | fileDescriptor.getServiceList().forEach((service: ServiceDescriptorProto) => { 87 | let serviceData = JSON.parse(defaultServiceType) as ServiceType; 88 | 89 | serviceData.serviceName = service.getName(); 90 | 91 | service.getMethodList().forEach((method: MethodDescriptorProto) => { 92 | let methodData = JSON.parse(defaultServiceMethodType) as ServiceMethodType; 93 | methodData.packageName = packageName; 94 | methodData.serviceName = serviceData.serviceName; 95 | methodData.methodName = method.getName(); 96 | methodData.requestStream = method.getClientStreaming(); 97 | methodData.responseStream = method.getServerStreaming(); 98 | methodData.requestTypeName = FieldTypes.getFieldType(MESSAGE_TYPE, method.getInputType().slice(1), '', entryMap); 99 | methodData.responseTypeName = FieldTypes.getFieldType(MESSAGE_TYPE, method.getOutputType().slice(1), '', entryMap); 100 | 101 | if (!method.getClientStreaming() && !method.getServerStreaming()) { 102 | methodData.type = 'ClientUnaryCall'; 103 | } else if (method.getClientStreaming() && !method.getServerStreaming()) { 104 | methodData.type = 'ClientWritableStream'; 105 | } else if (!method.getClientStreaming() && method.getServerStreaming()) { 106 | methodData.type = 'ClientReadableStream'; 107 | } else if (method.getClientStreaming() && method.getServerStreaming()) { 108 | methodData.type = 'ClientDuplexStream'; 109 | } 110 | 111 | serviceData.methods.push(methodData); 112 | }); 113 | 114 | // print service interface 115 | printer.printLn(`interface I${serviceData.serviceName}Service extends grpc.ServiceDefinition {`); 116 | serviceData.methods.forEach(methodData => { 117 | printer.printIndentedLn(`${Utility.lcFirst(methodData.methodName)}: I${serviceData.serviceName}Service_I${methodData.methodName};`); 118 | }); 119 | printer.printLn(`}`); 120 | printer.printEmptyLn(); 121 | 122 | // print method interface 123 | serviceData.methods.forEach(methodData => { 124 | printer.printLn(`interface I${serviceData.serviceName}Service_I${methodData.methodName} extends grpc.MethodDefinition<${methodData.requestTypeName}, ${methodData.responseTypeName}> {`); 125 | printer.printIndentedLn(`path: '/${methodData.packageName}.${methodData.serviceName}/${methodData.methodName}'`); 126 | printer.printIndentedLn(`requestStream: ${methodData.requestStream}`); 127 | printer.printIndentedLn(`responseStream: ${methodData.responseStream}`); 128 | printer.printIndentedLn(`requestSerialize: grpc.serialize<${methodData.requestTypeName}>;`); 129 | printer.printIndentedLn(`requestDeserialize: grpc.deserialize<${methodData.requestTypeName}>;`); 130 | printer.printIndentedLn(`responseSerialize: grpc.serialize<${methodData.responseTypeName}>;`); 131 | printer.printIndentedLn(`responseDeserialize: grpc.deserialize<${methodData.responseTypeName}>;`); 132 | printer.printLn(`}`); 133 | printer.printEmptyLn(); 134 | }); 135 | 136 | printer.printLn(`export const ${serviceData.serviceName}Service: I${serviceData.serviceName}Service;`); 137 | 138 | // print server interface 139 | printer.printLn(`export interface I${serviceData.serviceName}Server extends grpc.UntypedServiceImplementation {`); 140 | serviceData.methods.forEach((methodData) => { 141 | const methodName = Utility.lcFirst(methodData.methodName); 142 | const requestTypeName = methodData.requestTypeName; 143 | const responseTypeName = methodData.responseTypeName; 144 | 145 | switch (methodData.type) { 146 | case 'ClientUnaryCall': 147 | printer.printIndentedLn(`${methodName}: grpc.handleUnaryCall<${requestTypeName}, ${responseTypeName}>;`); 148 | break; 149 | case 'ClientWritableStream': 150 | printer.printIndentedLn(`${methodName}: grpc.handleClientStreamingCall<${requestTypeName}, ${responseTypeName}>;`); 151 | break; 152 | case 'ClientReadableStream': 153 | printer.printIndentedLn(`${methodName}: grpc.handleServerStreamingCall<${requestTypeName}, ${responseTypeName}>;`); 154 | break; 155 | case 'ClientDuplexStream': 156 | printer.printIndentedLn(`${methodName}: grpc.handleBidiStreamingCall<${requestTypeName}, ${responseTypeName}>;`); 157 | break; 158 | } 159 | 160 | }); 161 | printer.printLn(`}`); 162 | printer.printEmptyLn(); 163 | 164 | // print service client interface 165 | printer.printLn(`export interface I${serviceData.serviceName}Client {`); 166 | serviceData.methods.forEach(methodData => { 167 | const methodName = Utility.lcFirst(methodData.methodName); 168 | const requestTypeName = methodData.requestTypeName; 169 | const responseTypeName = methodData.responseTypeName; 170 | 171 | switch (methodData.type) { 172 | case 'ClientUnaryCall': 173 | printer.printIndentedLn(`${methodName}(request: ${requestTypeName}, callback: (error: grpc.ServiceError | null, response: ${responseTypeName}) => void): grpc.ClientUnaryCall;`); 174 | printer.printIndentedLn(`${methodName}(request: ${requestTypeName}, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: ${responseTypeName}) => void): grpc.ClientUnaryCall;`); 175 | printer.printIndentedLn(`${methodName}(request: ${requestTypeName}, metadata: grpc.Metadata, options: Partial, callback: (error: grpc.ServiceError | null, response: ${responseTypeName}) => void): grpc.ClientUnaryCall;`); 176 | break; 177 | case 'ClientReadableStream': 178 | printer.printIndentedLn(`${methodName}(request: ${requestTypeName}, options?: Partial): grpc.ClientReadableStream<${responseTypeName}>;`); 179 | printer.printIndentedLn(`${methodName}(request: ${requestTypeName}, metadata?: grpc.Metadata, options?: Partial): grpc.ClientReadableStream<${responseTypeName}>;`); 180 | break; 181 | case 'ClientWritableStream': 182 | printer.printIndentedLn(`${methodName}(callback: (error: grpc.ServiceError | null, response: ${responseTypeName}) => void): grpc.ClientWritableStream<${requestTypeName}>;`); 183 | printer.printIndentedLn(`${methodName}(metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: ${responseTypeName}) => void): grpc.ClientWritableStream<${requestTypeName}>;`); 184 | printer.printIndentedLn(`${methodName}(options: Partial, callback: (error: grpc.ServiceError | null, response: ${responseTypeName}) => void): grpc.ClientWritableStream<${requestTypeName}>;`); 185 | printer.printIndentedLn(`${methodName}(metadata: grpc.Metadata, options: Partial, callback: (error: grpc.ServiceError | null, response: ${responseTypeName}) => void): grpc.ClientWritableStream<${requestTypeName}>;`); 186 | break; 187 | case 'ClientDuplexStream': 188 | printer.printIndentedLn(`${methodName}(): grpc.ClientDuplexStream<${requestTypeName}, ${responseTypeName}>;`); 189 | printer.printIndentedLn(`${methodName}(options: Partial): grpc.ClientDuplexStream<${requestTypeName}, ${responseTypeName}>;`); 190 | printer.printIndentedLn(`${methodName}(metadata: grpc.Metadata, options?: Partial): grpc.ClientDuplexStream<${requestTypeName}, ${responseTypeName}>;`); 191 | break; 192 | } 193 | }); 194 | printer.printLn(`}`); 195 | printer.printEmptyLn(); 196 | 197 | // print service client 198 | printer.printLn(`export class ${serviceData.serviceName}Client extends grpc.Client implements I${serviceData.serviceName}Client {`); 199 | printer.printIndentedLn(`constructor(address: string, credentials: grpc.ChannelCredentials, options?: Partial);`); 200 | serviceData.methods.forEach(methodData => { 201 | const methodName = Utility.lcFirst(methodData.methodName); 202 | const requestTypeName = methodData.requestTypeName; 203 | const responseTypeName = methodData.responseTypeName; 204 | 205 | switch (methodData.type) { 206 | case 'ClientUnaryCall': 207 | printer.printIndentedLn(`public ${methodName}(request: ${requestTypeName}, callback: (error: grpc.ServiceError | null, response: ${responseTypeName}) => void): grpc.ClientUnaryCall;`); 208 | printer.printIndentedLn(`public ${methodName}(request: ${requestTypeName}, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: ${responseTypeName}) => void): grpc.ClientUnaryCall;`); 209 | printer.printIndentedLn(`public ${methodName}(request: ${requestTypeName}, metadata: grpc.Metadata, options: Partial, callback: (error: grpc.ServiceError | null, response: ${responseTypeName}) => void): grpc.ClientUnaryCall;`); 210 | break; 211 | case 'ClientReadableStream': 212 | printer.printIndentedLn(`public ${methodName}(request: ${requestTypeName}, options?: Partial): grpc.ClientReadableStream<${responseTypeName}>;`); 213 | printer.printIndentedLn(`public ${methodName}(request: ${requestTypeName}, metadata?: grpc.Metadata, options?: Partial): grpc.ClientReadableStream<${responseTypeName}>;`); 214 | break; 215 | case 'ClientWritableStream': 216 | printer.printIndentedLn(`public ${methodName}(callback: (error: grpc.ServiceError | null, response: ${responseTypeName}) => void): grpc.ClientWritableStream<${requestTypeName}>;`); 217 | printer.printIndentedLn(`public ${methodName}(metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: ${responseTypeName}) => void): grpc.ClientWritableStream<${requestTypeName}>;`); 218 | printer.printIndentedLn(`public ${methodName}(options: Partial, callback: (error: grpc.ServiceError | null, response: ${responseTypeName}) => void): grpc.ClientWritableStream<${requestTypeName}>;`); 219 | printer.printIndentedLn(`public ${methodName}(metadata: grpc.Metadata, options: Partial, callback: (error: grpc.ServiceError | null, response: ${responseTypeName}) => void): grpc.ClientWritableStream<${requestTypeName}>;`); 220 | break; 221 | case 'ClientDuplexStream': 222 | printer.printIndentedLn(`public ${methodName}(): grpc.ClientDuplexStream<${requestTypeName}, ${responseTypeName}>;`); 223 | printer.printIndentedLn(`public ${methodName}(options?: Partial): grpc.ClientDuplexStream<${requestTypeName}, ${responseTypeName}>;`); 224 | printer.printIndentedLn(`public ${methodName}(metadata?: grpc.Metadata, options?: Partial): grpc.ClientDuplexStream<${requestTypeName}, ${responseTypeName}>;`); 225 | break; 226 | } 227 | }); 228 | printer.printLn(`}`); 229 | printer.printEmptyLn(); 230 | 231 | }); 232 | 233 | return printer.getOutput(); 234 | } 235 | } 236 | 237 | 238 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | protoc-gen-grpc 2 | ========================= 3 | [![NPM Version][npm-image]][npm-url] 4 | [![NPM Downloads][downloads-image]][downloads-url] 5 | [![Build][travis-image]][travis-url] 6 | [![Test Coverage][coveralls-image]][coveralls-url] 7 | 8 | > Protocol compiler plugin for generating grpc interfaces in TypeScript. 9 | 10 | ## WARN 11 | 12 | > About Apple M1 arm64 13 | 14 | ```bash 15 | npm_config_target_arch=x64 npm i grpc-tools 16 | ``` 17 | 18 | > About node-pre-gyp ERR! stack Error: There was a fatal problem while downloading/extracting the tarball 19 | 20 | issue:https://github.com/mapbox/node-pre-gyp/issues/462 21 | 22 | ```bash 23 | npm install request -g 24 | ``` 25 | 26 | ## Install 27 | 28 | ```bash 29 | npm config set unsafe-perm true 30 | npm install protoc-gen-grpc -g 31 | ``` 32 | > If you don't want to set up a public configuration for NPM, you can try to add after the installation command `-unsafe-perm` parameters. 33 | 34 | ## How to use 35 | 36 | **Example** 37 | 38 | Please try ./example/build.sh 39 | 40 | **Support - grpc-js** 41 | 42 | bash 43 | 44 | ```bash 45 | # generate js codes with @grpc/grpc-js 46 | protoc-gen-grpc \ 47 | --js_out=import_style=commonjs,binary:${OUTPUT_DEST} \ 48 | --grpc_out=grpc_js:./examples/src/proto \ 49 | --proto_path ./examples/proto \ 50 | ./examples/proto/student.proto 51 | 52 | # generate d.ts codes with @grpc/grpc-js 53 | protoc-gen-grpc-ts \ 54 | --ts_out=grpc_js:./examples/src/proto \ 55 | --proto_path ./examples/proto \ 56 | ./examples/proto/student.proto 57 | ``` 58 | server.ts 59 | 60 | ```javascript 61 | // support grpc-js 62 | import * as grpc from '@grpc/grpc-js'; 63 | ... 64 | ... 65 | const server = new grpc.Server(); 66 | server.addService(ProductServiceService, ServerImpl); 67 | ``` 68 | 69 | **Support - grpc** 70 | 71 | bash 72 | 73 | ```bash 74 | # generate js codes with grpc 75 | protoc-gen-grpc \ 76 | --js_out=import_style=commonjs,binary:./examples/src/proto \ 77 | --grpc_out=./examples/src/proto \ 78 | --proto_path ./examples/proto \ 79 | ./examples/proto/student.proto 80 | 81 | # generate d.ts codes with grpc 82 | protoc-gen-grpc-ts \ 83 | --ts_out=./examples/src/proto \ 84 | --proto_path ./examples/proto \ 85 | ./examples/proto/student.proto 86 | ``` 87 | 88 | server.ts 89 | 90 | ```javascript 91 | // support grpc-js 92 | import * as grpc from 'grpc'; 93 | ... 94 | ... 95 | const server = new grpc.Server(); 96 | server.addService(ProductServiceService, new ServerImpl()); 97 | ``` 98 | 99 | ## Example 100 | 101 | There is a complete & runnable example in folder `examples`. 102 | 103 | ```bash 104 | ## bash1 105 | cd ./examples 106 | npm install 107 | sh ./bash/build.sh # build js & d.ts codes from proto file, and tsc to build/*.js 108 | sh ./bash/server.sh # start the grpc server 109 | 110 | ## bash2 111 | cd ./examples 112 | npm install 113 | sh ./bash/client.sh # start the grpc client & send requests 114 | ``` 115 | 116 | ### product.proto 117 | ```proto 118 | syntax = "proto3"; 119 | 120 | package com.product; 121 | 122 | message Product { 123 | int64 id = 1; 124 | string name = 2; 125 | string category = 3; 126 | } 127 | 128 | message GetProductRequest { 129 | int64 id = 1; 130 | } 131 | 132 | message GetProductViaCategoryRequest { 133 | string category = 1; 134 | } 135 | 136 | service ProductService { 137 | rpc GetProduct (GetProductRequest) returns (Product) {} 138 | rpc GetProductViaCategory (GetProductViaCategoryRequest) returns (stream Product) {} 139 | rpc GetBestProduct (stream GetProductRequest) returns (Product) {} 140 | rpc GetProducts (stream GetProductRequest) returns (stream Product) {} 141 | } 142 | 143 | message Shop { 144 | string name = 1; 145 | map list = 2; 146 | } 147 | ``` 148 | 149 | ### product_grpc_pb.d.ts 150 | ```typescript 151 | // package: com.product 152 | // file: product.proto 153 | 154 | import * as grpc from '@grpc/grpc-js'; 155 | import * as product_pb from './product_pb'; 156 | 157 | interface IProductServiceService extends grpc.ServiceDefinition { 158 | getProduct: IProductServiceService_IGetProduct; 159 | getProductViaCategory: IProductServiceService_IGetProductViaCategory; 160 | getBestProduct: IProductServiceService_IGetBestProduct; 161 | getProducts: IProductServiceService_IGetProducts; 162 | } 163 | 164 | interface IProductServiceService_IGetProduct extends grpc.MethodDefinition { 165 | path: '/com.product.ProductService/GetProduct' 166 | requestStream: false 167 | responseStream: false 168 | requestSerialize: grpc.serialize; 169 | requestDeserialize: grpc.deserialize; 170 | responseSerialize: grpc.serialize; 171 | responseDeserialize: grpc.deserialize; 172 | } 173 | 174 | interface IProductServiceService_IGetProductViaCategory extends grpc.MethodDefinition { 175 | path: '/com.product.ProductService/GetProductViaCategory' 176 | requestStream: false 177 | responseStream: true 178 | requestSerialize: grpc.serialize; 179 | requestDeserialize: grpc.deserialize; 180 | responseSerialize: grpc.serialize; 181 | responseDeserialize: grpc.deserialize; 182 | } 183 | 184 | interface IProductServiceService_IGetBestProduct extends grpc.MethodDefinition { 185 | path: '/com.product.ProductService/GetBestProduct' 186 | requestStream: true 187 | responseStream: false 188 | requestSerialize: grpc.serialize; 189 | requestDeserialize: grpc.deserialize; 190 | responseSerialize: grpc.serialize; 191 | responseDeserialize: grpc.deserialize; 192 | } 193 | 194 | interface IProductServiceService_IGetProducts extends grpc.MethodDefinition { 195 | path: '/com.product.ProductService/GetProducts' 196 | requestStream: true 197 | responseStream: true 198 | requestSerialize: grpc.serialize; 199 | requestDeserialize: grpc.deserialize; 200 | responseSerialize: grpc.serialize; 201 | responseDeserialize: grpc.deserialize; 202 | } 203 | 204 | export const ProductServiceService: IProductServiceService; 205 | export interface IProductServiceServer extends grpc.UntypedServiceImplementation { 206 | getProduct: grpc.handleUnaryCall; 207 | getProductViaCategory: grpc.handleServerStreamingCall; 208 | getBestProduct: grpc.handleClientStreamingCall; 209 | getProducts: grpc.handleBidiStreamingCall; 210 | } 211 | 212 | export interface IProductServiceClient { 213 | getProduct(request: product_pb.GetProductRequest, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientUnaryCall; 214 | getProduct(request: product_pb.GetProductRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientUnaryCall; 215 | getProduct(request: product_pb.GetProductRequest, metadata: grpc.Metadata, options: Partial, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientUnaryCall; 216 | getProductViaCategory(request: product_pb.GetProductViaCategoryRequest, options?: Partial): grpc.ClientReadableStream; 217 | getProductViaCategory(request: product_pb.GetProductViaCategoryRequest, metadata?: grpc.Metadata, options?: Partial): grpc.ClientReadableStream; 218 | getBestProduct(callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 219 | getBestProduct(metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 220 | getBestProduct(options: Partial, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 221 | getBestProduct(metadata: grpc.Metadata, options: Partial, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 222 | getProducts(): grpc.ClientDuplexStream; 223 | getProducts(options: Partial): grpc.ClientDuplexStream; 224 | getProducts(metadata: grpc.Metadata, options?: Partial): grpc.ClientDuplexStream; 225 | } 226 | 227 | export class ProductServiceClient extends grpc.Client implements IProductServiceClient { 228 | constructor(address: string, credentials: grpc.ChannelCredentials, options?: Partial); 229 | public getProduct(request: product_pb.GetProductRequest, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientUnaryCall; 230 | public getProduct(request: product_pb.GetProductRequest, metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientUnaryCall; 231 | public getProduct(request: product_pb.GetProductRequest, metadata: grpc.Metadata, options: Partial, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientUnaryCall; 232 | public getProductViaCategory(request: product_pb.GetProductViaCategoryRequest, options?: Partial): grpc.ClientReadableStream; 233 | public getProductViaCategory(request: product_pb.GetProductViaCategoryRequest, metadata?: grpc.Metadata, options?: Partial): grpc.ClientReadableStream; 234 | public getBestProduct(callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 235 | public getBestProduct(metadata: grpc.Metadata, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 236 | public getBestProduct(options: Partial, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 237 | public getBestProduct(metadata: grpc.Metadata, options: Partial, callback: (error: grpc.ServiceError | null, response: product_pb.Product) => void): grpc.ClientWritableStream; 238 | public getProducts(): grpc.ClientDuplexStream; 239 | public getProducts(options?: Partial): grpc.ClientDuplexStream; 240 | public getProducts(metadata?: grpc.Metadata, options?: Partial): grpc.ClientDuplexStream; 241 | } 242 | ``` 243 | 244 | ### product_pb.d.ts 245 | ```typescript 246 | // package: com.product 247 | // file: product.proto 248 | 249 | import * as jspb from 'google-protobuf'; 250 | 251 | export class Product extends jspb.Message { 252 | getId(): number; 253 | setId(value: number): void; 254 | 255 | getName(): string; 256 | setName(value: string): void; 257 | 258 | getCategory(): string; 259 | setCategory(value: string): void; 260 | 261 | serializeBinary(): Uint8Array; 262 | toObject(includeInstance?: boolean): Product.AsObject; 263 | static toObject(includeInstance: boolean, msg: Product): Product.AsObject; 264 | static extensions: {[key: number]: jspb.ExtensionFieldInfo}; 265 | static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo}; 266 | static serializeBinaryToWriter(message: Product, writer: jspb.BinaryWriter): void; 267 | static deserializeBinary(bytes: Uint8Array): Product; 268 | static deserializeBinaryFromReader(message: Product, reader: jspb.BinaryReader): Product; 269 | } 270 | 271 | export namespace Product { 272 | export type AsObject = { 273 | id: number, 274 | name: string, 275 | category: string, 276 | } 277 | } 278 | 279 | export class GetProductRequest extends jspb.Message { 280 | getId(): number; 281 | setId(value: number): void; 282 | 283 | serializeBinary(): Uint8Array; 284 | toObject(includeInstance?: boolean): GetProductRequest.AsObject; 285 | static toObject(includeInstance: boolean, msg: GetProductRequest): GetProductRequest.AsObject; 286 | static extensions: {[key: number]: jspb.ExtensionFieldInfo}; 287 | static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo}; 288 | static serializeBinaryToWriter(message: GetProductRequest, writer: jspb.BinaryWriter): void; 289 | static deserializeBinary(bytes: Uint8Array): GetProductRequest; 290 | static deserializeBinaryFromReader(message: GetProductRequest, reader: jspb.BinaryReader): GetProductRequest; 291 | } 292 | 293 | export namespace GetProductRequest { 294 | export type AsObject = { 295 | id: number, 296 | } 297 | } 298 | 299 | export class GetProductViaCategoryRequest extends jspb.Message { 300 | getCategory(): string; 301 | setCategory(value: string): void; 302 | 303 | serializeBinary(): Uint8Array; 304 | toObject(includeInstance?: boolean): GetProductViaCategoryRequest.AsObject; 305 | static toObject(includeInstance: boolean, msg: GetProductViaCategoryRequest): GetProductViaCategoryRequest.AsObject; 306 | static extensions: {[key: number]: jspb.ExtensionFieldInfo}; 307 | static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo}; 308 | static serializeBinaryToWriter(message: GetProductViaCategoryRequest, writer: jspb.BinaryWriter): void; 309 | static deserializeBinary(bytes: Uint8Array): GetProductViaCategoryRequest; 310 | static deserializeBinaryFromReader(message: GetProductViaCategoryRequest, reader: jspb.BinaryReader): GetProductViaCategoryRequest; 311 | } 312 | 313 | export namespace GetProductViaCategoryRequest { 314 | export type AsObject = { 315 | category: string, 316 | } 317 | } 318 | 319 | export class Shop extends jspb.Message { 320 | getName(): string; 321 | setName(value: string): void; 322 | 323 | getListMap(): jspb.Map; 324 | clearListMap(): void; 325 | serializeBinary(): Uint8Array; 326 | toObject(includeInstance?: boolean): Shop.AsObject; 327 | static toObject(includeInstance: boolean, msg: Shop): Shop.AsObject; 328 | static extensions: {[key: number]: jspb.ExtensionFieldInfo}; 329 | static extensionsBinary: {[key: number]: jspb.ExtensionFieldBinaryInfo}; 330 | static serializeBinaryToWriter(message: Shop, writer: jspb.BinaryWriter): void; 331 | static deserializeBinary(bytes: Uint8Array): Shop; 332 | static deserializeBinaryFromReader(message: Shop, reader: jspb.BinaryReader): Shop; 333 | } 334 | 335 | export namespace Shop { 336 | export type AsObject = { 337 | name: string, 338 | listMap: Array<[number, Product.AsObject]>, 339 | } 340 | } 341 | ``` 342 | 343 | ## License 344 | 345 | [MIT](LICENSE) 346 | 347 | [npm-image]: https://img.shields.io/npm/v/protoc-gen-grpc.svg 348 | [npm-url]: https://npmjs.org/package/protoc-gen-grpc 349 | [downloads-image]: https://img.shields.io/npm/dm/protoc-gen-grpc.svg 350 | [downloads-url]: https://npmjs.org/package/protoc-gen-grpc 351 | [travis-image]: https://app.travis-ci.com/stultuss/protoc-gen-grpc-ts.svg?branch=master 352 | [travis-url]: https://app.travis-ci.com/stultuss/protoc-gen-grpc-ts 353 | [travis-linux-image]: https://img.shields.io/travis/stultuss/protoc-gen-grpc-ts/master.svg?label=linux 354 | [travis-linux-url]: https://app.travis-ci.org/stultuss/protoc-gen-grpc-ts 355 | [travis-windows-image]: https://img.shields.io/travis/stultuss/protoc-gen-grpc-ts/master.svg?label=windows 356 | [travis-windows-url]: https://app.travis-ci.org/stultuss/protoc-gen-grpc-ts 357 | [coveralls-image]: https://img.shields.io/coveralls/stultuss/protoc-gen-grpc-ts/master.svg 358 | [coveralls-url]: https://coveralls.io/r/stultuss/protoc-gen-grpc-ts?branch=master 359 | -------------------------------------------------------------------------------- /examples/package-lock.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "example", 3 | "version": "2.0.1", 4 | "lockfileVersion": 3, 5 | "requires": true, 6 | "packages": { 7 | "": { 8 | "name": "example", 9 | "version": "2.0.1", 10 | "license": "MIT", 11 | "dependencies": { 12 | "@grpc/grpc-js": "~1.12.6", 13 | "debug": "^4.4.0", 14 | "google-protobuf": "~3.21.2" 15 | }, 16 | "devDependencies": { 17 | "@types/debug": "^4.1.12", 18 | "@types/node": "^18.19.0", 19 | "typescript": "^4.3.2" 20 | }, 21 | "engines": { 22 | "node": ">=16" 23 | } 24 | }, 25 | "node_modules/@grpc/grpc-js": { 26 | "version": "1.12.6", 27 | "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.12.6.tgz", 28 | "integrity": "sha512-JXUj6PI0oqqzTGvKtzOkxtpsyPRNsrmhh41TtIz/zEB6J+AUiZZ0dxWzcMwO9Ns5rmSPuMdghlTbUuqIM48d3Q==", 29 | "license": "Apache-2.0", 30 | "dependencies": { 31 | "@grpc/proto-loader": "^0.7.13", 32 | "@js-sdsl/ordered-map": "^4.4.2" 33 | }, 34 | "engines": { 35 | "node": ">=12.10.0" 36 | } 37 | }, 38 | "node_modules/@grpc/proto-loader": { 39 | "version": "0.7.13", 40 | "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.7.13.tgz", 41 | "integrity": "sha512-AiXO/bfe9bmxBjxxtYxFAXGZvMaN5s8kO+jBHAJCON8rJoB5YS/D6X7ZNc6XQkuHNmyl4CYaMI1fJ/Gn27RGGw==", 42 | "license": "Apache-2.0", 43 | "dependencies": { 44 | "lodash.camelcase": "^4.3.0", 45 | "long": "^5.0.0", 46 | "protobufjs": "^7.2.5", 47 | "yargs": "^17.7.2" 48 | }, 49 | "bin": { 50 | "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" 51 | }, 52 | "engines": { 53 | "node": ">=6" 54 | } 55 | }, 56 | "node_modules/@js-sdsl/ordered-map": { 57 | "version": "4.4.2", 58 | "resolved": "https://registry.npmjs.org/@js-sdsl/ordered-map/-/ordered-map-4.4.2.tgz", 59 | "integrity": "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw==", 60 | "license": "MIT", 61 | "funding": { 62 | "type": "opencollective", 63 | "url": "https://opencollective.com/js-sdsl" 64 | } 65 | }, 66 | "node_modules/@protobufjs/aspromise": { 67 | "version": "1.1.2", 68 | "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", 69 | "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==", 70 | "license": "BSD-3-Clause" 71 | }, 72 | "node_modules/@protobufjs/base64": { 73 | "version": "1.1.2", 74 | "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", 75 | "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==", 76 | "license": "BSD-3-Clause" 77 | }, 78 | "node_modules/@protobufjs/codegen": { 79 | "version": "2.0.4", 80 | "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.4.tgz", 81 | "integrity": "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==", 82 | "license": "BSD-3-Clause" 83 | }, 84 | "node_modules/@protobufjs/eventemitter": { 85 | "version": "1.1.0", 86 | "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz", 87 | "integrity": "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==", 88 | "license": "BSD-3-Clause" 89 | }, 90 | "node_modules/@protobufjs/fetch": { 91 | "version": "1.1.0", 92 | "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.0.tgz", 93 | "integrity": "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==", 94 | "license": "BSD-3-Clause", 95 | "dependencies": { 96 | "@protobufjs/aspromise": "^1.1.1", 97 | "@protobufjs/inquire": "^1.1.0" 98 | } 99 | }, 100 | "node_modules/@protobufjs/float": { 101 | "version": "1.0.2", 102 | "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", 103 | "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==", 104 | "license": "BSD-3-Clause" 105 | }, 106 | "node_modules/@protobufjs/inquire": { 107 | "version": "1.1.0", 108 | "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.0.tgz", 109 | "integrity": "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==", 110 | "license": "BSD-3-Clause" 111 | }, 112 | "node_modules/@protobufjs/path": { 113 | "version": "1.1.2", 114 | "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", 115 | "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==", 116 | "license": "BSD-3-Clause" 117 | }, 118 | "node_modules/@protobufjs/pool": { 119 | "version": "1.1.0", 120 | "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", 121 | "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==", 122 | "license": "BSD-3-Clause" 123 | }, 124 | "node_modules/@protobufjs/utf8": { 125 | "version": "1.1.0", 126 | "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.0.tgz", 127 | "integrity": "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==", 128 | "license": "BSD-3-Clause" 129 | }, 130 | "node_modules/@types/debug": { 131 | "version": "4.1.12", 132 | "resolved": "https://registry.npmjs.org/@types/debug/-/debug-4.1.12.tgz", 133 | "integrity": "sha512-vIChWdVG3LG1SMxEvI/AK+FWJthlrqlTu7fbrlywTkkaONwk/UAGaULXRlf8vkzFBLVm0zkMdCquhL5aOjhXPQ==", 134 | "dev": true, 135 | "license": "MIT", 136 | "dependencies": { 137 | "@types/ms": "*" 138 | } 139 | }, 140 | "node_modules/@types/ms": { 141 | "version": "2.1.0", 142 | "resolved": "https://registry.npmjs.org/@types/ms/-/ms-2.1.0.tgz", 143 | "integrity": "sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==", 144 | "dev": true, 145 | "license": "MIT" 146 | }, 147 | "node_modules/@types/node": { 148 | "version": "18.19.79", 149 | "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.79.tgz", 150 | "integrity": "sha512-90K8Oayimbctc5zTPHPfZloc/lGVs7f3phUAAMcTgEPtg8kKquGZDERC8K4vkBYkQQh48msiYUslYtxTWvqcAg==", 151 | "license": "MIT", 152 | "dependencies": { 153 | "undici-types": "~5.26.4" 154 | } 155 | }, 156 | "node_modules/ansi-regex": { 157 | "version": "5.0.1", 158 | "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", 159 | "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", 160 | "license": "MIT", 161 | "engines": { 162 | "node": ">=8" 163 | } 164 | }, 165 | "node_modules/ansi-styles": { 166 | "version": "4.3.0", 167 | "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", 168 | "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", 169 | "license": "MIT", 170 | "dependencies": { 171 | "color-convert": "^2.0.1" 172 | }, 173 | "engines": { 174 | "node": ">=8" 175 | }, 176 | "funding": { 177 | "url": "https://github.com/chalk/ansi-styles?sponsor=1" 178 | } 179 | }, 180 | "node_modules/cliui": { 181 | "version": "8.0.1", 182 | "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", 183 | "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", 184 | "license": "ISC", 185 | "dependencies": { 186 | "string-width": "^4.2.0", 187 | "strip-ansi": "^6.0.1", 188 | "wrap-ansi": "^7.0.0" 189 | }, 190 | "engines": { 191 | "node": ">=12" 192 | } 193 | }, 194 | "node_modules/color-convert": { 195 | "version": "2.0.1", 196 | "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", 197 | "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", 198 | "license": "MIT", 199 | "dependencies": { 200 | "color-name": "~1.1.4" 201 | }, 202 | "engines": { 203 | "node": ">=7.0.0" 204 | } 205 | }, 206 | "node_modules/color-name": { 207 | "version": "1.1.4", 208 | "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", 209 | "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", 210 | "license": "MIT" 211 | }, 212 | "node_modules/debug": { 213 | "version": "4.4.0", 214 | "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.0.tgz", 215 | "integrity": "sha512-6WTZ/IxCY/T6BALoZHaE4ctp9xm+Z5kY/pzYaCHRFeyVhojxlrm+46y68HA6hr0TcwEssoxNiDEUJQjfPZ/RYA==", 216 | "license": "MIT", 217 | "dependencies": { 218 | "ms": "^2.1.3" 219 | }, 220 | "engines": { 221 | "node": ">=6.0" 222 | }, 223 | "peerDependenciesMeta": { 224 | "supports-color": { 225 | "optional": true 226 | } 227 | } 228 | }, 229 | "node_modules/emoji-regex": { 230 | "version": "8.0.0", 231 | "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", 232 | "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", 233 | "license": "MIT" 234 | }, 235 | "node_modules/escalade": { 236 | "version": "3.2.0", 237 | "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", 238 | "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", 239 | "license": "MIT", 240 | "engines": { 241 | "node": ">=6" 242 | } 243 | }, 244 | "node_modules/get-caller-file": { 245 | "version": "2.0.5", 246 | "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", 247 | "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", 248 | "license": "ISC", 249 | "engines": { 250 | "node": "6.* || 8.* || >= 10.*" 251 | } 252 | }, 253 | "node_modules/google-protobuf": { 254 | "version": "3.21.4", 255 | "resolved": "https://registry.npmjs.org/google-protobuf/-/google-protobuf-3.21.4.tgz", 256 | "integrity": "sha512-MnG7N936zcKTco4Jd2PX2U96Kf9PxygAPKBug+74LHzmHXmceN16MmRcdgZv+DGef/S9YvQAfRsNCn4cjf9yyQ==", 257 | "license": "(BSD-3-Clause AND Apache-2.0)" 258 | }, 259 | "node_modules/is-fullwidth-code-point": { 260 | "version": "3.0.0", 261 | "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", 262 | "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", 263 | "license": "MIT", 264 | "engines": { 265 | "node": ">=8" 266 | } 267 | }, 268 | "node_modules/lodash.camelcase": { 269 | "version": "4.3.0", 270 | "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", 271 | "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==", 272 | "license": "MIT" 273 | }, 274 | "node_modules/long": { 275 | "version": "5.3.1", 276 | "resolved": "https://registry.npmjs.org/long/-/long-5.3.1.tgz", 277 | "integrity": "sha512-ka87Jz3gcx/I7Hal94xaN2tZEOPoUOEVftkQqZx2EeQRN7LGdfLlI3FvZ+7WDplm+vK2Urx9ULrvSowtdCieng==", 278 | "license": "Apache-2.0" 279 | }, 280 | "node_modules/ms": { 281 | "version": "2.1.3", 282 | "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", 283 | "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", 284 | "license": "MIT" 285 | }, 286 | "node_modules/protobufjs": { 287 | "version": "7.4.0", 288 | "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.4.0.tgz", 289 | "integrity": "sha512-mRUWCc3KUU4w1jU8sGxICXH/gNS94DvI1gxqDvBzhj1JpcsimQkYiOJfwsPUykUI5ZaspFbSgmBLER8IrQ3tqw==", 290 | "hasInstallScript": true, 291 | "license": "BSD-3-Clause", 292 | "dependencies": { 293 | "@protobufjs/aspromise": "^1.1.2", 294 | "@protobufjs/base64": "^1.1.2", 295 | "@protobufjs/codegen": "^2.0.4", 296 | "@protobufjs/eventemitter": "^1.1.0", 297 | "@protobufjs/fetch": "^1.1.0", 298 | "@protobufjs/float": "^1.0.2", 299 | "@protobufjs/inquire": "^1.1.0", 300 | "@protobufjs/path": "^1.1.2", 301 | "@protobufjs/pool": "^1.1.0", 302 | "@protobufjs/utf8": "^1.1.0", 303 | "@types/node": ">=13.7.0", 304 | "long": "^5.0.0" 305 | }, 306 | "engines": { 307 | "node": ">=12.0.0" 308 | } 309 | }, 310 | "node_modules/require-directory": { 311 | "version": "2.1.1", 312 | "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", 313 | "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", 314 | "license": "MIT", 315 | "engines": { 316 | "node": ">=0.10.0" 317 | } 318 | }, 319 | "node_modules/string-width": { 320 | "version": "4.2.3", 321 | "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", 322 | "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", 323 | "license": "MIT", 324 | "dependencies": { 325 | "emoji-regex": "^8.0.0", 326 | "is-fullwidth-code-point": "^3.0.0", 327 | "strip-ansi": "^6.0.1" 328 | }, 329 | "engines": { 330 | "node": ">=8" 331 | } 332 | }, 333 | "node_modules/strip-ansi": { 334 | "version": "6.0.1", 335 | "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", 336 | "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", 337 | "license": "MIT", 338 | "dependencies": { 339 | "ansi-regex": "^5.0.1" 340 | }, 341 | "engines": { 342 | "node": ">=8" 343 | } 344 | }, 345 | "node_modules/typescript": { 346 | "version": "4.9.5", 347 | "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.9.5.tgz", 348 | "integrity": "sha512-1FXk9E2Hm+QzZQ7z+McJiHL4NW1F2EzMu9Nq9i3zAaGqibafqYwCVU6WyWAuyQRRzOlxou8xZSyXLEN8oKj24g==", 349 | "dev": true, 350 | "license": "Apache-2.0", 351 | "bin": { 352 | "tsc": "bin/tsc", 353 | "tsserver": "bin/tsserver" 354 | }, 355 | "engines": { 356 | "node": ">=4.2.0" 357 | } 358 | }, 359 | "node_modules/undici-types": { 360 | "version": "5.26.5", 361 | "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", 362 | "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==", 363 | "license": "MIT" 364 | }, 365 | "node_modules/wrap-ansi": { 366 | "version": "7.0.0", 367 | "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", 368 | "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", 369 | "license": "MIT", 370 | "dependencies": { 371 | "ansi-styles": "^4.0.0", 372 | "string-width": "^4.1.0", 373 | "strip-ansi": "^6.0.0" 374 | }, 375 | "engines": { 376 | "node": ">=10" 377 | }, 378 | "funding": { 379 | "url": "https://github.com/chalk/wrap-ansi?sponsor=1" 380 | } 381 | }, 382 | "node_modules/y18n": { 383 | "version": "5.0.8", 384 | "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", 385 | "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", 386 | "license": "ISC", 387 | "engines": { 388 | "node": ">=10" 389 | } 390 | }, 391 | "node_modules/yargs": { 392 | "version": "17.7.2", 393 | "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", 394 | "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", 395 | "license": "MIT", 396 | "dependencies": { 397 | "cliui": "^8.0.1", 398 | "escalade": "^3.1.1", 399 | "get-caller-file": "^2.0.5", 400 | "require-directory": "^2.1.1", 401 | "string-width": "^4.2.3", 402 | "y18n": "^5.0.5", 403 | "yargs-parser": "^21.1.1" 404 | }, 405 | "engines": { 406 | "node": ">=12" 407 | } 408 | }, 409 | "node_modules/yargs-parser": { 410 | "version": "21.1.1", 411 | "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", 412 | "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", 413 | "license": "ISC", 414 | "engines": { 415 | "node": ">=12" 416 | } 417 | } 418 | } 419 | } 420 | -------------------------------------------------------------------------------- /examples/build/proto/product_pb.js: -------------------------------------------------------------------------------- 1 | // source: product.proto 2 | /** 3 | * @fileoverview 4 | * @enhanceable 5 | * @suppress {missingRequire} reports error on implicit type usages. 6 | * @suppress {messageConventions} JS Compiler reports an error if a variable or 7 | * field starts with 'MSG_' and isn't a translatable message. 8 | * @public 9 | */ 10 | // GENERATED CODE -- DO NOT EDIT! 11 | /* eslint-disable */ 12 | // @ts-nocheck 13 | 14 | var jspb = require('google-protobuf'); 15 | var goog = jspb; 16 | var global = (function() { 17 | if (this) { return this; } 18 | if (typeof window !== 'undefined') { return window; } 19 | if (typeof global !== 'undefined') { return global; } 20 | if (typeof self !== 'undefined') { return self; } 21 | return Function('return this')(); 22 | }.call(null)); 23 | 24 | goog.exportSymbol('proto.com.product.GetProductRequest', null, global); 25 | goog.exportSymbol('proto.com.product.GetProductViaCategoryRequest', null, global); 26 | goog.exportSymbol('proto.com.product.Product', null, global); 27 | goog.exportSymbol('proto.com.product.Shop', null, global); 28 | /** 29 | * Generated by JsPbCodeGenerator. 30 | * @param {Array=} opt_data Optional initial data array, typically from a 31 | * server response, or constructed directly in Javascript. The array is used 32 | * in place and becomes part of the constructed object. It is not cloned. 33 | * If no data is provided, the constructed object will be empty, but still 34 | * valid. 35 | * @extends {jspb.Message} 36 | * @constructor 37 | */ 38 | proto.com.product.Product = function(opt_data) { 39 | jspb.Message.initialize(this, opt_data, 0, -1, null, null); 40 | }; 41 | goog.inherits(proto.com.product.Product, jspb.Message); 42 | if (goog.DEBUG && !COMPILED) { 43 | /** 44 | * @public 45 | * @override 46 | */ 47 | proto.com.product.Product.displayName = 'proto.com.product.Product'; 48 | } 49 | /** 50 | * Generated by JsPbCodeGenerator. 51 | * @param {Array=} opt_data Optional initial data array, typically from a 52 | * server response, or constructed directly in Javascript. The array is used 53 | * in place and becomes part of the constructed object. It is not cloned. 54 | * If no data is provided, the constructed object will be empty, but still 55 | * valid. 56 | * @extends {jspb.Message} 57 | * @constructor 58 | */ 59 | proto.com.product.GetProductRequest = function(opt_data) { 60 | jspb.Message.initialize(this, opt_data, 0, -1, null, null); 61 | }; 62 | goog.inherits(proto.com.product.GetProductRequest, jspb.Message); 63 | if (goog.DEBUG && !COMPILED) { 64 | /** 65 | * @public 66 | * @override 67 | */ 68 | proto.com.product.GetProductRequest.displayName = 'proto.com.product.GetProductRequest'; 69 | } 70 | /** 71 | * Generated by JsPbCodeGenerator. 72 | * @param {Array=} opt_data Optional initial data array, typically from a 73 | * server response, or constructed directly in Javascript. The array is used 74 | * in place and becomes part of the constructed object. It is not cloned. 75 | * If no data is provided, the constructed object will be empty, but still 76 | * valid. 77 | * @extends {jspb.Message} 78 | * @constructor 79 | */ 80 | proto.com.product.GetProductViaCategoryRequest = function(opt_data) { 81 | jspb.Message.initialize(this, opt_data, 0, -1, null, null); 82 | }; 83 | goog.inherits(proto.com.product.GetProductViaCategoryRequest, jspb.Message); 84 | if (goog.DEBUG && !COMPILED) { 85 | /** 86 | * @public 87 | * @override 88 | */ 89 | proto.com.product.GetProductViaCategoryRequest.displayName = 'proto.com.product.GetProductViaCategoryRequest'; 90 | } 91 | /** 92 | * Generated by JsPbCodeGenerator. 93 | * @param {Array=} opt_data Optional initial data array, typically from a 94 | * server response, or constructed directly in Javascript. The array is used 95 | * in place and becomes part of the constructed object. It is not cloned. 96 | * If no data is provided, the constructed object will be empty, but still 97 | * valid. 98 | * @extends {jspb.Message} 99 | * @constructor 100 | */ 101 | proto.com.product.Shop = function(opt_data) { 102 | jspb.Message.initialize(this, opt_data, 0, -1, null, null); 103 | }; 104 | goog.inherits(proto.com.product.Shop, jspb.Message); 105 | if (goog.DEBUG && !COMPILED) { 106 | /** 107 | * @public 108 | * @override 109 | */ 110 | proto.com.product.Shop.displayName = 'proto.com.product.Shop'; 111 | } 112 | 113 | 114 | 115 | if (jspb.Message.GENERATE_TO_OBJECT) { 116 | /** 117 | * Creates an object representation of this proto. 118 | * Field names that are reserved in JavaScript and will be renamed to pb_name. 119 | * Optional fields that are not set will be set to undefined. 120 | * To access a reserved field use, foo.pb_, eg, foo.pb_default. 121 | * For the list of reserved names please see: 122 | * net/proto2/compiler/js/internal/generator.cc#kKeyword. 123 | * @param {boolean=} opt_includeInstance Deprecated. whether to include the 124 | * JSPB instance for transitional soy proto support: 125 | * http://goto/soy-param-migration 126 | * @return {!Object} 127 | */ 128 | proto.com.product.Product.prototype.toObject = function(opt_includeInstance) { 129 | return proto.com.product.Product.toObject(opt_includeInstance, this); 130 | }; 131 | 132 | 133 | /** 134 | * Static version of the {@see toObject} method. 135 | * @param {boolean|undefined} includeInstance Deprecated. Whether to include 136 | * the JSPB instance for transitional soy proto support: 137 | * http://goto/soy-param-migration 138 | * @param {!proto.com.product.Product} msg The msg instance to transform. 139 | * @return {!Object} 140 | * @suppress {unusedLocalVariables} f is only used for nested messages 141 | */ 142 | proto.com.product.Product.toObject = function(includeInstance, msg) { 143 | var f, obj = { 144 | id: jspb.Message.getFieldWithDefault(msg, 1, 0), 145 | name: jspb.Message.getFieldWithDefault(msg, 2, ""), 146 | category: jspb.Message.getFieldWithDefault(msg, 3, "") 147 | }; 148 | 149 | if (includeInstance) { 150 | obj.$jspbMessageInstance = msg; 151 | } 152 | return obj; 153 | }; 154 | } 155 | 156 | 157 | /** 158 | * Deserializes binary data (in protobuf wire format). 159 | * @param {jspb.ByteSource} bytes The bytes to deserialize. 160 | * @return {!proto.com.product.Product} 161 | */ 162 | proto.com.product.Product.deserializeBinary = function(bytes) { 163 | var reader = new jspb.BinaryReader(bytes); 164 | var msg = new proto.com.product.Product; 165 | return proto.com.product.Product.deserializeBinaryFromReader(msg, reader); 166 | }; 167 | 168 | 169 | /** 170 | * Deserializes binary data (in protobuf wire format) from the 171 | * given reader into the given message object. 172 | * @param {!proto.com.product.Product} msg The message object to deserialize into. 173 | * @param {!jspb.BinaryReader} reader The BinaryReader to use. 174 | * @return {!proto.com.product.Product} 175 | */ 176 | proto.com.product.Product.deserializeBinaryFromReader = function(msg, reader) { 177 | while (reader.nextField()) { 178 | if (reader.isEndGroup()) { 179 | break; 180 | } 181 | var field = reader.getFieldNumber(); 182 | switch (field) { 183 | case 1: 184 | var value = /** @type {number} */ (reader.readInt64()); 185 | msg.setId(value); 186 | break; 187 | case 2: 188 | var value = /** @type {string} */ (reader.readString()); 189 | msg.setName(value); 190 | break; 191 | case 3: 192 | var value = /** @type {string} */ (reader.readString()); 193 | msg.setCategory(value); 194 | break; 195 | default: 196 | reader.skipField(); 197 | break; 198 | } 199 | } 200 | return msg; 201 | }; 202 | 203 | 204 | /** 205 | * Serializes the message to binary data (in protobuf wire format). 206 | * @return {!Uint8Array} 207 | */ 208 | proto.com.product.Product.prototype.serializeBinary = function() { 209 | var writer = new jspb.BinaryWriter(); 210 | proto.com.product.Product.serializeBinaryToWriter(this, writer); 211 | return writer.getResultBuffer(); 212 | }; 213 | 214 | 215 | /** 216 | * Serializes the given message to binary data (in protobuf wire 217 | * format), writing to the given BinaryWriter. 218 | * @param {!proto.com.product.Product} message 219 | * @param {!jspb.BinaryWriter} writer 220 | * @suppress {unusedLocalVariables} f is only used for nested messages 221 | */ 222 | proto.com.product.Product.serializeBinaryToWriter = function(message, writer) { 223 | var f = undefined; 224 | f = message.getId(); 225 | if (f !== 0) { 226 | writer.writeInt64( 227 | 1, 228 | f 229 | ); 230 | } 231 | f = message.getName(); 232 | if (f.length > 0) { 233 | writer.writeString( 234 | 2, 235 | f 236 | ); 237 | } 238 | f = message.getCategory(); 239 | if (f.length > 0) { 240 | writer.writeString( 241 | 3, 242 | f 243 | ); 244 | } 245 | }; 246 | 247 | 248 | /** 249 | * optional int64 id = 1; 250 | * @return {number} 251 | */ 252 | proto.com.product.Product.prototype.getId = function() { 253 | return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); 254 | }; 255 | 256 | 257 | /** 258 | * @param {number} value 259 | * @return {!proto.com.product.Product} returns this 260 | */ 261 | proto.com.product.Product.prototype.setId = function(value) { 262 | return jspb.Message.setProto3IntField(this, 1, value); 263 | }; 264 | 265 | 266 | /** 267 | * optional string name = 2; 268 | * @return {string} 269 | */ 270 | proto.com.product.Product.prototype.getName = function() { 271 | return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); 272 | }; 273 | 274 | 275 | /** 276 | * @param {string} value 277 | * @return {!proto.com.product.Product} returns this 278 | */ 279 | proto.com.product.Product.prototype.setName = function(value) { 280 | return jspb.Message.setProto3StringField(this, 2, value); 281 | }; 282 | 283 | 284 | /** 285 | * optional string category = 3; 286 | * @return {string} 287 | */ 288 | proto.com.product.Product.prototype.getCategory = function() { 289 | return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); 290 | }; 291 | 292 | 293 | /** 294 | * @param {string} value 295 | * @return {!proto.com.product.Product} returns this 296 | */ 297 | proto.com.product.Product.prototype.setCategory = function(value) { 298 | return jspb.Message.setProto3StringField(this, 3, value); 299 | }; 300 | 301 | 302 | 303 | 304 | 305 | if (jspb.Message.GENERATE_TO_OBJECT) { 306 | /** 307 | * Creates an object representation of this proto. 308 | * Field names that are reserved in JavaScript and will be renamed to pb_name. 309 | * Optional fields that are not set will be set to undefined. 310 | * To access a reserved field use, foo.pb_, eg, foo.pb_default. 311 | * For the list of reserved names please see: 312 | * net/proto2/compiler/js/internal/generator.cc#kKeyword. 313 | * @param {boolean=} opt_includeInstance Deprecated. whether to include the 314 | * JSPB instance for transitional soy proto support: 315 | * http://goto/soy-param-migration 316 | * @return {!Object} 317 | */ 318 | proto.com.product.GetProductRequest.prototype.toObject = function(opt_includeInstance) { 319 | return proto.com.product.GetProductRequest.toObject(opt_includeInstance, this); 320 | }; 321 | 322 | 323 | /** 324 | * Static version of the {@see toObject} method. 325 | * @param {boolean|undefined} includeInstance Deprecated. Whether to include 326 | * the JSPB instance for transitional soy proto support: 327 | * http://goto/soy-param-migration 328 | * @param {!proto.com.product.GetProductRequest} msg The msg instance to transform. 329 | * @return {!Object} 330 | * @suppress {unusedLocalVariables} f is only used for nested messages 331 | */ 332 | proto.com.product.GetProductRequest.toObject = function(includeInstance, msg) { 333 | var f, obj = { 334 | id: jspb.Message.getFieldWithDefault(msg, 1, 0) 335 | }; 336 | 337 | if (includeInstance) { 338 | obj.$jspbMessageInstance = msg; 339 | } 340 | return obj; 341 | }; 342 | } 343 | 344 | 345 | /** 346 | * Deserializes binary data (in protobuf wire format). 347 | * @param {jspb.ByteSource} bytes The bytes to deserialize. 348 | * @return {!proto.com.product.GetProductRequest} 349 | */ 350 | proto.com.product.GetProductRequest.deserializeBinary = function(bytes) { 351 | var reader = new jspb.BinaryReader(bytes); 352 | var msg = new proto.com.product.GetProductRequest; 353 | return proto.com.product.GetProductRequest.deserializeBinaryFromReader(msg, reader); 354 | }; 355 | 356 | 357 | /** 358 | * Deserializes binary data (in protobuf wire format) from the 359 | * given reader into the given message object. 360 | * @param {!proto.com.product.GetProductRequest} msg The message object to deserialize into. 361 | * @param {!jspb.BinaryReader} reader The BinaryReader to use. 362 | * @return {!proto.com.product.GetProductRequest} 363 | */ 364 | proto.com.product.GetProductRequest.deserializeBinaryFromReader = function(msg, reader) { 365 | while (reader.nextField()) { 366 | if (reader.isEndGroup()) { 367 | break; 368 | } 369 | var field = reader.getFieldNumber(); 370 | switch (field) { 371 | case 1: 372 | var value = /** @type {number} */ (reader.readInt64()); 373 | msg.setId(value); 374 | break; 375 | default: 376 | reader.skipField(); 377 | break; 378 | } 379 | } 380 | return msg; 381 | }; 382 | 383 | 384 | /** 385 | * Serializes the message to binary data (in protobuf wire format). 386 | * @return {!Uint8Array} 387 | */ 388 | proto.com.product.GetProductRequest.prototype.serializeBinary = function() { 389 | var writer = new jspb.BinaryWriter(); 390 | proto.com.product.GetProductRequest.serializeBinaryToWriter(this, writer); 391 | return writer.getResultBuffer(); 392 | }; 393 | 394 | 395 | /** 396 | * Serializes the given message to binary data (in protobuf wire 397 | * format), writing to the given BinaryWriter. 398 | * @param {!proto.com.product.GetProductRequest} message 399 | * @param {!jspb.BinaryWriter} writer 400 | * @suppress {unusedLocalVariables} f is only used for nested messages 401 | */ 402 | proto.com.product.GetProductRequest.serializeBinaryToWriter = function(message, writer) { 403 | var f = undefined; 404 | f = message.getId(); 405 | if (f !== 0) { 406 | writer.writeInt64( 407 | 1, 408 | f 409 | ); 410 | } 411 | }; 412 | 413 | 414 | /** 415 | * optional int64 id = 1; 416 | * @return {number} 417 | */ 418 | proto.com.product.GetProductRequest.prototype.getId = function() { 419 | return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); 420 | }; 421 | 422 | 423 | /** 424 | * @param {number} value 425 | * @return {!proto.com.product.GetProductRequest} returns this 426 | */ 427 | proto.com.product.GetProductRequest.prototype.setId = function(value) { 428 | return jspb.Message.setProto3IntField(this, 1, value); 429 | }; 430 | 431 | 432 | 433 | 434 | 435 | if (jspb.Message.GENERATE_TO_OBJECT) { 436 | /** 437 | * Creates an object representation of this proto. 438 | * Field names that are reserved in JavaScript and will be renamed to pb_name. 439 | * Optional fields that are not set will be set to undefined. 440 | * To access a reserved field use, foo.pb_, eg, foo.pb_default. 441 | * For the list of reserved names please see: 442 | * net/proto2/compiler/js/internal/generator.cc#kKeyword. 443 | * @param {boolean=} opt_includeInstance Deprecated. whether to include the 444 | * JSPB instance for transitional soy proto support: 445 | * http://goto/soy-param-migration 446 | * @return {!Object} 447 | */ 448 | proto.com.product.GetProductViaCategoryRequest.prototype.toObject = function(opt_includeInstance) { 449 | return proto.com.product.GetProductViaCategoryRequest.toObject(opt_includeInstance, this); 450 | }; 451 | 452 | 453 | /** 454 | * Static version of the {@see toObject} method. 455 | * @param {boolean|undefined} includeInstance Deprecated. Whether to include 456 | * the JSPB instance for transitional soy proto support: 457 | * http://goto/soy-param-migration 458 | * @param {!proto.com.product.GetProductViaCategoryRequest} msg The msg instance to transform. 459 | * @return {!Object} 460 | * @suppress {unusedLocalVariables} f is only used for nested messages 461 | */ 462 | proto.com.product.GetProductViaCategoryRequest.toObject = function(includeInstance, msg) { 463 | var f, obj = { 464 | category: jspb.Message.getFieldWithDefault(msg, 1, "") 465 | }; 466 | 467 | if (includeInstance) { 468 | obj.$jspbMessageInstance = msg; 469 | } 470 | return obj; 471 | }; 472 | } 473 | 474 | 475 | /** 476 | * Deserializes binary data (in protobuf wire format). 477 | * @param {jspb.ByteSource} bytes The bytes to deserialize. 478 | * @return {!proto.com.product.GetProductViaCategoryRequest} 479 | */ 480 | proto.com.product.GetProductViaCategoryRequest.deserializeBinary = function(bytes) { 481 | var reader = new jspb.BinaryReader(bytes); 482 | var msg = new proto.com.product.GetProductViaCategoryRequest; 483 | return proto.com.product.GetProductViaCategoryRequest.deserializeBinaryFromReader(msg, reader); 484 | }; 485 | 486 | 487 | /** 488 | * Deserializes binary data (in protobuf wire format) from the 489 | * given reader into the given message object. 490 | * @param {!proto.com.product.GetProductViaCategoryRequest} msg The message object to deserialize into. 491 | * @param {!jspb.BinaryReader} reader The BinaryReader to use. 492 | * @return {!proto.com.product.GetProductViaCategoryRequest} 493 | */ 494 | proto.com.product.GetProductViaCategoryRequest.deserializeBinaryFromReader = function(msg, reader) { 495 | while (reader.nextField()) { 496 | if (reader.isEndGroup()) { 497 | break; 498 | } 499 | var field = reader.getFieldNumber(); 500 | switch (field) { 501 | case 1: 502 | var value = /** @type {string} */ (reader.readString()); 503 | msg.setCategory(value); 504 | break; 505 | default: 506 | reader.skipField(); 507 | break; 508 | } 509 | } 510 | return msg; 511 | }; 512 | 513 | 514 | /** 515 | * Serializes the message to binary data (in protobuf wire format). 516 | * @return {!Uint8Array} 517 | */ 518 | proto.com.product.GetProductViaCategoryRequest.prototype.serializeBinary = function() { 519 | var writer = new jspb.BinaryWriter(); 520 | proto.com.product.GetProductViaCategoryRequest.serializeBinaryToWriter(this, writer); 521 | return writer.getResultBuffer(); 522 | }; 523 | 524 | 525 | /** 526 | * Serializes the given message to binary data (in protobuf wire 527 | * format), writing to the given BinaryWriter. 528 | * @param {!proto.com.product.GetProductViaCategoryRequest} message 529 | * @param {!jspb.BinaryWriter} writer 530 | * @suppress {unusedLocalVariables} f is only used for nested messages 531 | */ 532 | proto.com.product.GetProductViaCategoryRequest.serializeBinaryToWriter = function(message, writer) { 533 | var f = undefined; 534 | f = message.getCategory(); 535 | if (f.length > 0) { 536 | writer.writeString( 537 | 1, 538 | f 539 | ); 540 | } 541 | }; 542 | 543 | 544 | /** 545 | * optional string category = 1; 546 | * @return {string} 547 | */ 548 | proto.com.product.GetProductViaCategoryRequest.prototype.getCategory = function() { 549 | return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); 550 | }; 551 | 552 | 553 | /** 554 | * @param {string} value 555 | * @return {!proto.com.product.GetProductViaCategoryRequest} returns this 556 | */ 557 | proto.com.product.GetProductViaCategoryRequest.prototype.setCategory = function(value) { 558 | return jspb.Message.setProto3StringField(this, 1, value); 559 | }; 560 | 561 | 562 | 563 | 564 | 565 | if (jspb.Message.GENERATE_TO_OBJECT) { 566 | /** 567 | * Creates an object representation of this proto. 568 | * Field names that are reserved in JavaScript and will be renamed to pb_name. 569 | * Optional fields that are not set will be set to undefined. 570 | * To access a reserved field use, foo.pb_, eg, foo.pb_default. 571 | * For the list of reserved names please see: 572 | * net/proto2/compiler/js/internal/generator.cc#kKeyword. 573 | * @param {boolean=} opt_includeInstance Deprecated. whether to include the 574 | * JSPB instance for transitional soy proto support: 575 | * http://goto/soy-param-migration 576 | * @return {!Object} 577 | */ 578 | proto.com.product.Shop.prototype.toObject = function(opt_includeInstance) { 579 | return proto.com.product.Shop.toObject(opt_includeInstance, this); 580 | }; 581 | 582 | 583 | /** 584 | * Static version of the {@see toObject} method. 585 | * @param {boolean|undefined} includeInstance Deprecated. Whether to include 586 | * the JSPB instance for transitional soy proto support: 587 | * http://goto/soy-param-migration 588 | * @param {!proto.com.product.Shop} msg The msg instance to transform. 589 | * @return {!Object} 590 | * @suppress {unusedLocalVariables} f is only used for nested messages 591 | */ 592 | proto.com.product.Shop.toObject = function(includeInstance, msg) { 593 | var f, obj = { 594 | name: jspb.Message.getFieldWithDefault(msg, 1, ""), 595 | listMap: (f = msg.getListMap()) ? f.toObject(includeInstance, proto.com.product.Product.toObject) : [] 596 | }; 597 | 598 | if (includeInstance) { 599 | obj.$jspbMessageInstance = msg; 600 | } 601 | return obj; 602 | }; 603 | } 604 | 605 | 606 | /** 607 | * Deserializes binary data (in protobuf wire format). 608 | * @param {jspb.ByteSource} bytes The bytes to deserialize. 609 | * @return {!proto.com.product.Shop} 610 | */ 611 | proto.com.product.Shop.deserializeBinary = function(bytes) { 612 | var reader = new jspb.BinaryReader(bytes); 613 | var msg = new proto.com.product.Shop; 614 | return proto.com.product.Shop.deserializeBinaryFromReader(msg, reader); 615 | }; 616 | 617 | 618 | /** 619 | * Deserializes binary data (in protobuf wire format) from the 620 | * given reader into the given message object. 621 | * @param {!proto.com.product.Shop} msg The message object to deserialize into. 622 | * @param {!jspb.BinaryReader} reader The BinaryReader to use. 623 | * @return {!proto.com.product.Shop} 624 | */ 625 | proto.com.product.Shop.deserializeBinaryFromReader = function(msg, reader) { 626 | while (reader.nextField()) { 627 | if (reader.isEndGroup()) { 628 | break; 629 | } 630 | var field = reader.getFieldNumber(); 631 | switch (field) { 632 | case 1: 633 | var value = /** @type {string} */ (reader.readString()); 634 | msg.setName(value); 635 | break; 636 | case 2: 637 | var value = msg.getListMap(); 638 | reader.readMessage(value, function(message, reader) { 639 | jspb.Map.deserializeBinary(message, reader, jspb.BinaryReader.prototype.readInt64, jspb.BinaryReader.prototype.readMessage, proto.com.product.Product.deserializeBinaryFromReader, 0, new proto.com.product.Product()); 640 | }); 641 | break; 642 | default: 643 | reader.skipField(); 644 | break; 645 | } 646 | } 647 | return msg; 648 | }; 649 | 650 | 651 | /** 652 | * Serializes the message to binary data (in protobuf wire format). 653 | * @return {!Uint8Array} 654 | */ 655 | proto.com.product.Shop.prototype.serializeBinary = function() { 656 | var writer = new jspb.BinaryWriter(); 657 | proto.com.product.Shop.serializeBinaryToWriter(this, writer); 658 | return writer.getResultBuffer(); 659 | }; 660 | 661 | 662 | /** 663 | * Serializes the given message to binary data (in protobuf wire 664 | * format), writing to the given BinaryWriter. 665 | * @param {!proto.com.product.Shop} message 666 | * @param {!jspb.BinaryWriter} writer 667 | * @suppress {unusedLocalVariables} f is only used for nested messages 668 | */ 669 | proto.com.product.Shop.serializeBinaryToWriter = function(message, writer) { 670 | var f = undefined; 671 | f = message.getName(); 672 | if (f.length > 0) { 673 | writer.writeString( 674 | 1, 675 | f 676 | ); 677 | } 678 | f = message.getListMap(true); 679 | if (f && f.getLength() > 0) { 680 | f.serializeBinary(2, writer, jspb.BinaryWriter.prototype.writeInt64, jspb.BinaryWriter.prototype.writeMessage, proto.com.product.Product.serializeBinaryToWriter); 681 | } 682 | }; 683 | 684 | 685 | /** 686 | * optional string name = 1; 687 | * @return {string} 688 | */ 689 | proto.com.product.Shop.prototype.getName = function() { 690 | return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); 691 | }; 692 | 693 | 694 | /** 695 | * @param {string} value 696 | * @return {!proto.com.product.Shop} returns this 697 | */ 698 | proto.com.product.Shop.prototype.setName = function(value) { 699 | return jspb.Message.setProto3StringField(this, 1, value); 700 | }; 701 | 702 | 703 | /** 704 | * map list = 2; 705 | * @param {boolean=} opt_noLazyCreate Do not create the map if 706 | * empty, instead returning `undefined` 707 | * @return {!jspb.Map} 708 | */ 709 | proto.com.product.Shop.prototype.getListMap = function(opt_noLazyCreate) { 710 | return /** @type {!jspb.Map} */ ( 711 | jspb.Message.getMapField(this, 2, opt_noLazyCreate, 712 | proto.com.product.Product)); 713 | }; 714 | 715 | 716 | /** 717 | * Clears values from the map. The map will be non-null. 718 | * @return {!proto.com.product.Shop} returns this 719 | */ 720 | proto.com.product.Shop.prototype.clearListMap = function() { 721 | this.getListMap().clear(); 722 | return this;}; 723 | 724 | 725 | goog.object.extend(exports, proto.com.product); 726 | -------------------------------------------------------------------------------- /examples/src/proto/product_pb.js: -------------------------------------------------------------------------------- 1 | // source: product.proto 2 | /** 3 | * @fileoverview 4 | * @enhanceable 5 | * @suppress {missingRequire} reports error on implicit type usages. 6 | * @suppress {messageConventions} JS Compiler reports an error if a variable or 7 | * field starts with 'MSG_' and isn't a translatable message. 8 | * @public 9 | */ 10 | // GENERATED CODE -- DO NOT EDIT! 11 | /* eslint-disable */ 12 | // @ts-nocheck 13 | 14 | var jspb = require('google-protobuf'); 15 | var goog = jspb; 16 | var global = (function() { 17 | if (this) { return this; } 18 | if (typeof window !== 'undefined') { return window; } 19 | if (typeof global !== 'undefined') { return global; } 20 | if (typeof self !== 'undefined') { return self; } 21 | return Function('return this')(); 22 | }.call(null)); 23 | 24 | goog.exportSymbol('proto.com.product.GetProductRequest', null, global); 25 | goog.exportSymbol('proto.com.product.GetProductViaCategoryRequest', null, global); 26 | goog.exportSymbol('proto.com.product.Product', null, global); 27 | goog.exportSymbol('proto.com.product.Shop', null, global); 28 | /** 29 | * Generated by JsPbCodeGenerator. 30 | * @param {Array=} opt_data Optional initial data array, typically from a 31 | * server response, or constructed directly in Javascript. The array is used 32 | * in place and becomes part of the constructed object. It is not cloned. 33 | * If no data is provided, the constructed object will be empty, but still 34 | * valid. 35 | * @extends {jspb.Message} 36 | * @constructor 37 | */ 38 | proto.com.product.Product = function(opt_data) { 39 | jspb.Message.initialize(this, opt_data, 0, -1, null, null); 40 | }; 41 | goog.inherits(proto.com.product.Product, jspb.Message); 42 | if (goog.DEBUG && !COMPILED) { 43 | /** 44 | * @public 45 | * @override 46 | */ 47 | proto.com.product.Product.displayName = 'proto.com.product.Product'; 48 | } 49 | /** 50 | * Generated by JsPbCodeGenerator. 51 | * @param {Array=} opt_data Optional initial data array, typically from a 52 | * server response, or constructed directly in Javascript. The array is used 53 | * in place and becomes part of the constructed object. It is not cloned. 54 | * If no data is provided, the constructed object will be empty, but still 55 | * valid. 56 | * @extends {jspb.Message} 57 | * @constructor 58 | */ 59 | proto.com.product.GetProductRequest = function(opt_data) { 60 | jspb.Message.initialize(this, opt_data, 0, -1, null, null); 61 | }; 62 | goog.inherits(proto.com.product.GetProductRequest, jspb.Message); 63 | if (goog.DEBUG && !COMPILED) { 64 | /** 65 | * @public 66 | * @override 67 | */ 68 | proto.com.product.GetProductRequest.displayName = 'proto.com.product.GetProductRequest'; 69 | } 70 | /** 71 | * Generated by JsPbCodeGenerator. 72 | * @param {Array=} opt_data Optional initial data array, typically from a 73 | * server response, or constructed directly in Javascript. The array is used 74 | * in place and becomes part of the constructed object. It is not cloned. 75 | * If no data is provided, the constructed object will be empty, but still 76 | * valid. 77 | * @extends {jspb.Message} 78 | * @constructor 79 | */ 80 | proto.com.product.GetProductViaCategoryRequest = function(opt_data) { 81 | jspb.Message.initialize(this, opt_data, 0, -1, null, null); 82 | }; 83 | goog.inherits(proto.com.product.GetProductViaCategoryRequest, jspb.Message); 84 | if (goog.DEBUG && !COMPILED) { 85 | /** 86 | * @public 87 | * @override 88 | */ 89 | proto.com.product.GetProductViaCategoryRequest.displayName = 'proto.com.product.GetProductViaCategoryRequest'; 90 | } 91 | /** 92 | * Generated by JsPbCodeGenerator. 93 | * @param {Array=} opt_data Optional initial data array, typically from a 94 | * server response, or constructed directly in Javascript. The array is used 95 | * in place and becomes part of the constructed object. It is not cloned. 96 | * If no data is provided, the constructed object will be empty, but still 97 | * valid. 98 | * @extends {jspb.Message} 99 | * @constructor 100 | */ 101 | proto.com.product.Shop = function(opt_data) { 102 | jspb.Message.initialize(this, opt_data, 0, -1, null, null); 103 | }; 104 | goog.inherits(proto.com.product.Shop, jspb.Message); 105 | if (goog.DEBUG && !COMPILED) { 106 | /** 107 | * @public 108 | * @override 109 | */ 110 | proto.com.product.Shop.displayName = 'proto.com.product.Shop'; 111 | } 112 | 113 | 114 | 115 | if (jspb.Message.GENERATE_TO_OBJECT) { 116 | /** 117 | * Creates an object representation of this proto. 118 | * Field names that are reserved in JavaScript and will be renamed to pb_name. 119 | * Optional fields that are not set will be set to undefined. 120 | * To access a reserved field use, foo.pb_, eg, foo.pb_default. 121 | * For the list of reserved names please see: 122 | * net/proto2/compiler/js/internal/generator.cc#kKeyword. 123 | * @param {boolean=} opt_includeInstance Deprecated. whether to include the 124 | * JSPB instance for transitional soy proto support: 125 | * http://goto/soy-param-migration 126 | * @return {!Object} 127 | */ 128 | proto.com.product.Product.prototype.toObject = function(opt_includeInstance) { 129 | return proto.com.product.Product.toObject(opt_includeInstance, this); 130 | }; 131 | 132 | 133 | /** 134 | * Static version of the {@see toObject} method. 135 | * @param {boolean|undefined} includeInstance Deprecated. Whether to include 136 | * the JSPB instance for transitional soy proto support: 137 | * http://goto/soy-param-migration 138 | * @param {!proto.com.product.Product} msg The msg instance to transform. 139 | * @return {!Object} 140 | * @suppress {unusedLocalVariables} f is only used for nested messages 141 | */ 142 | proto.com.product.Product.toObject = function(includeInstance, msg) { 143 | var f, obj = { 144 | id: jspb.Message.getFieldWithDefault(msg, 1, 0), 145 | name: jspb.Message.getFieldWithDefault(msg, 2, ""), 146 | category: jspb.Message.getFieldWithDefault(msg, 3, "") 147 | }; 148 | 149 | if (includeInstance) { 150 | obj.$jspbMessageInstance = msg; 151 | } 152 | return obj; 153 | }; 154 | } 155 | 156 | 157 | /** 158 | * Deserializes binary data (in protobuf wire format). 159 | * @param {jspb.ByteSource} bytes The bytes to deserialize. 160 | * @return {!proto.com.product.Product} 161 | */ 162 | proto.com.product.Product.deserializeBinary = function(bytes) { 163 | var reader = new jspb.BinaryReader(bytes); 164 | var msg = new proto.com.product.Product; 165 | return proto.com.product.Product.deserializeBinaryFromReader(msg, reader); 166 | }; 167 | 168 | 169 | /** 170 | * Deserializes binary data (in protobuf wire format) from the 171 | * given reader into the given message object. 172 | * @param {!proto.com.product.Product} msg The message object to deserialize into. 173 | * @param {!jspb.BinaryReader} reader The BinaryReader to use. 174 | * @return {!proto.com.product.Product} 175 | */ 176 | proto.com.product.Product.deserializeBinaryFromReader = function(msg, reader) { 177 | while (reader.nextField()) { 178 | if (reader.isEndGroup()) { 179 | break; 180 | } 181 | var field = reader.getFieldNumber(); 182 | switch (field) { 183 | case 1: 184 | var value = /** @type {number} */ (reader.readInt64()); 185 | msg.setId(value); 186 | break; 187 | case 2: 188 | var value = /** @type {string} */ (reader.readString()); 189 | msg.setName(value); 190 | break; 191 | case 3: 192 | var value = /** @type {string} */ (reader.readString()); 193 | msg.setCategory(value); 194 | break; 195 | default: 196 | reader.skipField(); 197 | break; 198 | } 199 | } 200 | return msg; 201 | }; 202 | 203 | 204 | /** 205 | * Serializes the message to binary data (in protobuf wire format). 206 | * @return {!Uint8Array} 207 | */ 208 | proto.com.product.Product.prototype.serializeBinary = function() { 209 | var writer = new jspb.BinaryWriter(); 210 | proto.com.product.Product.serializeBinaryToWriter(this, writer); 211 | return writer.getResultBuffer(); 212 | }; 213 | 214 | 215 | /** 216 | * Serializes the given message to binary data (in protobuf wire 217 | * format), writing to the given BinaryWriter. 218 | * @param {!proto.com.product.Product} message 219 | * @param {!jspb.BinaryWriter} writer 220 | * @suppress {unusedLocalVariables} f is only used for nested messages 221 | */ 222 | proto.com.product.Product.serializeBinaryToWriter = function(message, writer) { 223 | var f = undefined; 224 | f = message.getId(); 225 | if (f !== 0) { 226 | writer.writeInt64( 227 | 1, 228 | f 229 | ); 230 | } 231 | f = message.getName(); 232 | if (f.length > 0) { 233 | writer.writeString( 234 | 2, 235 | f 236 | ); 237 | } 238 | f = message.getCategory(); 239 | if (f.length > 0) { 240 | writer.writeString( 241 | 3, 242 | f 243 | ); 244 | } 245 | }; 246 | 247 | 248 | /** 249 | * optional int64 id = 1; 250 | * @return {number} 251 | */ 252 | proto.com.product.Product.prototype.getId = function() { 253 | return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); 254 | }; 255 | 256 | 257 | /** 258 | * @param {number} value 259 | * @return {!proto.com.product.Product} returns this 260 | */ 261 | proto.com.product.Product.prototype.setId = function(value) { 262 | return jspb.Message.setProto3IntField(this, 1, value); 263 | }; 264 | 265 | 266 | /** 267 | * optional string name = 2; 268 | * @return {string} 269 | */ 270 | proto.com.product.Product.prototype.getName = function() { 271 | return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 2, "")); 272 | }; 273 | 274 | 275 | /** 276 | * @param {string} value 277 | * @return {!proto.com.product.Product} returns this 278 | */ 279 | proto.com.product.Product.prototype.setName = function(value) { 280 | return jspb.Message.setProto3StringField(this, 2, value); 281 | }; 282 | 283 | 284 | /** 285 | * optional string category = 3; 286 | * @return {string} 287 | */ 288 | proto.com.product.Product.prototype.getCategory = function() { 289 | return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 3, "")); 290 | }; 291 | 292 | 293 | /** 294 | * @param {string} value 295 | * @return {!proto.com.product.Product} returns this 296 | */ 297 | proto.com.product.Product.prototype.setCategory = function(value) { 298 | return jspb.Message.setProto3StringField(this, 3, value); 299 | }; 300 | 301 | 302 | 303 | 304 | 305 | if (jspb.Message.GENERATE_TO_OBJECT) { 306 | /** 307 | * Creates an object representation of this proto. 308 | * Field names that are reserved in JavaScript and will be renamed to pb_name. 309 | * Optional fields that are not set will be set to undefined. 310 | * To access a reserved field use, foo.pb_, eg, foo.pb_default. 311 | * For the list of reserved names please see: 312 | * net/proto2/compiler/js/internal/generator.cc#kKeyword. 313 | * @param {boolean=} opt_includeInstance Deprecated. whether to include the 314 | * JSPB instance for transitional soy proto support: 315 | * http://goto/soy-param-migration 316 | * @return {!Object} 317 | */ 318 | proto.com.product.GetProductRequest.prototype.toObject = function(opt_includeInstance) { 319 | return proto.com.product.GetProductRequest.toObject(opt_includeInstance, this); 320 | }; 321 | 322 | 323 | /** 324 | * Static version of the {@see toObject} method. 325 | * @param {boolean|undefined} includeInstance Deprecated. Whether to include 326 | * the JSPB instance for transitional soy proto support: 327 | * http://goto/soy-param-migration 328 | * @param {!proto.com.product.GetProductRequest} msg The msg instance to transform. 329 | * @return {!Object} 330 | * @suppress {unusedLocalVariables} f is only used for nested messages 331 | */ 332 | proto.com.product.GetProductRequest.toObject = function(includeInstance, msg) { 333 | var f, obj = { 334 | id: jspb.Message.getFieldWithDefault(msg, 1, 0) 335 | }; 336 | 337 | if (includeInstance) { 338 | obj.$jspbMessageInstance = msg; 339 | } 340 | return obj; 341 | }; 342 | } 343 | 344 | 345 | /** 346 | * Deserializes binary data (in protobuf wire format). 347 | * @param {jspb.ByteSource} bytes The bytes to deserialize. 348 | * @return {!proto.com.product.GetProductRequest} 349 | */ 350 | proto.com.product.GetProductRequest.deserializeBinary = function(bytes) { 351 | var reader = new jspb.BinaryReader(bytes); 352 | var msg = new proto.com.product.GetProductRequest; 353 | return proto.com.product.GetProductRequest.deserializeBinaryFromReader(msg, reader); 354 | }; 355 | 356 | 357 | /** 358 | * Deserializes binary data (in protobuf wire format) from the 359 | * given reader into the given message object. 360 | * @param {!proto.com.product.GetProductRequest} msg The message object to deserialize into. 361 | * @param {!jspb.BinaryReader} reader The BinaryReader to use. 362 | * @return {!proto.com.product.GetProductRequest} 363 | */ 364 | proto.com.product.GetProductRequest.deserializeBinaryFromReader = function(msg, reader) { 365 | while (reader.nextField()) { 366 | if (reader.isEndGroup()) { 367 | break; 368 | } 369 | var field = reader.getFieldNumber(); 370 | switch (field) { 371 | case 1: 372 | var value = /** @type {number} */ (reader.readInt64()); 373 | msg.setId(value); 374 | break; 375 | default: 376 | reader.skipField(); 377 | break; 378 | } 379 | } 380 | return msg; 381 | }; 382 | 383 | 384 | /** 385 | * Serializes the message to binary data (in protobuf wire format). 386 | * @return {!Uint8Array} 387 | */ 388 | proto.com.product.GetProductRequest.prototype.serializeBinary = function() { 389 | var writer = new jspb.BinaryWriter(); 390 | proto.com.product.GetProductRequest.serializeBinaryToWriter(this, writer); 391 | return writer.getResultBuffer(); 392 | }; 393 | 394 | 395 | /** 396 | * Serializes the given message to binary data (in protobuf wire 397 | * format), writing to the given BinaryWriter. 398 | * @param {!proto.com.product.GetProductRequest} message 399 | * @param {!jspb.BinaryWriter} writer 400 | * @suppress {unusedLocalVariables} f is only used for nested messages 401 | */ 402 | proto.com.product.GetProductRequest.serializeBinaryToWriter = function(message, writer) { 403 | var f = undefined; 404 | f = message.getId(); 405 | if (f !== 0) { 406 | writer.writeInt64( 407 | 1, 408 | f 409 | ); 410 | } 411 | }; 412 | 413 | 414 | /** 415 | * optional int64 id = 1; 416 | * @return {number} 417 | */ 418 | proto.com.product.GetProductRequest.prototype.getId = function() { 419 | return /** @type {number} */ (jspb.Message.getFieldWithDefault(this, 1, 0)); 420 | }; 421 | 422 | 423 | /** 424 | * @param {number} value 425 | * @return {!proto.com.product.GetProductRequest} returns this 426 | */ 427 | proto.com.product.GetProductRequest.prototype.setId = function(value) { 428 | return jspb.Message.setProto3IntField(this, 1, value); 429 | }; 430 | 431 | 432 | 433 | 434 | 435 | if (jspb.Message.GENERATE_TO_OBJECT) { 436 | /** 437 | * Creates an object representation of this proto. 438 | * Field names that are reserved in JavaScript and will be renamed to pb_name. 439 | * Optional fields that are not set will be set to undefined. 440 | * To access a reserved field use, foo.pb_, eg, foo.pb_default. 441 | * For the list of reserved names please see: 442 | * net/proto2/compiler/js/internal/generator.cc#kKeyword. 443 | * @param {boolean=} opt_includeInstance Deprecated. whether to include the 444 | * JSPB instance for transitional soy proto support: 445 | * http://goto/soy-param-migration 446 | * @return {!Object} 447 | */ 448 | proto.com.product.GetProductViaCategoryRequest.prototype.toObject = function(opt_includeInstance) { 449 | return proto.com.product.GetProductViaCategoryRequest.toObject(opt_includeInstance, this); 450 | }; 451 | 452 | 453 | /** 454 | * Static version of the {@see toObject} method. 455 | * @param {boolean|undefined} includeInstance Deprecated. Whether to include 456 | * the JSPB instance for transitional soy proto support: 457 | * http://goto/soy-param-migration 458 | * @param {!proto.com.product.GetProductViaCategoryRequest} msg The msg instance to transform. 459 | * @return {!Object} 460 | * @suppress {unusedLocalVariables} f is only used for nested messages 461 | */ 462 | proto.com.product.GetProductViaCategoryRequest.toObject = function(includeInstance, msg) { 463 | var f, obj = { 464 | category: jspb.Message.getFieldWithDefault(msg, 1, "") 465 | }; 466 | 467 | if (includeInstance) { 468 | obj.$jspbMessageInstance = msg; 469 | } 470 | return obj; 471 | }; 472 | } 473 | 474 | 475 | /** 476 | * Deserializes binary data (in protobuf wire format). 477 | * @param {jspb.ByteSource} bytes The bytes to deserialize. 478 | * @return {!proto.com.product.GetProductViaCategoryRequest} 479 | */ 480 | proto.com.product.GetProductViaCategoryRequest.deserializeBinary = function(bytes) { 481 | var reader = new jspb.BinaryReader(bytes); 482 | var msg = new proto.com.product.GetProductViaCategoryRequest; 483 | return proto.com.product.GetProductViaCategoryRequest.deserializeBinaryFromReader(msg, reader); 484 | }; 485 | 486 | 487 | /** 488 | * Deserializes binary data (in protobuf wire format) from the 489 | * given reader into the given message object. 490 | * @param {!proto.com.product.GetProductViaCategoryRequest} msg The message object to deserialize into. 491 | * @param {!jspb.BinaryReader} reader The BinaryReader to use. 492 | * @return {!proto.com.product.GetProductViaCategoryRequest} 493 | */ 494 | proto.com.product.GetProductViaCategoryRequest.deserializeBinaryFromReader = function(msg, reader) { 495 | while (reader.nextField()) { 496 | if (reader.isEndGroup()) { 497 | break; 498 | } 499 | var field = reader.getFieldNumber(); 500 | switch (field) { 501 | case 1: 502 | var value = /** @type {string} */ (reader.readString()); 503 | msg.setCategory(value); 504 | break; 505 | default: 506 | reader.skipField(); 507 | break; 508 | } 509 | } 510 | return msg; 511 | }; 512 | 513 | 514 | /** 515 | * Serializes the message to binary data (in protobuf wire format). 516 | * @return {!Uint8Array} 517 | */ 518 | proto.com.product.GetProductViaCategoryRequest.prototype.serializeBinary = function() { 519 | var writer = new jspb.BinaryWriter(); 520 | proto.com.product.GetProductViaCategoryRequest.serializeBinaryToWriter(this, writer); 521 | return writer.getResultBuffer(); 522 | }; 523 | 524 | 525 | /** 526 | * Serializes the given message to binary data (in protobuf wire 527 | * format), writing to the given BinaryWriter. 528 | * @param {!proto.com.product.GetProductViaCategoryRequest} message 529 | * @param {!jspb.BinaryWriter} writer 530 | * @suppress {unusedLocalVariables} f is only used for nested messages 531 | */ 532 | proto.com.product.GetProductViaCategoryRequest.serializeBinaryToWriter = function(message, writer) { 533 | var f = undefined; 534 | f = message.getCategory(); 535 | if (f.length > 0) { 536 | writer.writeString( 537 | 1, 538 | f 539 | ); 540 | } 541 | }; 542 | 543 | 544 | /** 545 | * optional string category = 1; 546 | * @return {string} 547 | */ 548 | proto.com.product.GetProductViaCategoryRequest.prototype.getCategory = function() { 549 | return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); 550 | }; 551 | 552 | 553 | /** 554 | * @param {string} value 555 | * @return {!proto.com.product.GetProductViaCategoryRequest} returns this 556 | */ 557 | proto.com.product.GetProductViaCategoryRequest.prototype.setCategory = function(value) { 558 | return jspb.Message.setProto3StringField(this, 1, value); 559 | }; 560 | 561 | 562 | 563 | 564 | 565 | if (jspb.Message.GENERATE_TO_OBJECT) { 566 | /** 567 | * Creates an object representation of this proto. 568 | * Field names that are reserved in JavaScript and will be renamed to pb_name. 569 | * Optional fields that are not set will be set to undefined. 570 | * To access a reserved field use, foo.pb_, eg, foo.pb_default. 571 | * For the list of reserved names please see: 572 | * net/proto2/compiler/js/internal/generator.cc#kKeyword. 573 | * @param {boolean=} opt_includeInstance Deprecated. whether to include the 574 | * JSPB instance for transitional soy proto support: 575 | * http://goto/soy-param-migration 576 | * @return {!Object} 577 | */ 578 | proto.com.product.Shop.prototype.toObject = function(opt_includeInstance) { 579 | return proto.com.product.Shop.toObject(opt_includeInstance, this); 580 | }; 581 | 582 | 583 | /** 584 | * Static version of the {@see toObject} method. 585 | * @param {boolean|undefined} includeInstance Deprecated. Whether to include 586 | * the JSPB instance for transitional soy proto support: 587 | * http://goto/soy-param-migration 588 | * @param {!proto.com.product.Shop} msg The msg instance to transform. 589 | * @return {!Object} 590 | * @suppress {unusedLocalVariables} f is only used for nested messages 591 | */ 592 | proto.com.product.Shop.toObject = function(includeInstance, msg) { 593 | var f, obj = { 594 | name: jspb.Message.getFieldWithDefault(msg, 1, ""), 595 | listMap: (f = msg.getListMap()) ? f.toObject(includeInstance, proto.com.product.Product.toObject) : [] 596 | }; 597 | 598 | if (includeInstance) { 599 | obj.$jspbMessageInstance = msg; 600 | } 601 | return obj; 602 | }; 603 | } 604 | 605 | 606 | /** 607 | * Deserializes binary data (in protobuf wire format). 608 | * @param {jspb.ByteSource} bytes The bytes to deserialize. 609 | * @return {!proto.com.product.Shop} 610 | */ 611 | proto.com.product.Shop.deserializeBinary = function(bytes) { 612 | var reader = new jspb.BinaryReader(bytes); 613 | var msg = new proto.com.product.Shop; 614 | return proto.com.product.Shop.deserializeBinaryFromReader(msg, reader); 615 | }; 616 | 617 | 618 | /** 619 | * Deserializes binary data (in protobuf wire format) from the 620 | * given reader into the given message object. 621 | * @param {!proto.com.product.Shop} msg The message object to deserialize into. 622 | * @param {!jspb.BinaryReader} reader The BinaryReader to use. 623 | * @return {!proto.com.product.Shop} 624 | */ 625 | proto.com.product.Shop.deserializeBinaryFromReader = function(msg, reader) { 626 | while (reader.nextField()) { 627 | if (reader.isEndGroup()) { 628 | break; 629 | } 630 | var field = reader.getFieldNumber(); 631 | switch (field) { 632 | case 1: 633 | var value = /** @type {string} */ (reader.readString()); 634 | msg.setName(value); 635 | break; 636 | case 2: 637 | var value = msg.getListMap(); 638 | reader.readMessage(value, function(message, reader) { 639 | jspb.Map.deserializeBinary(message, reader, jspb.BinaryReader.prototype.readInt64, jspb.BinaryReader.prototype.readMessage, proto.com.product.Product.deserializeBinaryFromReader, 0, new proto.com.product.Product()); 640 | }); 641 | break; 642 | default: 643 | reader.skipField(); 644 | break; 645 | } 646 | } 647 | return msg; 648 | }; 649 | 650 | 651 | /** 652 | * Serializes the message to binary data (in protobuf wire format). 653 | * @return {!Uint8Array} 654 | */ 655 | proto.com.product.Shop.prototype.serializeBinary = function() { 656 | var writer = new jspb.BinaryWriter(); 657 | proto.com.product.Shop.serializeBinaryToWriter(this, writer); 658 | return writer.getResultBuffer(); 659 | }; 660 | 661 | 662 | /** 663 | * Serializes the given message to binary data (in protobuf wire 664 | * format), writing to the given BinaryWriter. 665 | * @param {!proto.com.product.Shop} message 666 | * @param {!jspb.BinaryWriter} writer 667 | * @suppress {unusedLocalVariables} f is only used for nested messages 668 | */ 669 | proto.com.product.Shop.serializeBinaryToWriter = function(message, writer) { 670 | var f = undefined; 671 | f = message.getName(); 672 | if (f.length > 0) { 673 | writer.writeString( 674 | 1, 675 | f 676 | ); 677 | } 678 | f = message.getListMap(true); 679 | if (f && f.getLength() > 0) { 680 | f.serializeBinary(2, writer, jspb.BinaryWriter.prototype.writeInt64, jspb.BinaryWriter.prototype.writeMessage, proto.com.product.Product.serializeBinaryToWriter); 681 | } 682 | }; 683 | 684 | 685 | /** 686 | * optional string name = 1; 687 | * @return {string} 688 | */ 689 | proto.com.product.Shop.prototype.getName = function() { 690 | return /** @type {string} */ (jspb.Message.getFieldWithDefault(this, 1, "")); 691 | }; 692 | 693 | 694 | /** 695 | * @param {string} value 696 | * @return {!proto.com.product.Shop} returns this 697 | */ 698 | proto.com.product.Shop.prototype.setName = function(value) { 699 | return jspb.Message.setProto3StringField(this, 1, value); 700 | }; 701 | 702 | 703 | /** 704 | * map list = 2; 705 | * @param {boolean=} opt_noLazyCreate Do not create the map if 706 | * empty, instead returning `undefined` 707 | * @return {!jspb.Map} 708 | */ 709 | proto.com.product.Shop.prototype.getListMap = function(opt_noLazyCreate) { 710 | return /** @type {!jspb.Map} */ ( 711 | jspb.Message.getMapField(this, 2, opt_noLazyCreate, 712 | proto.com.product.Product)); 713 | }; 714 | 715 | 716 | /** 717 | * Clears values from the map. The map will be non-null. 718 | * @return {!proto.com.product.Shop} returns this 719 | */ 720 | proto.com.product.Shop.prototype.clearListMap = function() { 721 | this.getListMap().clear(); 722 | return this;}; 723 | 724 | 725 | goog.object.extend(exports, proto.com.product); 726 | --------------------------------------------------------------------------------