From 1c91baf9d73e838a4ae66532b226c6e0e6abf596 Mon Sep 17 00:00:00 2001 From: ajguerrer Date: Fri, 6 Sep 2019 23:53:48 -0600 Subject: [PATCH 1/2] add angular support --- advanced.yml | 9 + javascript/net/grpc/web/grpc_generator.cc | 185 ++++++++++++++++++ .../gateway/docker/angular_client/Dockerfile | 36 ++++ net/grpc/gateway/docker/common/Dockerfile | 2 +- .../examples/echo/angular-example/.gitignore | 48 +++++ .../examples/echo/angular-example/README.md | 27 +++ .../echo/angular-example/angular.json | 119 +++++++++++ .../echo/angular-example/browserslist | 12 ++ .../echo/angular-example/karma.conf.js | 38 ++++ .../echo/angular-example/package.json | 52 +++++ .../src/app/app.component.html | 22 +++ .../src/app/app.component.sass | 0 .../angular-example/src/app/app.component.ts | 117 +++++++++++ .../angular-example/src/app/app.module.ts | 30 +++ .../angular-example/src/app/shared/.gitkeep | 0 .../src/app/shared/echo.service.spec.ts | 106 ++++++++++ .../echo/angular-example/src/assets/.gitkeep | 0 .../src/environments/environment.prod.ts | 3 + .../src/environments/environment.ts | 16 ++ .../echo/angular-example/src/favicon.ico | Bin 0 -> 948 bytes .../echo/angular-example/src/index.html | 15 ++ .../examples/echo/angular-example/src/main.ts | 12 ++ .../echo/angular-example/src/polyfills.ts | 63 ++++++ .../echo/angular-example/src/styles.sass | 6 + .../examples/echo/angular-example/src/test.ts | 20 ++ .../echo/angular-example/tsconfig.app.json | 18 ++ .../echo/angular-example/tsconfig.json | 26 +++ .../echo/angular-example/tsconfig.spec.json | 18 ++ scripts/kokoro.sh | 4 + 29 files changed, 1003 insertions(+), 1 deletion(-) create mode 100644 net/grpc/gateway/docker/angular_client/Dockerfile create mode 100644 net/grpc/gateway/examples/echo/angular-example/.gitignore create mode 100644 net/grpc/gateway/examples/echo/angular-example/README.md create mode 100644 net/grpc/gateway/examples/echo/angular-example/angular.json create mode 100644 net/grpc/gateway/examples/echo/angular-example/browserslist create mode 100644 net/grpc/gateway/examples/echo/angular-example/karma.conf.js create mode 100644 net/grpc/gateway/examples/echo/angular-example/package.json create mode 100644 net/grpc/gateway/examples/echo/angular-example/src/app/app.component.html create mode 100644 net/grpc/gateway/examples/echo/angular-example/src/app/app.component.sass create mode 100644 net/grpc/gateway/examples/echo/angular-example/src/app/app.component.ts create mode 100644 net/grpc/gateway/examples/echo/angular-example/src/app/app.module.ts create mode 100644 net/grpc/gateway/examples/echo/angular-example/src/app/shared/.gitkeep create mode 100644 net/grpc/gateway/examples/echo/angular-example/src/app/shared/echo.service.spec.ts create mode 100644 net/grpc/gateway/examples/echo/angular-example/src/assets/.gitkeep create mode 100644 net/grpc/gateway/examples/echo/angular-example/src/environments/environment.prod.ts create mode 100644 net/grpc/gateway/examples/echo/angular-example/src/environments/environment.ts create mode 100644 net/grpc/gateway/examples/echo/angular-example/src/favicon.ico create mode 100644 net/grpc/gateway/examples/echo/angular-example/src/index.html create mode 100644 net/grpc/gateway/examples/echo/angular-example/src/main.ts create mode 100644 net/grpc/gateway/examples/echo/angular-example/src/polyfills.ts create mode 100644 net/grpc/gateway/examples/echo/angular-example/src/styles.sass create mode 100644 net/grpc/gateway/examples/echo/angular-example/src/test.ts create mode 100644 net/grpc/gateway/examples/echo/angular-example/tsconfig.app.json create mode 100644 net/grpc/gateway/examples/echo/angular-example/tsconfig.json create mode 100644 net/grpc/gateway/examples/echo/angular-example/tsconfig.spec.json diff --git a/advanced.yml b/advanced.yml index 446937ff..f0a3e191 100644 --- a/advanced.yml +++ b/advanced.yml @@ -95,3 +95,12 @@ services: image: grpcweb/binary-client ports: - "8081:8081" + angular-client: + build: + context: ./ + dockerfile: ./net/grpc/gateway/docker/angular_client/Dockerfile + depends_on: + - prereqs + image: grpcweb/angular-client + ports: + - "8081:8081" diff --git a/javascript/net/grpc/web/grpc_generator.cc b/javascript/net/grpc/web/grpc_generator.cc index a6f56254..9f15c96b 100644 --- a/javascript/net/grpc/web/grpc_generator.cc +++ b/javascript/net/grpc/web/grpc_generator.cc @@ -238,6 +238,26 @@ void ReplaceCharacters(string *s, const char *remove, char replacewith) { } } +// Returns name in PascalCase to SCREAMING_SNAKE_CASE. +// e.g 'EchoServiceConfig' -> 'ECHO_SERVICE_CONFIG' +string PascalToConstCase(const string& s) { + if (s.empty()) { + return s; + } + // Ignore the first character. It's already uppercase and doesn't need an + // underscore. + string result; + result.push_back(s[0]); + for (int i = 1; i < s.size(); ++i) { + if (s[i] >= 'A' && s[i] <= 'Z') { + result.push_back('_'); + result.push_back(s[i]); + } else { + result.push_back(s[i] - 'a' + 'A'); + } + } + return result; +} // The following function was copied from // google/protobuf/src/google/protobuf/compiler/cpp/cpp_helpers.cc @@ -633,6 +653,149 @@ void PrintES6Imports(Printer* printer, const FileDescriptor* file) { printer->Print(vars, "} from './$base_name$_pb';\n\n"); } +void PrintAngularServiceImports(Printer* printer, const FileDescriptor* file, + const string base_file_name) { + printer->Print( + "import {Injectable, InjectionToken, Inject} from '@angular/core';\n"); + printer->Print("import {Observable} from 'rxjs';\n\n"); + + if (!file->service_count()) { + return; + } + + std::map vars; + vars["base_file_name"] = base_file_name; + + const ServiceDescriptor* service = file->service(0); + vars["service_name"] = service->name(); + + if (file->service_count() == 1) { + printer->Print( + vars, "import {$service_name$Client} from './$base_file_name$';\n\n"); + return; + } + + printer->Print("import {\n"); + printer->Indent(); + printer->Print(vars, "$service_name$"); + + for (int service_index = 1; service_index < file->service_count(); + ++service_index) { + const ServiceDescriptor* service = file->service(service_index); + vars["service_name"] = service->name(); + printer->Print(vars, ",\n$service_name$Client"); + } + + printer->Outdent(); + printer->Print(vars, "} from './$base_file_name$';\n\n"); +} + +void PrintAngularServiceMethod(Printer* printer, const MethodDescriptor* method, + std::map vars) { + if (!method->client_streaming()) { + printer->Print(vars, + "$js_method_name$(\n" + " request: $input_type$,\n" + " metadata?: grpcWeb.Metadata\n" + "): Observable<$output_type$> {\n"); + printer->Indent(); + printer->Print("return new Observable(subscriber => {\n"); + printer->Indent(); + + if (method->server_streaming()) { + vars["stream_object"] = "stream"; + printer->Print( + vars, + "const $stream_object$ = this.client.$js_method_name$(request, " + "metadata);\n" + "$stream_object$.on('data', (response) => " + "subscriber.next(response));\n" + "$stream_object$.on('error', (err) => subscriber.error(err));\n" + "$stream_object$.on('status', (status) => {\n" + " if (status.code != grpcWeb.StatusCode.OK) {\n" + " subscriber.error({code: status.code, message: " + "status.details});\n" + " }\n" + "});\n" + "$stream_object$.on('end', () => subscriber.complete());\n"); + } else { + vars["stream_object"] = "call"; + printer->Print( + vars, + "const callback = (err, response) => {\n" + " if (err) {\n" + " subscriber.error(err);\n" + " } else {\n" + " subscriber.next(response);\n" + " subscriber.complete();\n" + " }\n" + "};\n" + "const $stream_object$ = this.client.$js_method_name$(request, " + "metadata, callback);\n"); + } + printer->Print(vars, + "return () => { if ($stream_object$) { " + "$stream_object$.cancel(); } }\n"); + printer->Outdent(); + printer->Print("});\n"); + printer->Outdent(); + printer->Print("}\n\n"); + } +} + +void PrintAngularServiceClass(Printer* printer, const FileDescriptor* file) { + for (int service_index = 0; service_index < file->service_count(); + ++service_index) { + std::map vars; + const ServiceDescriptor* service = file->service(service_index); + vars["service_name"] = service->name(); + printer->Print(vars, "export interface $service_name$Config {\n"); + printer->Print( + " hostname: string;\n" + " credentials: null | { [index: string]: string; };\n" + " options: null | { [index: string]: string; };\n"); + printer->Print("};\n"); + vars["config_name"] = PascalToConstCase(service->name()) + "_CONFIG"; + printer->Print( + vars, + "export const $config_name$ = new " + "InjectionToken<$service_name$Config>('$config_name$');\n\n"); + + printer->Print( + "@Injectable({\n" + " providedIn: 'root',\n" + "})\n"); + printer->Print(vars, "export class $service_name$ {\n"); + printer->Indent(); + printer->Print(vars, + "private client: $service_name$Client;\n\n" + "constructor(@Inject($config_name$) private config: " + "$service_name$Config) {\n" + " this.client = new $service_name$Client(\n" + " this.config.hostname,\n" + " this.config.credentials,\n" + " this.config.options);\n" + "}\n\n"); + for (int method_index = 0; method_index < service->method_count(); + ++method_index) { + const MethodDescriptor* method = service->method(method_index); + vars["js_method_name"] = LowercaseFirstLetter(method->name()); + vars["input_type"] = JSMessageType(method->input_type(), file); + vars["output_type"] = JSMessageType(method->output_type(), file); + PrintAngularServiceMethod(printer, method, vars); + } + printer->Outdent(); + printer->Print("}\n"); + } +} + +void PrintAngularServiceFile(Printer* printer, const FileDescriptor* file, + const string base_file_name) { + PrintAngularServiceImports(printer, file, base_file_name); + PrintES6Imports(printer, file); + PrintAngularServiceClass(printer, file); +} + void PrintTypescriptFile(Printer* printer, const FileDescriptor* file, std::map vars) { PrintES6Imports(printer, file); @@ -1309,6 +1472,7 @@ class GrpcCodeGenerator : public CodeGenerator { ImportStyle import_style; bool generate_dts = false; bool gen_multiple_files = false; + bool generate_angular = false; for (size_t i = 0; i < options.size(); ++i) { if (options[i].first == "out") { @@ -1317,6 +1481,8 @@ class GrpcCodeGenerator : public CodeGenerator { mode = options[i].second; } else if (options[i].first == "import_style") { import_style_str = options[i].second; + } else if (options[i].first == "framework") { + generate_angular = options[i].second == "angular"; } else if (options[i].first == "multiple_files") { gen_multiple_files = options[i].second == "true"; } else { @@ -1357,6 +1523,10 @@ class GrpcCodeGenerator : public CodeGenerator { import_style = ImportStyle::CLOSURE; } else if (import_style_str == "commonjs") { import_style = ImportStyle::COMMONJS; + // Generate Typescript declarations for Angular. + if (generate_angular) { + generate_dts = true; + } } else if (import_style_str == "commonjs+dts") { import_style = ImportStyle::COMMONJS; generate_dts = true; @@ -1559,6 +1729,21 @@ class GrpcCodeGenerator : public CodeGenerator { PrintGrpcWebDtsFile(&grpcweb_dts_printer, file); } + if (generate_angular && import_style != ImportStyle::CLOSURE) { + string angular_service_file_name = + StripProto(file->name()) + ".service.pb.ts"; + + std::unique_ptr angular_service_output( + context->Open(angular_service_file_name)); + Printer angular_service_printer(angular_service_output.get(), '$'); + + PrintFileHeader(&angular_service_printer, vars); + + const string base_file_name = StripSuffixString( + file_name, import_style == TYPESCRIPT ? ".ts" : ".js"); + PrintAngularServiceFile(&angular_service_printer, file, base_file_name); + } + return true; } }; diff --git a/net/grpc/gateway/docker/angular_client/Dockerfile b/net/grpc/gateway/docker/angular_client/Dockerfile new file mode 100644 index 00000000..f6f635df --- /dev/null +++ b/net/grpc/gateway/docker/angular_client/Dockerfile @@ -0,0 +1,36 @@ +# Copyright 2018 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +FROM grpcweb/prereqs + +ARG EXAMPLE_DIR=/github/grpc-web/net/grpc/gateway/examples/echo +ARG ANGULAR_SERVICE_DIR=$EXAMPLE_DIR/angular-example/src/app/shared + +RUN npm install -g @angular/cli + +RUN curl -o chrome.deb -sSL https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb +RUN dpkg -i chrome.deb; apt-get -fy install + +RUN protoc -I=$EXAMPLE_DIR echo.proto \ +--js_out=import_style=commonjs:$ANGULAR_SERVICE_DIR \ +--grpc-web_out=import_style=commonjs+dts,mode=grpcwebtext,framework=angular:$ANGULAR_SERVICE_DIR + +RUN cd $EXAMPLE_DIR/angular-example && \ + npm install && \ + ng build --prod && \ + cp dist/angular-example/* /var/www/html + +EXPOSE 8081 +WORKDIR /var/www/html +CMD ["python", "-m", "SimpleHTTPServer", "8081"] diff --git a/net/grpc/gateway/docker/common/Dockerfile b/net/grpc/gateway/docker/common/Dockerfile index 0ee5dc04..100811b5 100644 --- a/net/grpc/gateway/docker/common/Dockerfile +++ b/net/grpc/gateway/docker/common/Dockerfile @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -FROM node:8-stretch +FROM node:10-stretch RUN apt-get -qq update && apt-get -qq install -y \ unzip diff --git a/net/grpc/gateway/examples/echo/angular-example/.gitignore b/net/grpc/gateway/examples/echo/angular-example/.gitignore new file mode 100644 index 00000000..79893d85 --- /dev/null +++ b/net/grpc/gateway/examples/echo/angular-example/.gitignore @@ -0,0 +1,48 @@ +# See http://help.github.com/ignore-files/ for more about ignoring files. + +# compiled output +/dist +/tmp +/out-tsc +# Only exists if Bazel was run +/bazel-out + +# dependencies +/node_modules +package-lock.json +yarn.lock + +# profiling files +chrome-profiler-events*.json +speed-measure-plugin*.json + +# IDEs and editors +/.idea +.project +.classpath +.c9/ +*.launch +.settings/ +*.sublime-workspace + +# IDE - VSCode +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +.history/* + +# misc +/.sass-cache +/connect.lock +/coverage +/libpeerconnection.log +npm-debug.log +yarn-error.log +testem.log +/typings + +# System Files +.DS_Store +Thumbs.db diff --git a/net/grpc/gateway/examples/echo/angular-example/README.md b/net/grpc/gateway/examples/echo/angular-example/README.md new file mode 100644 index 00000000..b5756ab8 --- /dev/null +++ b/net/grpc/gateway/examples/echo/angular-example/README.md @@ -0,0 +1,27 @@ +# AngularExample + +This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 8.3.0. + +## Development server + +Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. + +## Code scaffolding + +Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. + +## Build + +Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. + +## Running unit tests + +Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). + +## Running end-to-end tests + +Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). + +## Further help + +To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). diff --git a/net/grpc/gateway/examples/echo/angular-example/angular.json b/net/grpc/gateway/examples/echo/angular-example/angular.json new file mode 100644 index 00000000..3cdefe71 --- /dev/null +++ b/net/grpc/gateway/examples/echo/angular-example/angular.json @@ -0,0 +1,119 @@ +{ + "$schema": "./node_modules/@angular/cli/lib/config/schema.json", + "version": 1, + "newProjectRoot": "projects", + "projects": { + "angular-example": { + "projectType": "application", + "schematics": { + "@schematics/angular:component": { + "style": "sass" + } + }, + "root": "", + "sourceRoot": "src", + "prefix": "app", + "architect": { + "build": { + "builder": "@angular-devkit/build-angular:browser", + "options": { + "outputPath": "dist/angular-example", + "index": "src/index.html", + "main": "src/main.ts", + "polyfills": "src/polyfills.ts", + "tsConfig": "tsconfig.app.json", + "aot": false, + "assets": [ + "src/favicon.ico", + "src/assets" + ], + "styles": [ + "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", + "src/styles.sass" + ], + "scripts": [] + }, + "configurations": { + "production": { + "fileReplacements": [ + { + "replace": "src/environments/environment.ts", + "with": "src/environments/environment.prod.ts" + } + ], + "optimization": true, + "outputHashing": "all", + "sourceMap": false, + "extractCss": true, + "namedChunks": false, + "aot": true, + "extractLicenses": true, + "vendorChunk": false, + "buildOptimizer": true, + "budgets": [ + { + "type": "initial", + "maximumWarning": "2mb", + "maximumError": "5mb" + }, + { + "type": "anyComponentStyle", + "maximumWarning": "6kb", + "maximumError": "10kb" + } + ] + } + } + }, + "serve": { + "builder": "@angular-devkit/build-angular:dev-server", + "options": { + "browserTarget": "angular-example:build" + }, + "configurations": { + "production": { + "browserTarget": "angular-example:build:production" + } + } + }, + "extract-i18n": { + "builder": "@angular-devkit/build-angular:extract-i18n", + "options": { + "browserTarget": "angular-example:build" + } + }, + "test": { + "builder": "@angular-devkit/build-angular:karma", + "options": { + "main": "src/test.ts", + "polyfills": "src/polyfills.ts", + "tsConfig": "tsconfig.spec.json", + "karmaConfig": "karma.conf.js", + "assets": [ + "src/favicon.ico", + "src/assets" + ], + "styles": [ + "src/styles.sass" + ], + "scripts": [] + } + }, + "lint": { + "builder": "@angular-devkit/build-angular:tslint", + "options": { + "tsConfig": [ + "tsconfig.app.json", + "tsconfig.spec.json", + "e2e/tsconfig.json" + ], + "exclude": [ + "**/node_modules/**" + ] + } + } + } + } + }, + "defaultProject": "angular-example" +} \ No newline at end of file diff --git a/net/grpc/gateway/examples/echo/angular-example/browserslist b/net/grpc/gateway/examples/echo/angular-example/browserslist new file mode 100644 index 00000000..80848532 --- /dev/null +++ b/net/grpc/gateway/examples/echo/angular-example/browserslist @@ -0,0 +1,12 @@ +# This file is used by the build system to adjust CSS and JS output to support the specified browsers below. +# For additional information regarding the format and rule options, please see: +# https://github.com/browserslist/browserslist#queries + +# You can see what browsers were selected by your queries by running: +# npx browserslist + +> 0.5% +last 2 versions +Firefox ESR +not dead +not IE 9-11 # For IE 9-11 support, remove 'not'. \ No newline at end of file diff --git a/net/grpc/gateway/examples/echo/angular-example/karma.conf.js b/net/grpc/gateway/examples/echo/angular-example/karma.conf.js new file mode 100644 index 00000000..41b61274 --- /dev/null +++ b/net/grpc/gateway/examples/echo/angular-example/karma.conf.js @@ -0,0 +1,38 @@ +// Karma configuration file, see link for more information +// https://karma-runner.github.io/1.0/config/configuration-file.html + +module.exports = function (config) { + config.set({ + basePath: '', + frameworks: ['jasmine', '@angular-devkit/build-angular'], + plugins: [ + require('karma-jasmine'), + require('karma-chrome-launcher'), + require('karma-jasmine-html-reporter'), + require('karma-coverage-istanbul-reporter'), + require('@angular-devkit/build-angular/plugins/karma') + ], + client: { + clearContext: false // leave Jasmine Spec Runner output visible in browser + }, + coverageIstanbulReporter: { + dir: require('path').join(__dirname, './coverage/angular-example'), + reports: ['html', 'lcovonly', 'text-summary'], + fixWebpackSourcePaths: true + }, + reporters: ['progress', 'kjhtml'], + port: 9876, + colors: true, + logLevel: config.LOG_INFO, + autoWatch: true, + browsers: ['ChromeHeadlessNoSandbox'], + customLaunchers: { + ChromeHeadlessNoSandbox: { + base: 'ChromeHeadless', + flags: ['--no-sandbox'] + } + }, + singleRun: false, + restartOnFileChange: true + }); +}; diff --git a/net/grpc/gateway/examples/echo/angular-example/package.json b/net/grpc/gateway/examples/echo/angular-example/package.json new file mode 100644 index 00000000..488bf4d5 --- /dev/null +++ b/net/grpc/gateway/examples/echo/angular-example/package.json @@ -0,0 +1,52 @@ +{ + "name": "angular-example", + "version": "0.0.0", + "scripts": { + "ng": "ng", + "start": "ng serve", + "build": "ng build", + "test": "ng test", + "lint": "ng lint", + "e2e": "ng e2e" + }, + "private": true, + "dependencies": { + "@angular/animations": "~8.2.3", + "@angular/cdk": "~8.1.4", + "@angular/common": "~8.2.3", + "@angular/compiler": "~8.2.3", + "@angular/core": "~8.2.3", + "@angular/flex-layout": "^8.0.0-beta.27", + "@angular/forms": "~8.2.3", + "@angular/material": "^8.1.4", + "@angular/platform-browser": "~8.2.3", + "@angular/platform-browser-dynamic": "~8.2.3", + "@angular/router": "~8.2.3", + "google-protobuf": "^3.9.1", + "grpc-web": "^1.0.6", + "rxjs": "~6.4.0", + "tslib": "^1.10.0", + "zone.js": "~0.9.1" + }, + "devDependencies": { + "@angular-devkit/build-angular": "~0.803.0", + "@angular/cli": "~8.3.0", + "@angular/compiler-cli": "~8.2.3", + "@angular/language-service": "~8.2.3", + "@types/jasmine": "~3.3.8", + "@types/jasminewd2": "~2.0.3", + "@types/node": "~8.9.4", + "codelyzer": "^5.0.0", + "jasmine-core": "~3.4.0", + "jasmine-spec-reporter": "~4.2.1", + "karma": "~4.1.0", + "karma-chrome-launcher": "~2.2.0", + "karma-coverage-istanbul-reporter": "~2.0.1", + "karma-jasmine": "~2.0.1", + "karma-jasmine-html-reporter": "^1.4.0", + "ts-node": "~7.0.0", + "tslint": "~5.15.0", + "typescript": "~3.5.3", + "xhr-mock": "^2.5.0" + } +} diff --git a/net/grpc/gateway/examples/echo/angular-example/src/app/app.component.html b/net/grpc/gateway/examples/echo/angular-example/src/app/app.component.html new file mode 100644 index 00000000..0c186b21 --- /dev/null +++ b/net/grpc/gateway/examples/echo/angular-example/src/app/app.component.html @@ -0,0 +1,22 @@ +
+ + + Example: "Hello", "4 Hello" + + +
+ + + + + + {{message.text}} + + + {{message.text}} + + + + \ No newline at end of file diff --git a/net/grpc/gateway/examples/echo/angular-example/src/app/app.component.sass b/net/grpc/gateway/examples/echo/angular-example/src/app/app.component.sass new file mode 100644 index 00000000..e69de29b diff --git a/net/grpc/gateway/examples/echo/angular-example/src/app/app.component.ts b/net/grpc/gateway/examples/echo/angular-example/src/app/app.component.ts new file mode 100644 index 00000000..3cccb206 --- /dev/null +++ b/net/grpc/gateway/examples/echo/angular-example/src/app/app.component.ts @@ -0,0 +1,117 @@ +import { Component } from '@angular/core'; +import { EchoService, ECHO_SERVICE_CONFIG } from './shared/echo.service.pb'; +import { EchoRequest, ServerStreamingEchoRequest } from './shared/echo_pb'; +import { delay } from 'rxjs/operators'; +import { Subscription } from 'rxjs'; + +export interface Message { + text?: string; + isRequest?: boolean; +} + +const INTERVAL = 500; // ms +const MAX_STREAM_MESSAGES = 50; + +@Component({ + selector: 'app-root', + templateUrl: './app.component.html', + styleUrls: ['./app.component.sass'], + providers: [ + EchoService, + { + provide: ECHO_SERVICE_CONFIG, + useValue: { hostname: 'http://localhost:8080' } + }, + ] +}) +export class AppComponent { + stream: Subscription; + + constructor(private echoService: EchoService) { } + + messages: Message[] = []; + + onSend(message: string) { + const msg = message.trim(); + if (!msg) return; + + if (msg.indexOf(' ') > 0) { + const count = msg.substr(0, msg.indexOf(' ')); + if (/^\d+$/.test(count)) { + this.repeatEcho(msg.substr(msg.indexOf(' ') + 1), Number(count)); + } else { + this.echo(msg); + } + } else if (msg === 'error') { + this.echoError(); + } else if (msg === 'cancel') { + this.cancel(); + } else { + this.echo(msg); + } + } + + private echo(message: string) { + this.addLeftMessage(message); + const request = new EchoRequest(); + request.setMessage(message); + + this.echoService.echo(request, { 'custom-header-1': 'value1' }) + .pipe(delay(INTERVAL)) + .subscribe( + response => this.addRightMessage(response.getMessage()), + error => this.handleError(error), + ); + } + + private repeatEcho(message: string, count: number) { + this.addLeftMessage(message); + if (count > MAX_STREAM_MESSAGES) { + count = MAX_STREAM_MESSAGES; + } + const request = new ServerStreamingEchoRequest(); + request.setMessage(message); + request.setMessageCount(count); + request.setMessageInterval(INTERVAL); + + this.stream = this.echoService.serverStreamingEcho( + request, { 'custom-header-1': 'value1' }).subscribe( + response => this.addRightMessage(response.getMessage()), + error => this.handleError(error), + ); + } + + private echoError() { + this.addLeftMessage('Error'); + const request = new EchoRequest(); + request.setMessage('error') + this.echoService.echoAbort(request, {}).subscribe( + response => this.addRightMessage(response.getMessage()), + error => this.handleError(error), + ); + } + + private cancel() { + this.addLeftMessage('Cancel'); + if (this.stream) { + this.stream.unsubscribe(); + } + } + + private handleError(error) { + this.addRightMessage( + 'Error code: ' + error.code + ' "' + decodeURI(error.message) + '"'); + } + + private addLeftMessage(message: string) { + // Empty message used to skip right tile on the mat-grid-list. + const newMessage: Message[] = [{ text: message, isRequest: true }, {}]; + this.messages = newMessage.concat(this.messages); + } + + private addRightMessage(message: string) { + // Empty message used to skip left tile on the mat-grid-list. + const newMessage: Message[] = [{}, { text: message }]; + this.messages = newMessage.concat(this.messages); + } +} diff --git a/net/grpc/gateway/examples/echo/angular-example/src/app/app.module.ts b/net/grpc/gateway/examples/echo/angular-example/src/app/app.module.ts new file mode 100644 index 00000000..892f060e --- /dev/null +++ b/net/grpc/gateway/examples/echo/angular-example/src/app/app.module.ts @@ -0,0 +1,30 @@ +import { BrowserModule } from '@angular/platform-browser'; +import { NgModule } from '@angular/core'; +import { NoopAnimationsModule } from '@angular/platform-browser/animations'; +import { FlexLayoutModule } from '@angular/flex-layout'; +import {MatFormFieldModule} from '@angular/material/form-field'; +import {MatInputModule} from '@angular/material/input'; +import {MatButtonModule} from '@angular/material/button'; +import {MatGridListModule} from '@angular/material/grid-list'; +import {MatChipsModule} from '@angular/material/chips'; + +import { AppComponent } from './app.component'; + +@NgModule({ + declarations: [ + AppComponent + ], + imports: [ + BrowserModule, + NoopAnimationsModule, + FlexLayoutModule, + MatFormFieldModule, + MatInputModule, + MatButtonModule, + MatGridListModule, + MatChipsModule, + ], + providers: [], + bootstrap: [AppComponent] +}) +export class AppModule { } diff --git a/net/grpc/gateway/examples/echo/angular-example/src/app/shared/.gitkeep b/net/grpc/gateway/examples/echo/angular-example/src/app/shared/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/net/grpc/gateway/examples/echo/angular-example/src/app/shared/echo.service.spec.ts b/net/grpc/gateway/examples/echo/angular-example/src/app/shared/echo.service.spec.ts new file mode 100644 index 00000000..0c744d21 --- /dev/null +++ b/net/grpc/gateway/examples/echo/angular-example/src/app/shared/echo.service.spec.ts @@ -0,0 +1,106 @@ +import { EchoService, ECHO_SERVICE_CONFIG } from "./echo.service.pb"; +import { TestBed, async } from '@angular/core/testing'; +import { EchoRequest, ServerStreamingEchoRequest } from './echo_pb'; +import { StatusCode } from 'grpc-web'; +import { single, count, tap } from 'rxjs/operators'; +import XHRMock from 'xhr-mock'; + + +describe('EchoService', () => { + var service: EchoService; + + beforeEach(() => { + TestBed.configureTestingModule({ + providers: [ + EchoService, + { + provide: ECHO_SERVICE_CONFIG, + useValue: { hostname: 'MyHostname' } + } + ] + }); + service = TestBed.get(EchoService); + + XHRMock.setup(); + }); + + afterEach(() => { + XHRMock.teardown(); + }); + + it('should send unary request', async(() => { + const request = new EchoRequest(); + request.setMessage('aaa'); + XHRMock.use((request, response) => { + expect(request.method()).toBe('POST'); + // a single 'aaa' string, encoded + expect(request.body()).toBe('AAAAAAUKA2FhYQ=='); + expect(request.url().toString()) + .toBe('MyHostname/grpc.gateway.testing.EchoService/Echo'); + expect(request.headers()).toEqual({ + 'accept': 'application/grpc-web-text', + 'content-type': 'application/grpc-web-text', + 'custom-header-1': 'value1', + 'x-grpc-web': '1', + 'x-user-agent': 'grpc-web-javascript/0.1', + }); + return response; + }); + + service.echo(request, { 'custom-header-1': 'value1' }).subscribe(); + })); + + it('should receive unary response', async(() => { + const request = new EchoRequest(); + request.setMessage('aaa'); + XHRMock.use((request, response) => { + return response + .status(200) + .headers({ 'Content-type': 'application/grpc-web-text' }) + // a single data frame with 'aaa' message, encoded + .body('AAAAAAUKA2FhYQ=='); + }); + + service.echo(request) + .pipe(single()) + .subscribe((response) => { + expect(response.getMessage()).toBe('aaa'); + }, fail); + })); + + it('should receive streaming response', async(() => { + const request = new ServerStreamingEchoRequest(); + request.setMessage('aaa'); + request.setMessageCount(3); + XHRMock.use((request, response) => { + return response + .status(200) + .headers({ 'Content-type': 'application/grpc-web-text' }) + // 3 'aaa' messages in 3 data frames, encoded + .body('AAAAAAUKA2FhYQAAAAAFCgNhYWEAAAAABQoDYWFh'); + }); + + service.serverStreamingEcho(request) + .pipe( + tap(request => expect(request.getMessage()).toBe('aaa')), + count()) + .subscribe(count => expect(count).toBe(3), fail); + })); + + it('should receive failure', async(() => { + const request = new EchoRequest(); + request.setMessage('aaa'); + XHRMock.use((request, response) => { + return response + .status(200) + .headers({ 'Content-type': 'application/grpc-web-text' }) + // a trailer frame with content 'grpc-status:10' + .body('gAAAABBncnBjLXN0YXR1czoxMA0K'); + }); + + service.echo(request).subscribe( + fail, + error => expect(error.code).toBe(StatusCode.ABORTED), + ); + })); +}); diff --git a/net/grpc/gateway/examples/echo/angular-example/src/assets/.gitkeep b/net/grpc/gateway/examples/echo/angular-example/src/assets/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/net/grpc/gateway/examples/echo/angular-example/src/environments/environment.prod.ts b/net/grpc/gateway/examples/echo/angular-example/src/environments/environment.prod.ts new file mode 100644 index 00000000..3612073b --- /dev/null +++ b/net/grpc/gateway/examples/echo/angular-example/src/environments/environment.prod.ts @@ -0,0 +1,3 @@ +export const environment = { + production: true +}; diff --git a/net/grpc/gateway/examples/echo/angular-example/src/environments/environment.ts b/net/grpc/gateway/examples/echo/angular-example/src/environments/environment.ts new file mode 100644 index 00000000..7b4f817a --- /dev/null +++ b/net/grpc/gateway/examples/echo/angular-example/src/environments/environment.ts @@ -0,0 +1,16 @@ +// This file can be replaced during build by using the `fileReplacements` array. +// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. +// The list of file replacements can be found in `angular.json`. + +export const environment = { + production: false +}; + +/* + * For easier debugging in development mode, you can import the following file + * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. + * + * This import should be commented out in production mode because it will have a negative impact + * on performance if an error is thrown. + */ +// import 'zone.js/dist/zone-error'; // Included with Angular CLI. diff --git a/net/grpc/gateway/examples/echo/angular-example/src/favicon.ico b/net/grpc/gateway/examples/echo/angular-example/src/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..997406ad22c29aae95893fb3d666c30258a09537 GIT binary patch literal 948 zcmV;l155mgP)CBYU7IjCFmI-B}4sMJt3^s9NVg!P0 z6hDQy(L`XWMkB@zOLgN$4KYz;j0zZxq9KKdpZE#5@k0crP^5f9KO};h)ZDQ%ybhht z%t9#h|nu0K(bJ ztIkhEr!*UyrZWQ1k2+YkGqDi8Z<|mIN&$kzpKl{cNP=OQzXHz>vn+c)F)zO|Bou>E z2|-d_=qY#Y+yOu1a}XI?cU}%04)zz%anD(XZC{#~WreV!a$7k2Ug`?&CUEc0EtrkZ zL49MB)h!_K{H(*l_93D5tO0;BUnvYlo+;yss%n^&qjt6fZOa+}+FDO(~2>G z2dx@=JZ?DHP^;b7*Y1as5^uphBsh*s*z&MBd?e@I>-9kU>63PjP&^#5YTOb&x^6Cf z?674rmSHB5Fk!{Gv7rv!?qX#ei_L(XtwVqLX3L}$MI|kJ*w(rhx~tc&L&xP#?cQow zX_|gx$wMr3pRZIIr_;;O|8fAjd;1`nOeu5K(pCu7>^3E&D2OBBq?sYa(%S?GwG&_0-s%_v$L@R!5H_fc)lOb9ZoOO#p`Nn`KU z3LTTBtjwo`7(HA6 z7gmO$yTR!5L>Bsg!X8616{JUngg_@&85%>W=mChTR;x4`P=?PJ~oPuy5 zU-L`C@_!34D21{fD~Y8NVnR3t;aqZI3fIhmgmx}$oc-dKDC6Ap$Gy>a!`A*x2L1v0 WcZ@i?LyX}70000 + + + + AngularExample + + + + + + + + + + diff --git a/net/grpc/gateway/examples/echo/angular-example/src/main.ts b/net/grpc/gateway/examples/echo/angular-example/src/main.ts new file mode 100644 index 00000000..c7b673cf --- /dev/null +++ b/net/grpc/gateway/examples/echo/angular-example/src/main.ts @@ -0,0 +1,12 @@ +import { enableProdMode } from '@angular/core'; +import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; + +import { AppModule } from './app/app.module'; +import { environment } from './environments/environment'; + +if (environment.production) { + enableProdMode(); +} + +platformBrowserDynamic().bootstrapModule(AppModule) + .catch(err => console.error(err)); diff --git a/net/grpc/gateway/examples/echo/angular-example/src/polyfills.ts b/net/grpc/gateway/examples/echo/angular-example/src/polyfills.ts new file mode 100644 index 00000000..aa665d6b --- /dev/null +++ b/net/grpc/gateway/examples/echo/angular-example/src/polyfills.ts @@ -0,0 +1,63 @@ +/** + * This file includes polyfills needed by Angular and is loaded before the app. + * You can add your own extra polyfills to this file. + * + * This file is divided into 2 sections: + * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. + * 2. Application imports. Files imported after ZoneJS that should be loaded before your main + * file. + * + * The current setup is for so-called "evergreen" browsers; the last versions of browsers that + * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), + * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. + * + * Learn more in https://angular.io/guide/browser-support + */ + +/*************************************************************************************************** + * BROWSER POLYFILLS + */ + +/** IE10 and IE11 requires the following for NgClass support on SVG elements */ +// import 'classlist.js'; // Run `npm install --save classlist.js`. + +/** + * Web Animations `@angular/platform-browser/animations` + * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. + * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). + */ +// import 'web-animations-js'; // Run `npm install --save web-animations-js`. + +/** + * By default, zone.js will patch all possible macroTask and DomEvents + * user can disable parts of macroTask/DomEvents patch by setting following flags + * because those flags need to be set before `zone.js` being loaded, and webpack + * will put import in the top of bundle, so user need to create a separate file + * in this directory (for example: zone-flags.ts), and put the following flags + * into that file, and then add the following code before importing zone.js. + * import './zone-flags.ts'; + * + * The flags allowed in zone-flags.ts are listed here. + * + * The following flags will work for all browsers. + * + * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame + * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick + * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames + * + * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js + * with the following flag, it will bypass `zone.js` patch for IE/Edge + * + * (window as any).__Zone_enable_cross_context_check = true; + * + */ + +/*************************************************************************************************** + * Zone JS is required by default for Angular itself. + */ +import 'zone.js/dist/zone'; // Included with Angular CLI. + + +/*************************************************************************************************** + * APPLICATION IMPORTS + */ diff --git a/net/grpc/gateway/examples/echo/angular-example/src/styles.sass b/net/grpc/gateway/examples/echo/angular-example/src/styles.sass new file mode 100644 index 00000000..7f7b8652 --- /dev/null +++ b/net/grpc/gateway/examples/echo/angular-example/src/styles.sass @@ -0,0 +1,6 @@ +@import '~@angular/material/prebuilt-themes/indigo-pink.css' + +body + font-family: Roboto, Arial, sans-serif + margin: 0 + height: 100% \ No newline at end of file diff --git a/net/grpc/gateway/examples/echo/angular-example/src/test.ts b/net/grpc/gateway/examples/echo/angular-example/src/test.ts new file mode 100644 index 00000000..16317897 --- /dev/null +++ b/net/grpc/gateway/examples/echo/angular-example/src/test.ts @@ -0,0 +1,20 @@ +// This file is required by karma.conf.js and loads recursively all the .spec and framework files + +import 'zone.js/dist/zone-testing'; +import { getTestBed } from '@angular/core/testing'; +import { + BrowserDynamicTestingModule, + platformBrowserDynamicTesting +} from '@angular/platform-browser-dynamic/testing'; + +declare const require: any; + +// First, initialize the Angular testing environment. +getTestBed().initTestEnvironment( + BrowserDynamicTestingModule, + platformBrowserDynamicTesting() +); +// Then we find all the tests. +const context = require.context('./', true, /\.spec\.ts$/); +// And load the modules. +context.keys().map(context); diff --git a/net/grpc/gateway/examples/echo/angular-example/tsconfig.app.json b/net/grpc/gateway/examples/echo/angular-example/tsconfig.app.json new file mode 100644 index 00000000..565a11a2 --- /dev/null +++ b/net/grpc/gateway/examples/echo/angular-example/tsconfig.app.json @@ -0,0 +1,18 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "./out-tsc/app", + "types": [] + }, + "files": [ + "src/main.ts", + "src/polyfills.ts" + ], + "include": [ + "src/**/*.ts" + ], + "exclude": [ + "src/test.ts", + "src/**/*.spec.ts" + ] +} diff --git a/net/grpc/gateway/examples/echo/angular-example/tsconfig.json b/net/grpc/gateway/examples/echo/angular-example/tsconfig.json new file mode 100644 index 00000000..30956ae7 --- /dev/null +++ b/net/grpc/gateway/examples/echo/angular-example/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compileOnSave": false, + "compilerOptions": { + "baseUrl": "./", + "outDir": "./dist/out-tsc", + "sourceMap": true, + "declaration": false, + "downlevelIteration": true, + "experimentalDecorators": true, + "module": "esnext", + "moduleResolution": "node", + "importHelpers": true, + "target": "es2015", + "typeRoots": [ + "node_modules/@types" + ], + "lib": [ + "es2018", + "dom" + ] + }, + "angularCompilerOptions": { + "fullTemplateTypeCheck": true, + "strictInjectionParameters": true + } +} diff --git a/net/grpc/gateway/examples/echo/angular-example/tsconfig.spec.json b/net/grpc/gateway/examples/echo/angular-example/tsconfig.spec.json new file mode 100644 index 00000000..6400fde7 --- /dev/null +++ b/net/grpc/gateway/examples/echo/angular-example/tsconfig.spec.json @@ -0,0 +1,18 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "./out-tsc/spec", + "types": [ + "jasmine", + "node" + ] + }, + "files": [ + "src/test.ts", + "src/polyfills.ts" + ], + "include": [ + "src/**/*.spec.ts", + "src/**/*.d.ts" + ] +} diff --git a/scripts/kokoro.sh b/scripts/kokoro.sh index 96b3061f..8ad30a0d 100755 --- a/scripts/kokoro.sh +++ b/scripts/kokoro.sh @@ -76,3 +76,7 @@ docker-compose down # Run unit tests from npm package docker run --rm grpcweb/prereqs /bin/bash \ /github/grpc-web/scripts/docker-run-tests.sh + +ANGULAR_DIR="/github/grpc-web/net/grpc/gateway/examples/echo/angular-example" +docker run -w $ANGULAR_DIR grpcweb/angular-client \ + ng test --watch=false --browsers=ChromeHeadlessNoSandbox From 9d321e8956e2dc0768387573f8e465d65bfbf427 Mon Sep 17 00:00:00 2001 From: ajguerrer Date: Sat, 7 Sep 2019 01:42:02 -0600 Subject: [PATCH 2/2] minor changes --- .../examples/echo/angular-example/src/app/shared/.gitkeep | 0 net/grpc/gateway/examples/echo/angular-example/src/styles.sass | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) delete mode 100644 net/grpc/gateway/examples/echo/angular-example/src/app/shared/.gitkeep diff --git a/net/grpc/gateway/examples/echo/angular-example/src/app/shared/.gitkeep b/net/grpc/gateway/examples/echo/angular-example/src/app/shared/.gitkeep deleted file mode 100644 index e69de29b..00000000 diff --git a/net/grpc/gateway/examples/echo/angular-example/src/styles.sass b/net/grpc/gateway/examples/echo/angular-example/src/styles.sass index 7f7b8652..fd4ee169 100644 --- a/net/grpc/gateway/examples/echo/angular-example/src/styles.sass +++ b/net/grpc/gateway/examples/echo/angular-example/src/styles.sass @@ -3,4 +3,4 @@ body font-family: Roboto, Arial, sans-serif margin: 0 - height: 100% \ No newline at end of file + height: 100%