diff --git a/.prettierignore b/.prettierignore index 7dac26426..25e2a462d 100644 --- a/.prettierignore +++ b/.prettierignore @@ -1,2 +1,7 @@ test-connection.yaml -deploy/kubernetes/charts/**/*.yaml \ No newline at end of file +deploy/kubernetes/charts/**/*.yaml +deploy/kubernetes/charts/**/*.yml +dist +ATTRIBUTION.md +deploy/terraform/eks/**/*.yaml +src/**/target \ No newline at end of file diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 000000000..e69de29bb diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md index a0ea08c6a..ec98f2b76 100644 --- a/CODE_OF_CONDUCT.md +++ b/CODE_OF_CONDUCT.md @@ -1,4 +1,5 @@ ## Code of Conduct + This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact -opensource-codeofconduct@amazon.com with any additional questions or comments. \ No newline at end of file +opensource-codeofconduct@amazon.com with any additional questions or comments. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 685bc24ef..f1a28cf58 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -6,7 +6,6 @@ documentation, we greatly value feedback and contributions from our community. Please read through this document before submitting any issues or pull requests to ensure we have all the necessary information to effectively respond to your bug report or contribution. - ## Reporting Bugs/Feature Requests We welcome you to use the GitHub issue tracker to report bugs or suggest features. @@ -14,16 +13,16 @@ We welcome you to use the GitHub issue tracker to report bugs or suggest feature When filing an issue, please check existing open, or recently closed, issues to make sure somebody else hasn't already reported the issue. Please try to include as much information as you can. Details like these are incredibly useful: -* A reproducible test case or series of steps -* The version of our code being used -* Any modifications you've made relevant to the bug -* Anything unusual about your environment or deployment - +- A reproducible test case or series of steps +- The version of our code being used +- Any modifications you've made relevant to the bug +- Anything unusual about your environment or deployment ## Contributing via Pull Requests + Contributions via pull requests are much appreciated. Before sending us a pull request, please ensure that: -1. You are working against the latest source on the *main* branch. +1. You are working against the latest source on the _main_ branch. 2. You check existing open, and recently merged, pull requests to make sure someone else hasn't addressed the problem already. 3. You open an issue to discuss any significant work - we would hate for your time to be wasted. @@ -33,28 +32,27 @@ To send us a pull request, please: 2. Modify the source; please focus on the specific change you are contributing. If you also reformat all the code, it will be hard for us to focus on your change. 3. Ensure local tests pass. 4. Ensure code files are formatted using language provided tools such as `terraform fmt`. -4. Commit to your fork using clear commit messages. -5. Send us a pull request, answering any default questions in the pull request interface. -6. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. +5. Commit to your fork using clear commit messages. +6. Send us a pull request, answering any default questions in the pull request interface. +7. Pay attention to any automated CI failures reported in the pull request, and stay involved in the conversation. GitHub provides additional document on [forking a repository](https://help.github.com/articles/fork-a-repo/) and [creating a pull request](https://help.github.com/articles/creating-a-pull-request/). - ## Finding contributions to work on -Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. +Looking at the existing issues is a great way to find something to contribute on. As our projects, by default, use the default GitHub issue labels (enhancement/bug/duplicate/help wanted/invalid/question/wontfix), looking at any 'help wanted' issues is a great place to start. ## Code of Conduct + This project has adopted the [Amazon Open Source Code of Conduct](https://aws.github.io/code-of-conduct). For more information see the [Code of Conduct FAQ](https://aws.github.io/code-of-conduct-faq) or contact opensource-codeofconduct@amazon.com with any additional questions or comments. - ## Security issue notifications -If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. +If you discover a potential security issue in this project we ask that you notify AWS/Amazon Security via our [vulnerability reporting page](http://aws.amazon.com/security/vulnerability-reporting/). Please do **not** create a public github issue. ## Licensing -See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. \ No newline at end of file +See the [LICENSE](LICENSE) file for our project's licensing. We will ask you to confirm the licensing of your contribution. diff --git a/deploy/terraform/ecs/default/README.md b/deploy/terraform/ecs/default/README.md index 17267e315..bc42d7ba6 100644 --- a/deploy/terraform/ecs/default/README.md +++ b/deploy/terraform/ecs/default/README.md @@ -3,6 +3,7 @@ This Terraform module creates all the necessary infrastructure and deploys the retail sample application on [Amazon Elastic Container Service](https://aws.amazon.com/ecs/). It provides: + - VPC with public and private subnets - ECS cluster using Fargate for compute - All application dependencies such as RDS, DynamoDB table, Elasticache etc. @@ -14,6 +15,7 @@ NOTE: This will create resources in your AWS account which will incur costs. You ## Usage Pre-requisites for this are: + - AWS, Terraform and kubectl installed locally - AWS CLI configured and authenticated with account to deploy to @@ -41,12 +43,12 @@ This section documents the variables and outputs of the Terraform configuration. ### Inputs -| Name | Description | Type | Default | Required | -|------|-------------|------|---------|:--------:| -| `environment_name` | Name of the environment which will be used for all resources created | `string` | `retail-store-ecs` | yes | +| Name | Description | Type | Default | Required | +| ------------------ | -------------------------------------------------------------------- | -------- | ------------------ | :------: | +| `environment_name` | Name of the environment which will be used for all resources created | `string` | `retail-store-ecs` | yes | ### Outputs -| Name | Description | -|------|-------------| +| Name | Description | +| ----------------- | ----------------------------------------- | | `application_url` | URL where the application can be accessed | diff --git a/deploy/terraform/eks/default/README.md b/deploy/terraform/eks/default/README.md index a5df8864f..1ac5d9b7d 100644 --- a/deploy/terraform/eks/default/README.md +++ b/deploy/terraform/eks/default/README.md @@ -3,6 +3,7 @@ This Terraform module creates all the necessary infrastructure and deploys the retail sample application on [Amazon Elastic Kubernetes Service](https://aws.amazon.com/eks/) (EKS). This configuration will deploy all application dependencies using AWS managed services such as Amazon RDS and Amazon DynamoDB. It provides: + - VPC with public and private subnets - EKS cluster and managed node groups in multiple availability zones - All application dependencies such as RDS, DynamoDB table, Elasticache etc. @@ -15,6 +16,7 @@ NOTE: This will create resources in your AWS account which will incur costs. You ## Usage Pre-requisites for this are: + - AWS, Terraform and kubectl installed locally - AWS CLI configured and authenticated with account to deploy to @@ -63,14 +65,14 @@ This section documents the variables and outputs of the Terraform configuration. ### Inputs -| Name | Description | Type | Default | Required | -|------|-------------|------|---------|:--------:| -| `environment_name` | Name of the environment which will be used for all resources created | `string` | `retail-store` | yes | -| `opentelemetry_enabled` | Flag to enable OpenTelemetry, which will install the AWS Distro for OpenTelemetry addon in the EKS cluster, create OpenTelemetry collectors and configure the application components appropriately | `bool` | `false` | no | -| `istio_enabled` | Flag to enable Istio, which will install Istio in the EKS cluster and configure the application components appropriately | `bool` | `false` | no | +| Name | Description | Type | Default | Required | +| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- | -------------- | :------: | +| `environment_name` | Name of the environment which will be used for all resources created | `string` | `retail-store` | yes | +| `opentelemetry_enabled` | Flag to enable OpenTelemetry, which will install the AWS Distro for OpenTelemetry addon in the EKS cluster, create OpenTelemetry collectors and configure the application components appropriately | `bool` | `false` | no | +| `istio_enabled` | Flag to enable Istio, which will install Istio in the EKS cluster and configure the application components appropriately | `bool` | `false` | no | ### Outputs -| Name | Description | -|------|-------------| -| `configure_kubectl` | AWS CLI command to configure `kubectl` for EKS cluster | \ No newline at end of file +| Name | Description | +| ------------------- | ------------------------------------------------------ | +| `configure_kubectl` | AWS CLI command to configure `kubectl` for EKS cluster | diff --git a/deploy/terraform/eks/minimal/README.md b/deploy/terraform/eks/minimal/README.md index eb2ceb358..84e2e9b51 100644 --- a/deploy/terraform/eks/minimal/README.md +++ b/deploy/terraform/eks/minimal/README.md @@ -3,6 +3,7 @@ This Terraform module creates all the necessary infrastructure for the retail sample application on [Amazon Elastic Kubernetes Service](https://aws.amazon.com/eks/) (EKS). This configuration will only provision the EKS cluster and other foundational infrastructure such as the VPC. It will not deploy services to fulfill application dependencies such as Amazon RDS or Amazon DynamoDB (see [default configuration](../default/)). It provides: + - VPC with public and private subnets - EKS cluster and managed node groups in multiple availability zones @@ -11,6 +12,7 @@ NOTE: This will create resources in your AWS account which will incur costs. You ## Usage Pre-requisites for this are: + - AWS, Terraform and kubectl installed locally - AWS CLI configured and authenticated with account to deploy to @@ -48,14 +50,14 @@ This section documents the variables and outputs of the Terraform configuration. ### Inputs -| Name | Description | Type | Default | Required | -|------|-------------|------|---------|:--------:| -| `environment_name` | Name of the environment which will be used for all resources created | `string` | `retail-store` | yes | -| `opentelemetry_enabled` | Flag to enable OpenTelemetry, which will install the AWS Distro for OpenTelemetry addon in the EKS cluster and create OpenTelemetry collectors. | `bool` | `false` | no | -| `istio_enabled` | Flag to enable Istio, which will install Istio in the EKS cluster | `bool` | `false` | no | +| Name | Description | Type | Default | Required | +| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | -------- | -------------- | :------: | +| `environment_name` | Name of the environment which will be used for all resources created | `string` | `retail-store` | yes | +| `opentelemetry_enabled` | Flag to enable OpenTelemetry, which will install the AWS Distro for OpenTelemetry addon in the EKS cluster and create OpenTelemetry collectors. | `bool` | `false` | no | +| `istio_enabled` | Flag to enable Istio, which will install Istio in the EKS cluster | `bool` | `false` | no | ### Outputs -| Name | Description | -|------|-------------| -| `configure_kubectl` | AWS CLI command to configure `kubectl` for EKS cluster | \ No newline at end of file +| Name | Description | +| ------------------- | ------------------------------------------------------ | +| `configure_kubectl` | AWS CLI command to configure `kubectl` for EKS cluster | diff --git a/deploy/terraform/lib/images/README.md b/deploy/terraform/lib/images/README.md index 345d5bb8f..615b038ce 100644 --- a/deploy/terraform/lib/images/README.md +++ b/deploy/terraform/lib/images/README.md @@ -128,4 +128,4 @@ result = { "orders" = "public.ecr.aws/aws-containers/retail-store-sample-orders:0.2.0" "ui" = "public.ecr.aws/aws-containers/retail-store-sample-ui:0.2.0" } -``` \ No newline at end of file +``` diff --git a/oss/ort/curations.yml b/oss/ort/curations.yml index e0595f746..4a389b1b2 100644 --- a/oss/ort/curations.yml +++ b/oss/ort/curations.yml @@ -17,4 +17,4 @@ - id: "Maven:org.hdrhistogram:HdrHistogram" curations: comment: "Dual-licensed, using BSD-2-Clause" - concluded_license: "BSD-2-Clause" \ No newline at end of file + concluded_license: "BSD-2-Clause" diff --git a/oss/ort/go-mod.ort.yml b/oss/ort/go-mod.ort.yml index 518cdf0f2..ef7dbfbe7 100644 --- a/oss/ort/go-mod.ort.yml +++ b/oss/ort/go-mod.ort.yml @@ -1 +1 @@ -excludes: {} \ No newline at end of file +excludes: {} diff --git a/oss/ort/maven.ort.yml b/oss/ort/maven.ort.yml index e51147ebb..002d85cf5 100644 --- a/oss/ort/maven.ort.yml +++ b/oss/ort/maven.ort.yml @@ -1,11 +1,11 @@ excludes: scopes: - - pattern: "provided" - reason: "PROVIDED_DEPENDENCY_OF" - comment: "Packages provided at runtime by the JDK or container only." - - pattern: "test" - reason: "TEST_DEPENDENCY_OF" - comment: "Packages for testing only." - - pattern: "devDependencies" - reason: "DEV_DEPENDENCY_OF" - comment: "Packages for development only." + - pattern: "provided" + reason: "PROVIDED_DEPENDENCY_OF" + comment: "Packages provided at runtime by the JDK or container only." + - pattern: "test" + reason: "TEST_DEPENDENCY_OF" + comment: "Packages for testing only." + - pattern: "devDependencies" + reason: "DEV_DEPENDENCY_OF" + comment: "Packages for development only." diff --git a/oss/ort/npm.ort.yml b/oss/ort/npm.ort.yml index 7712f1f1a..78e550a28 100644 --- a/oss/ort/npm.ort.yml +++ b/oss/ort/npm.ort.yml @@ -1,5 +1,5 @@ excludes: scopes: - - pattern: "devDependencies" - reason: "DEV_DEPENDENCY_OF" - comment: "Packages for development only." \ No newline at end of file + - pattern: "devDependencies" + reason: "DEV_DEPENDENCY_OF" + comment: "Packages for development only." diff --git a/release-notes-configuration.json b/release-notes-configuration.json index f3877e6e7..bf7286e08 100644 --- a/release-notes-configuration.json +++ b/release-notes-configuration.json @@ -13,8 +13,8 @@ "labels": ["test"] }, { - "title": "## ๐Ÿ“ฆ Dependencies", - "labels": ["deps"] + "title": "## ๐Ÿ“ฆ Dependencies", + "labels": ["deps"] }, { "title": "## ๐Ÿ“– Documentation", @@ -25,11 +25,7 @@ "labels": ["chore"] } ], - "ignore_labels": [ - "release", - "deps", - "dependabot" - ], + "ignore_labels": ["release", "deps", "dependabot"], "transformers": [ { "pattern": "[\\-\\*] ((feat|fix|test|chore|docs):)( )?(.+?)\n(.+?[\\-\\*] )(.+)", diff --git a/src/assets/buildpack.yml b/src/assets/buildpack.yml index cab5b89d2..0dc4b8a55 100644 --- a/src/assets/buildpack.yml +++ b/src/assets/buildpack.yml @@ -1,3 +1,3 @@ --- nginx: - version: "mainline" \ No newline at end of file + version: "mainline" diff --git a/src/assets/public/health.html b/src/assets/public/health.html index a0aba9318..d86bac9de 100644 --- a/src/assets/public/health.html +++ b/src/assets/public/health.html @@ -1 +1 @@ -OK \ No newline at end of file +OK diff --git a/src/cart/README.md b/src/cart/README.md index 91f8cee11..dad8a33c3 100644 --- a/src/cart/README.md +++ b/src/cart/README.md @@ -1,8 +1,8 @@ # AWS Containers Retail Sample - Cart Service -| Language | Persistence | -|---|---| -| Java | Amazon DynamoDB | +| Language | Persistence | +| -------- | --------------- | +| Java | Amazon DynamoDB | This service provides an API for storing customer shopping carts. Data is stored in Amazon DynamoDB. @@ -10,11 +10,11 @@ This service provides an API for storing customer shopping carts. Data is stored The following environment variables are available for configuring the service: -| Name | Description | Default | -|---|---|---| -| `PORT` | The port which the server will listen on | `8080` | -| `CARTS_DYNAMODB_TABLENAME` | The name of the Amazon DynamoDB table used for persistence | `Items` | -| `CARTS_DYNAMODB_ENDPOINT` | The Amazon DynamoDB endpoint to use | ` ` | +| Name | Description | Default | +| ---------------------------- | ----------------------------------------------------------------- | ------- | +| `PORT` | The port which the server will listen on | `8080` | +| `CARTS_DYNAMODB_TABLENAME` | The name of the Amazon DynamoDB table used for persistence | `Items` | +| `CARTS_DYNAMODB_ENDPOINT` | The Amazon DynamoDB endpoint to use | ` ` | | `CARTS_DYNAMODB_CREATETABLE` | Enable to automatically create the Amazon DynamoDB table required | `false` | ## Running @@ -24,6 +24,7 @@ There are two main options for running the service: ### Local Pre-requisites: + - Java 17 installed Run the Spring Boot application like so: @@ -48,4 +49,4 @@ To clean up: ``` docker compose down -``` \ No newline at end of file +``` diff --git a/src/cart/openapi.yml b/src/cart/openapi.yml index c310dba78..a86f08c26 100644 --- a/src/cart/openapi.yml +++ b/src/cart/openapi.yml @@ -22,11 +22,11 @@ paths: "200": description: OK content: - '*/*': + "*/*": schema: type: array items: - $ref: '#/components/schemas/Item' + $ref: "#/components/schemas/Item" post: tags: - carts @@ -42,15 +42,15 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/Item' + $ref: "#/components/schemas/Item" required: true responses: "201": description: Created content: - '*/*': + "*/*": schema: - $ref: '#/components/schemas/Item' + $ref: "#/components/schemas/Item" patch: tags: - carts @@ -66,7 +66,7 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/Item' + $ref: "#/components/schemas/Item" required: true responses: "202": @@ -87,9 +87,9 @@ paths: "200": description: OK content: - '*/*': + "*/*": schema: - $ref: '#/components/schemas/Cart' + $ref: "#/components/schemas/Cart" delete: tags: - carts @@ -105,9 +105,9 @@ paths: "202": description: Accepted content: - '*/*': + "*/*": schema: - $ref: '#/components/schemas/Cart' + $ref: "#/components/schemas/Cart" /carts/{customerId}/merge: get: tags: @@ -149,9 +149,9 @@ paths: "200": description: OK content: - '*/*': + "*/*": schema: - $ref: '#/components/schemas/Item' + $ref: "#/components/schemas/Item" delete: tags: - carts @@ -192,4 +192,4 @@ components: items: type: array items: - $ref: '#/components/schemas/Item' + $ref: "#/components/schemas/Item" diff --git a/src/cart/src/main/resources/application-chaos-errors.yml b/src/cart/src/main/resources/application-chaos-errors.yml index 22be39da6..9a2f49681 100644 --- a/src/cart/src/main/resources/application-chaos-errors.yml +++ b/src/cart/src/main/resources/application-chaos-errors.yml @@ -3,4 +3,4 @@ chaos: assaults: exceptionsActive: true exception: - type: com.amazon.sample.carts.chaos.Http500StatusException \ No newline at end of file + type: com.amazon.sample.carts.chaos.Http500StatusException diff --git a/src/cart/src/main/resources/application-chaos-latency.yml b/src/cart/src/main/resources/application-chaos-latency.yml index 3c0e1241b..18c40fbe6 100644 --- a/src/cart/src/main/resources/application-chaos-latency.yml +++ b/src/cart/src/main/resources/application-chaos-latency.yml @@ -1,4 +1,4 @@ chaos: monkey: assaults: - latencyActive: true \ No newline at end of file + latencyActive: true diff --git a/src/cart/src/main/resources/application-chaos-monkey.yml b/src/cart/src/main/resources/application-chaos-monkey.yml index 828777177..a5db0d8cf 100644 --- a/src/cart/src/main/resources/application-chaos-monkey.yml +++ b/src/cart/src/main/resources/application-chaos-monkey.yml @@ -14,4 +14,4 @@ chaos: - com.amazon.sample.carts.controllers.ItemsController.updateItem watcher: restController: true - service: false \ No newline at end of file + service: false diff --git a/src/cart/src/main/resources/application-mongo.yml b/src/cart/src/main/resources/application-mongo.yml index ba44b9a4c..40e15c713 100644 --- a/src/cart/src/main/resources/application-mongo.yml +++ b/src/cart/src/main/resources/application-mongo.yml @@ -1,4 +1,4 @@ spring: data: mongodb: - uri: mongodb://${mongo_db:carts-db}:27017/data \ No newline at end of file + uri: mongodb://${mongo_db:carts-db}:27017/data diff --git a/src/cart/src/main/resources/application-prod.yml b/src/cart/src/main/resources/application-prod.yml index 037ed6c42..d3696f5f6 100644 --- a/src/cart/src/main/resources/application-prod.yml +++ b/src/cart/src/main/resources/application-prod.yml @@ -1,2 +1,2 @@ server: - shutdown: graceful \ No newline at end of file + shutdown: graceful diff --git a/src/cart/src/main/resources/application.yml b/src/cart/src/main/resources/application.yml index e50b7f51f..bcd4888d7 100644 --- a/src/cart/src/main/resources/application.yml +++ b/src/cart/src/main/resources/application.yml @@ -2,7 +2,7 @@ management: endpoints: web: exposure: - include: '*' + include: "*" server: port: ${port:8080} @@ -16,4 +16,4 @@ spring: - org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration - org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration - org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration - - org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration \ No newline at end of file + - org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration diff --git a/src/catalog/README.md b/src/catalog/README.md index 13eb30b21..db65ccec4 100644 --- a/src/catalog/README.md +++ b/src/catalog/README.md @@ -1,8 +1,8 @@ # AWS Containers Retail Sample - Catalog Service | Language | Persistence | -|---|---| -| Go | MySQL | +| -------- | ----------- | +| Go | MySQL | This service provides an API for retrieving product catalog information. Data is stored in a MySQL database. @@ -10,16 +10,16 @@ This service provides an API for retrieving product catalog information. Data is The following environment variables are available for configuring the service: -| Name | Description | Default | -|---|---|---| -| PORT | The port which the server will listen on | `8080` | -| DB_ENDPOINT | The endpoint of the MySQL database | `catalog-db:3306` | -| DB_READ_ENDPOINT | (Optional) The read endpoint of the MySQL database | | -| DB_NAME | The name of the database to connect to | `sampledb` | -| DB_USER | The username for authenticating to the database | `catalog_user` | -| DB_PASSWORD | The password for authenticating to the database | | -| DB_MIGRATE | Whether to run the database migration function on startup | `true` | -| DB_CONNECT_TIMEOUT | Database connection timeout in seconds | `5` | +| Name | Description | Default | +| ------------------ | --------------------------------------------------------- | ----------------- | +| PORT | The port which the server will listen on | `8080` | +| DB_ENDPOINT | The endpoint of the MySQL database | `catalog-db:3306` | +| DB_READ_ENDPOINT | (Optional) The read endpoint of the MySQL database | | +| DB_NAME | The name of the database to connect to | `sampledb` | +| DB_USER | The username for authenticating to the database | `catalog_user` | +| DB_PASSWORD | The password for authenticating to the database | | +| DB_MIGRATE | Whether to run the database migration function on startup | `true` | +| DB_CONNECT_TIMEOUT | Database connection timeout in seconds | `5` | ## Running @@ -65,4 +65,4 @@ To clean up: ``` docker compose down -``` \ No newline at end of file +``` diff --git a/src/catalog/docs/swagger.json b/src/catalog/docs/swagger.json index e7ae04114..0735338d2 100644 --- a/src/catalog/docs/swagger.json +++ b/src/catalog/docs/swagger.json @@ -1,293 +1,269 @@ { - "swagger": "2.0", - "info": { - "description": "This API serves the product catalog", - "title": "Catalog API", - "contact": {}, - "license": { - "name": "Apache 2.0", - "url": "http://www.apache.org/licenses/LICENSE-2.0.html" - }, - "version": "1.0" + "swagger": "2.0", + "info": { + "description": "This API serves the product catalog", + "title": "Catalog API", + "contact": {}, + "license": { + "name": "Apache 2.0", + "url": "http://www.apache.org/licenses/LICENSE-2.0.html" }, - "host": "localhost:8080", - "basePath": "/", - "paths": { - "/catalogue": { - "get": { - "description": "Get catalog", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "catalog" - ], - "summary": "Get catalog", - "parameters": [ - { - "type": "string", - "description": "Tagged products to include", - "name": "tags", - "in": "query" - }, - { - "type": "string", - "description": "Order of response", - "name": "order", - "in": "query" - }, - { - "type": "integer", - "description": "Page number", - "name": "page", - "in": "query" - }, - { - "type": "integer", - "description": "Page size", - "name": "size", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/model.Product" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/httputil.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/httputil.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/httputil.HTTPError" - } - } - } + "version": "1.0" + }, + "host": "localhost:8080", + "basePath": "/", + "paths": { + "/catalogue": { + "get": { + "description": "Get catalog", + "consumes": ["application/json"], + "produces": ["application/json"], + "tags": ["catalog"], + "summary": "Get catalog", + "parameters": [ + { + "type": "string", + "description": "Tagged products to include", + "name": "tags", + "in": "query" + }, + { + "type": "string", + "description": "Order of response", + "name": "order", + "in": "query" + }, + { + "type": "integer", + "description": "Page number", + "name": "page", + "in": "query" + }, + { + "type": "integer", + "description": "Page size", + "name": "size", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/model.Product" + } } - }, - "/catalogue/product/{id}": { - "get": { - "description": "Get catalog", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "catalog" - ], - "summary": "Get catalog", - "parameters": [ - { - "type": "string", - "description": "product ID", - "name": "id", - "in": "path", - "required": true - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/model.Product" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/httputil.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/httputil.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/httputil.HTTPError" - } - } - } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" } - }, - "/catalogue/size": { - "get": { - "description": "Get catalog size", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "catalog" - ], - "summary": "Get catalog size", - "parameters": [ - { - "type": "string", - "description": "Tagged products to include", - "name": "tags", - "in": "query" - } - ], - "responses": { - "200": { - "description": "OK", - "schema": { - "$ref": "#/definitions/model.CatalogSizeResponse" - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/httputil.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/httputil.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/httputil.HTTPError" - } - } - } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" } - }, - "/catalogue/tags": { - "get": { - "description": "get tags", - "consumes": [ - "application/json" - ], - "produces": [ - "application/json" - ], - "tags": [ - "catalog" - ], - "summary": "List tags", - "responses": { - "200": { - "description": "OK", - "schema": { - "type": "array", - "items": { - "$ref": "#/definitions/model.Tag" - } - } - }, - "400": { - "description": "Bad Request", - "schema": { - "$ref": "#/definitions/httputil.HTTPError" - } - }, - "404": { - "description": "Not Found", - "schema": { - "$ref": "#/definitions/httputil.HTTPError" - } - }, - "500": { - "description": "Internal Server Error", - "schema": { - "$ref": "#/definitions/httputil.HTTPError" - } - } - } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" } + } } + } }, - "definitions": { - "httputil.HTTPError": { - "type": "object", - "properties": { - "code": { - "type": "integer", - "example": 400 - }, - "message": { - "type": "string", - "example": "status bad request" - } + "/catalogue/product/{id}": { + "get": { + "description": "Get catalog", + "consumes": ["application/json"], + "produces": ["application/json"], + "tags": ["catalog"], + "summary": "Get catalog", + "parameters": [ + { + "type": "string", + "description": "product ID", + "name": "id", + "in": "path", + "required": true + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/model.Product" } - }, - "model.CatalogSizeResponse": { - "type": "object", - "properties": { - "size": { - "type": "integer" - } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" } - }, - "model.Product": { - "type": "object", - "properties": { - "count": { - "type": "integer" - }, - "description": { - "type": "string" - }, - "id": { - "type": "string" - }, - "imageUrl": { - "type": "string" - }, - "name": { - "type": "string" - }, - "price": { - "type": "integer" - }, - "tag": { - "type": "array", - "items": { - "type": "string" - } - } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" } - }, - "model.Tag": { - "type": "object", - "properties": { - "displayName": { - "type": "string" - }, - "name": { - "type": "string" - } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + } + } + } + }, + "/catalogue/size": { + "get": { + "description": "Get catalog size", + "consumes": ["application/json"], + "produces": ["application/json"], + "tags": ["catalog"], + "summary": "Get catalog size", + "parameters": [ + { + "type": "string", + "description": "Tagged products to include", + "name": "tags", + "in": "query" + } + ], + "responses": { + "200": { + "description": "OK", + "schema": { + "$ref": "#/definitions/model.CatalogSizeResponse" + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + } + } + } + }, + "/catalogue/tags": { + "get": { + "description": "get tags", + "consumes": ["application/json"], + "produces": ["application/json"], + "tags": ["catalog"], + "summary": "List tags", + "responses": { + "200": { + "description": "OK", + "schema": { + "type": "array", + "items": { + "$ref": "#/definitions/model.Tag" + } + } + }, + "400": { + "description": "Bad Request", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + }, + "404": { + "description": "Not Found", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" } + }, + "500": { + "description": "Internal Server Error", + "schema": { + "$ref": "#/definitions/httputil.HTTPError" + } + } + } + } + } + }, + "definitions": { + "httputil.HTTPError": { + "type": "object", + "properties": { + "code": { + "type": "integer", + "example": 400 + }, + "message": { + "type": "string", + "example": "status bad request" + } + } + }, + "model.CatalogSizeResponse": { + "type": "object", + "properties": { + "size": { + "type": "integer" + } + } + }, + "model.Product": { + "type": "object", + "properties": { + "count": { + "type": "integer" + }, + "description": { + "type": "string" + }, + "id": { + "type": "string" + }, + "imageUrl": { + "type": "string" + }, + "name": { + "type": "string" + }, + "price": { + "type": "integer" + }, + "tag": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "model.Tag": { + "type": "object", + "properties": { + "displayName": { + "type": "string" + }, + "name": { + "type": "string" } + } } -} \ No newline at end of file + } +} diff --git a/src/catalog/docs/swagger.yaml b/src/catalog/docs/swagger.yaml index 9438fa0d6..dc257264a 100644 --- a/src/catalog/docs/swagger.yaml +++ b/src/catalog/docs/swagger.yaml @@ -53,141 +53,141 @@ paths: /catalogue: get: consumes: - - application/json + - application/json description: Get catalog parameters: - - description: Tagged products to include - in: query - name: tags - type: string - - description: Order of response - in: query - name: order - type: string - - description: Page number - in: query - name: page - type: integer - - description: Page size - in: query - name: size - type: integer + - description: Tagged products to include + in: query + name: tags + type: string + - description: Order of response + in: query + name: order + type: string + - description: Page number + in: query + name: page + type: integer + - description: Page size + in: query + name: size + type: integer produces: - - application/json + - application/json responses: "200": description: OK schema: items: - $ref: '#/definitions/model.Product' + $ref: "#/definitions/model.Product" type: array "400": description: Bad Request schema: - $ref: '#/definitions/httputil.HTTPError' + $ref: "#/definitions/httputil.HTTPError" "404": description: Not Found schema: - $ref: '#/definitions/httputil.HTTPError' + $ref: "#/definitions/httputil.HTTPError" "500": description: Internal Server Error schema: - $ref: '#/definitions/httputil.HTTPError' + $ref: "#/definitions/httputil.HTTPError" summary: Get catalog tags: - - catalog + - catalog /catalogue/product/{id}: get: consumes: - - application/json + - application/json description: Get catalog parameters: - - description: product ID - in: path - name: id - required: true - type: string + - description: product ID + in: path + name: id + required: true + type: string produces: - - application/json + - application/json responses: "200": description: OK schema: - $ref: '#/definitions/model.Product' + $ref: "#/definitions/model.Product" "400": description: Bad Request schema: - $ref: '#/definitions/httputil.HTTPError' + $ref: "#/definitions/httputil.HTTPError" "404": description: Not Found schema: - $ref: '#/definitions/httputil.HTTPError' + $ref: "#/definitions/httputil.HTTPError" "500": description: Internal Server Error schema: - $ref: '#/definitions/httputil.HTTPError' + $ref: "#/definitions/httputil.HTTPError" summary: Get catalog tags: - - catalog + - catalog /catalogue/size: get: consumes: - - application/json + - application/json description: Get catalog size parameters: - - description: Tagged products to include - in: query - name: tags - type: string + - description: Tagged products to include + in: query + name: tags + type: string produces: - - application/json + - application/json responses: "200": description: OK schema: - $ref: '#/definitions/model.CatalogSizeResponse' + $ref: "#/definitions/model.CatalogSizeResponse" "400": description: Bad Request schema: - $ref: '#/definitions/httputil.HTTPError' + $ref: "#/definitions/httputil.HTTPError" "404": description: Not Found schema: - $ref: '#/definitions/httputil.HTTPError' + $ref: "#/definitions/httputil.HTTPError" "500": description: Internal Server Error schema: - $ref: '#/definitions/httputil.HTTPError' + $ref: "#/definitions/httputil.HTTPError" summary: Get catalog size tags: - - catalog + - catalog /catalogue/tags: get: consumes: - - application/json + - application/json description: get tags produces: - - application/json + - application/json responses: "200": description: OK schema: items: - $ref: '#/definitions/model.Tag' + $ref: "#/definitions/model.Tag" type: array "400": description: Bad Request schema: - $ref: '#/definitions/httputil.HTTPError' + $ref: "#/definitions/httputil.HTTPError" "404": description: Not Found schema: - $ref: '#/definitions/httputil.HTTPError' + $ref: "#/definitions/httputil.HTTPError" "500": description: Internal Server Error schema: - $ref: '#/definitions/httputil.HTTPError' + $ref: "#/definitions/httputil.HTTPError" summary: List tags tags: - - catalog + - catalog swagger: "2.0" diff --git a/src/checkout/.eslintrc.js b/src/checkout/.eslintrc.js index 0a0d68e20..dbfe3a3a8 100644 --- a/src/checkout/.eslintrc.js +++ b/src/checkout/.eslintrc.js @@ -20,7 +20,7 @@ module.exports = { parser: '@typescript-eslint/parser', parserOptions: { project: 'tsconfig.json', - tsconfigRootDir : __dirname, + tsconfigRootDir: __dirname, sourceType: 'module', }, plugins: ['@typescript-eslint/eslint-plugin'], diff --git a/src/checkout/.prettierrc b/src/checkout/.prettierrc index dcb72794f..a20502b7f 100644 --- a/src/checkout/.prettierrc +++ b/src/checkout/.prettierrc @@ -1,4 +1,4 @@ { "singleQuote": true, "trailingComma": "all" -} \ No newline at end of file +} diff --git a/src/checkout/README.md b/src/checkout/README.md index 8202e92ee..397906cd5 100644 --- a/src/checkout/README.md +++ b/src/checkout/README.md @@ -1,8 +1,8 @@ # AWS Containers Retail Sample - Checkout Service | Language | Persistence | -|---|---| -| Node | Redis | +| -------- | ----------- | +| Node | Redis | This service provides an API for storing customer data during the checkout process. Data is stored in Redis. @@ -10,13 +10,13 @@ This service provides an API for storing customer data during the checkout proce The following environment variables are available for configuring the service: -| Name | Description | Default | -|---|---|---| -| `PORT` | The port which the server will listen on | `8080` | -| `ENDPOINTS_ORDERS` | The endpoint of the orders API. If empty uses a mock implementation | `""` | -| `REDIS_URL` | The endpoint of the Redis server used to write data. If empty use in-memory storage | `""` | -| `REDIS_READER_URL` | The endpoint of the Redis server used to read data. If empty use the value of `REDIS_URL` | `""` | -| `SHIPPING_NAME_PREFIX` | A string prefix that can be applied to the names of the shipping options | `""` | +| Name | Description | Default | +| ---------------------- | ----------------------------------------------------------------------------------------- | ------- | +| `PORT` | The port which the server will listen on | `8080` | +| `ENDPOINTS_ORDERS` | The endpoint of the orders API. If empty uses a mock implementation | `""` | +| `REDIS_URL` | The endpoint of the Redis server used to write data. If empty use in-memory storage | `""` | +| `REDIS_READER_URL` | The endpoint of the Redis server used to read data. If empty use the value of `REDIS_URL` | `""` | +| `SHIPPING_NAME_PREFIX` | A string prefix that can be applied to the names of the shipping options | `""` | ## Running @@ -25,6 +25,7 @@ There are two main options for running the service: ### Local Pre-requisites: + - Node.JS >= 16 installed Run the application like so: diff --git a/src/checkout/src/app.controller.ts b/src/checkout/src/app.controller.ts index 7e87c008b..a69e5d978 100644 --- a/src/checkout/src/app.controller.ts +++ b/src/checkout/src/app.controller.ts @@ -21,9 +21,7 @@ import { HealthCheck, HealthCheckService } from '@nestjs/terminus'; @Controller() export class AppController { - constructor( - private healthCheckService: HealthCheckService, - ){} + constructor(private healthCheckService: HealthCheckService) {} @Get('health') @HealthCheck() diff --git a/src/checkout/src/app.module.ts b/src/checkout/src/app.module.ts index 7d0b562ec..751cac297 100644 --- a/src/checkout/src/app.module.ts +++ b/src/checkout/src/app.module.ts @@ -26,14 +26,12 @@ import { LoggerMiddleware } from './middleware/logger.middleware'; import { PrometheusModule } from '@willsoto/nestjs-prometheus'; import { OpenTelemetryModule } from 'nestjs-otel'; -const OpenTelemetryModuleConfig = OpenTelemetryModule.forRoot({ - -}); +const OpenTelemetryModuleConfig = OpenTelemetryModule.forRoot({}); @Module({ imports: [ ConfigModule.forRoot({ - load: [configuration] + load: [configuration], }), TerminusModule, PrometheusModule.register(), @@ -45,8 +43,6 @@ const OpenTelemetryModuleConfig = OpenTelemetryModule.forRoot({ }) export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { - consumer.apply(LoggerMiddleware) - .exclude('health') - .forRoutes('*'); + consumer.apply(LoggerMiddleware).exclude('health').forRoutes('*'); } -} \ No newline at end of file +} diff --git a/src/checkout/src/checkout/checkout.controller.ts b/src/checkout/src/checkout/checkout.controller.ts index cd4958042..4070895e7 100644 --- a/src/checkout/src/checkout/checkout.controller.ts +++ b/src/checkout/src/checkout/checkout.controller.ts @@ -16,7 +16,15 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import { Body, Controller, Get, Inject, NotFoundException, Param, Post } from '@nestjs/common'; +import { + Body, + Controller, + Get, + Inject, + NotFoundException, + Param, + Post, +} from '@nestjs/common'; import { CheckoutService } from './checkout.service'; import { Checkout } from './models/Checkout'; import { CheckoutRequest } from './models/CheckoutRequest'; @@ -33,11 +41,13 @@ export class CheckoutController { }*/ @Get(':customerId') - async getCheckout(@Param('customerId') customerId: string) : Promise { + async getCheckout( + @Param('customerId') customerId: string, + ): Promise { const checkout = this.checkoutService.get(customerId); - return checkout.then(function(data) { - if(!data) { + return checkout.then(function (data) { + if (!data) { throw new NotFoundException('Checkout not found'); } @@ -46,12 +56,17 @@ export class CheckoutController { } @Post(':customerId/update') - async updateCheckout(@Param('customerId') customerId: string, @Body() request: CheckoutRequest) : Promise { + async updateCheckout( + @Param('customerId') customerId: string, + @Body() request: CheckoutRequest, + ): Promise { return this.checkoutService.update(customerId, request); } @Post(':customerId/submit') - async submitCheckout(@Param('customerId') customerId: string) : Promise { + async submitCheckout( + @Param('customerId') customerId: string, + ): Promise { return this.checkoutService.submit(customerId); } } diff --git a/src/checkout/src/checkout/checkout.module.ts b/src/checkout/src/checkout/checkout.module.ts index 93718339c..8f68b9f48 100644 --- a/src/checkout/src/checkout/checkout.module.ts +++ b/src/checkout/src/checkout/checkout.module.ts @@ -20,15 +20,19 @@ import { Module } from '@nestjs/common'; import { ConfigModule, ConfigService } from '@nestjs/config'; import { CheckoutController } from './checkout.controller'; import { CheckoutService } from './checkout.service'; -import { MockOrdersService, HttpOrdersService } from './orders' -import { InMemoryCheckoutRepository, ICheckoutRepository, RedisCheckoutRepository } from './repositories'; +import { MockOrdersService, HttpOrdersService } from './orders'; +import { + InMemoryCheckoutRepository, + ICheckoutRepository, + RedisCheckoutRepository, +} from './repositories'; import { MockShippingService } from './shipping'; const orderServiceProvider = { provide: 'OrdersService', useFactory: (configService: ConfigService) => { - const ordersEndpoint = configService.get('endpoints.orders') - if(ordersEndpoint) { + const ordersEndpoint = configService.get('endpoints.orders'); + if (ordersEndpoint) { return new HttpOrdersService(ordersEndpoint); } return new MockOrdersService(); @@ -50,17 +54,16 @@ const repositoryProvider = { let redisUrl = configService.get('redis.url'); let redisReaderUrl = configService.get('redis.reader.url'); - if(!redisReaderUrl) { + if (!redisReaderUrl) { redisReaderUrl = redisUrl; } - let repository : ICheckoutRepository; + let repository: ICheckoutRepository; - if(redisUrl) { + if (redisUrl) { console.log('Creating RedisRepository...'); repository = new RedisCheckoutRepository(redisUrl, redisReaderUrl); - } - else { + } else { console.log('Creating InMemoryRepository...'); repository = new InMemoryCheckoutRepository(); } @@ -73,6 +76,11 @@ const repositoryProvider = { @Module({ imports: [ConfigModule], controllers: [CheckoutController], - providers: [orderServiceProvider, shippingServiceProvider, repositoryProvider, CheckoutService], + providers: [ + orderServiceProvider, + shippingServiceProvider, + repositoryProvider, + CheckoutService, + ], }) export class CheckoutModule {} diff --git a/src/checkout/src/checkout/checkout.service.ts b/src/checkout/src/checkout/checkout.service.ts index 7bbb0e457..f6119ee47 100644 --- a/src/checkout/src/checkout/checkout.service.ts +++ b/src/checkout/src/checkout/checkout.service.ts @@ -17,68 +17,77 @@ */ import { Inject, Injectable } from '@nestjs/common'; -import { ConfigService } from '@nestjs/config' +import { ConfigService } from '@nestjs/config'; import { Checkout } from './models/Checkout'; import { CheckoutRequest } from './models/CheckoutRequest'; import { IOrdersService } from './orders/IOrdersService'; -import { serialize , deserialize} from 'class-transformer'; +import { serialize, deserialize } from 'class-transformer'; import { CheckoutSubmitted } from './models/CheckoutSubmitted'; import { IShippingService } from './shipping'; import { ICheckoutRepository } from './repositories'; @Injectable() export class CheckoutService { - constructor(private configService: ConfigService, - @Inject('CheckoutRepository') private checkoutRepository : ICheckoutRepository, - @Inject('OrdersService') private ordersService : IOrdersService, - @Inject('ShippingService') private shippingService : IShippingService) {} - - async get(customerId: string) : Promise { + constructor( + private configService: ConfigService, + @Inject('CheckoutRepository') + private checkoutRepository: ICheckoutRepository, + @Inject('OrdersService') private ordersService: IOrdersService, + @Inject('ShippingService') private shippingService: IShippingService, + ) {} + + async get(customerId: string): Promise { const json = await this.checkoutRepository.get(customerId); - if(!json) { + if (!json) { return null; } return deserialize(Checkout, json); } - - async update(customerId: string, request : CheckoutRequest) : Promise { - const tax = request.shippingAddress ? Math.floor(request.subtotal * 0.05) : -1; // Hardcoded 5% tax for now + async update( + customerId: string, + request: CheckoutRequest, + ): Promise { + const tax = request.shippingAddress + ? Math.floor(request.subtotal * 0.05) + : -1; // Hardcoded 5% tax for now const effectiveTax = tax == -1 ? 0 : tax; - return this.shippingService.getShippingRates(request).then(async (shippingRates) => { - let shipping = -1; + return this.shippingService + .getShippingRates(request) + .then(async (shippingRates) => { + let shipping = -1; - if(shippingRates) { - for ( let i = 0; i < shippingRates.rates.length; i++ ) { - if(shippingRates.rates[i].token == request.deliveryOptionToken) { - shipping = shippingRates.rates[i].amount; + if (shippingRates) { + for (let i = 0; i < shippingRates.rates.length; i++) { + if (shippingRates.rates[i].token == request.deliveryOptionToken) { + shipping = shippingRates.rates[i].amount; + } } } - } - const checkout : Checkout = { - shippingRates, - request, - paymentId: this.makeid(16), - paymentToken: this.makeid(32), - shipping, - tax, - total: request.subtotal + effectiveTax, - }; + const checkout: Checkout = { + shippingRates, + request, + paymentId: this.makeid(16), + paymentToken: this.makeid(32), + shipping, + tax, + total: request.subtotal + effectiveTax, + }; - await this.checkoutRepository.set(customerId, serialize(checkout)); + await this.checkoutRepository.set(customerId, serialize(checkout)); - return checkout; - }); + return checkout; + }); } - async submit(customerId: string) : Promise { + async submit(customerId: string): Promise { let checkout = await this.get(customerId); - if(!checkout) { + if (!checkout) { throw new Error('Checkout not found'); } @@ -88,16 +97,17 @@ export class CheckoutService { return Promise.resolve({ orderId: order.id, - customerEmail: checkout.request.customerEmail + customerEmail: checkout.request.customerEmail, }); } private makeid(length) { - let result = ''; - const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + let result = ''; + const characters = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const charactersLength = characters.length; - for ( let i = 0; i < length; i++ ) { - result += characters.charAt(Math.floor(Math.random() * charactersLength)); + for (let i = 0; i < length; i++) { + result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; } diff --git a/src/checkout/src/checkout/models/Checkout.ts b/src/checkout/src/checkout/models/Checkout.ts index 06cbd1630..8da6a41fc 100644 --- a/src/checkout/src/checkout/models/Checkout.ts +++ b/src/checkout/src/checkout/models/Checkout.ts @@ -22,31 +22,29 @@ import { CheckoutRequest } from './CheckoutRequest'; import { ShippingRates } from './ShippingRates'; export class Checkout { - @ValidateNested() @Type(() => CheckoutRequest) - request : CheckoutRequest; + request: CheckoutRequest; @ValidateNested() @Type(() => ShippingRates) - shippingRates : ShippingRates; + shippingRates: ShippingRates; @IsString() - paymentId : string; + paymentId: string; @IsString() - paymentToken : string; + paymentToken: string; @IsInt() @Min(-1) - shipping : number; + shipping: number; @IsInt() @Min(-1) - tax : number; + tax: number; @IsInt() @Min(-1) - total : number; - -} \ No newline at end of file + total: number; +} diff --git a/src/checkout/src/checkout/models/CheckoutRequest.ts b/src/checkout/src/checkout/models/CheckoutRequest.ts index 846f3ca48..f3474481a 100644 --- a/src/checkout/src/checkout/models/CheckoutRequest.ts +++ b/src/checkout/src/checkout/models/CheckoutRequest.ts @@ -17,32 +17,37 @@ */ import { Type } from 'class-transformer'; -import { ValidateNested, IsEmail, IsInt, Min, IsOptional, IsString } from 'class-validator'; +import { + ValidateNested, + IsEmail, + IsInt, + Min, + IsOptional, + IsString, +} from 'class-validator'; import { Item } from './Item'; import { ShippingAddress } from './ShippingAddress'; export class CheckoutRequest { - @IsEmail() @IsOptional() - customerEmail : string; + customerEmail: string; @ValidateNested({ each: true }) @Type(() => Item) - items : Item[]; + items: Item[]; @ValidateNested() @Type(() => ShippingAddress) @IsOptional() - shippingAddress : ShippingAddress; + shippingAddress: ShippingAddress; @IsInt() @Min(0) - subtotal : number; + subtotal: number; @IsString() @IsOptional() - deliveryOptionToken : string; - -} \ No newline at end of file + deliveryOptionToken: string; +} diff --git a/src/checkout/src/checkout/models/CheckoutSubmitted.ts b/src/checkout/src/checkout/models/CheckoutSubmitted.ts index e915b8f72..ca91c197b 100644 --- a/src/checkout/src/checkout/models/CheckoutSubmitted.ts +++ b/src/checkout/src/checkout/models/CheckoutSubmitted.ts @@ -19,11 +19,9 @@ import { IsNumber, IsString } from 'class-validator'; export class CheckoutSubmitted { - @IsString() - orderId : string; + orderId: string; @IsString() - customerEmail : string; - -} \ No newline at end of file + customerEmail: string; +} diff --git a/src/checkout/src/checkout/models/Item.ts b/src/checkout/src/checkout/models/Item.ts index 6d3a15d8e..359efdfe1 100644 --- a/src/checkout/src/checkout/models/Item.ts +++ b/src/checkout/src/checkout/models/Item.ts @@ -19,26 +19,24 @@ import { IsString, IsInt, Min } from 'class-validator'; export class Item { - @IsString() - id : string; + id: string; @IsString() - name : string; + name: string; @IsInt() @Min(0) - quantity : number; + quantity: number; @IsInt() @Min(0) - unitCost : number; + unitCost: number; @IsInt() @Min(0) - totalCost : number; + totalCost: number; @IsString() - imageUrl : string; - -} \ No newline at end of file + imageUrl: string; +} diff --git a/src/checkout/src/checkout/models/ShippingAddress.ts b/src/checkout/src/checkout/models/ShippingAddress.ts index e78e547d0..363b37122 100644 --- a/src/checkout/src/checkout/models/ShippingAddress.ts +++ b/src/checkout/src/checkout/models/ShippingAddress.ts @@ -19,27 +19,25 @@ import { IsOptional, IsString } from 'class-validator'; export class ShippingAddress { - @IsString() - firstName : string; + firstName: string; @IsString() - lastName : string; + lastName: string; @IsString() - address1 : string; + address1: string; @IsString() @IsOptional() - address2 : string; + address2: string; @IsString() - city : string; + city: string; @IsString() - state : string; + state: string; @IsString() - zip : string; - -} \ No newline at end of file + zip: string; +} diff --git a/src/checkout/src/checkout/models/ShippingOption.ts b/src/checkout/src/checkout/models/ShippingOption.ts index 8f6e80fcd..64f22f5e8 100644 --- a/src/checkout/src/checkout/models/ShippingOption.ts +++ b/src/checkout/src/checkout/models/ShippingOption.ts @@ -19,17 +19,15 @@ import { IsInt, IsNumber, IsString } from 'class-validator'; export class ShippingOption { - @IsString() - name : string; + name: string; @IsInt() - amount : number; + amount: number; @IsString() - token : string; + token: string; @IsInt() - estimatedDays : number; - -} \ No newline at end of file + estimatedDays: number; +} diff --git a/src/checkout/src/checkout/models/ShippingRates.ts b/src/checkout/src/checkout/models/ShippingRates.ts index 6a85a10cb..117dc4cd7 100644 --- a/src/checkout/src/checkout/models/ShippingRates.ts +++ b/src/checkout/src/checkout/models/ShippingRates.ts @@ -21,12 +21,10 @@ import { IsString, ValidateNested } from 'class-validator'; import { ShippingOption } from './ShippingOption'; export class ShippingRates { - @IsString() - shipmentId : string; + shipmentId: string; @ValidateNested({ each: true }) @Type(() => ShippingOption) - rates : ShippingOption[]; - -} \ No newline at end of file + rates: ShippingOption[]; +} diff --git a/src/checkout/src/checkout/orders/HttpOrdersService.ts b/src/checkout/src/checkout/orders/HttpOrdersService.ts index 486ccc97a..67f97427e 100644 --- a/src/checkout/src/checkout/orders/HttpOrdersService.ts +++ b/src/checkout/src/checkout/orders/HttpOrdersService.ts @@ -21,21 +21,22 @@ import { ExistingOrder, OrdersApi } from '../../clients/orders/api'; import { IOrdersService } from './IOrdersService'; export class HttpOrdersService implements IOrdersService { - - private ordersApi : OrdersApi; + private ordersApi: OrdersApi; constructor(endpoint: string) { this.ordersApi = new OrdersApi(endpoint); } - async create(checkout : Checkout) : Promise { - return this.ordersApi.createOrder({ - email: checkout.request.customerEmail, - firstName: "John", - lastName: "Doe", - items: checkout.request.items - }).then((value) => { - return value.body; - }); + async create(checkout: Checkout): Promise { + return this.ordersApi + .createOrder({ + email: checkout.request.customerEmail, + firstName: 'John', + lastName: 'Doe', + items: checkout.request.items, + }) + .then((value) => { + return value.body; + }); } -} \ No newline at end of file +} diff --git a/src/checkout/src/checkout/orders/IOrdersService.ts b/src/checkout/src/checkout/orders/IOrdersService.ts index 8415149f3..e525406b3 100644 --- a/src/checkout/src/checkout/orders/IOrdersService.ts +++ b/src/checkout/src/checkout/orders/IOrdersService.ts @@ -20,5 +20,5 @@ import { ExistingOrder } from '../../clients/orders/api'; import { Checkout } from '../models/Checkout'; export interface IOrdersService { - create(checkout : Checkout) : Promise; -} \ No newline at end of file + create(checkout: Checkout): Promise; +} diff --git a/src/checkout/src/checkout/orders/MockOrdersService.ts b/src/checkout/src/checkout/orders/MockOrdersService.ts index c2d1e7ce6..c3a03e527 100644 --- a/src/checkout/src/checkout/orders/MockOrdersService.ts +++ b/src/checkout/src/checkout/orders/MockOrdersService.ts @@ -21,14 +21,12 @@ import { ExistingOrder, Order, OrdersApi } from '../../clients/orders/api'; import { IOrdersService } from './IOrdersService'; export class MockOrdersService implements IOrdersService { + constructor() {} - constructor() { - } - - async create(checkout : Checkout) : Promise { + async create(checkout: Checkout): Promise { return { - id: "abc123", - email: checkout.request.customerEmail + id: 'abc123', + email: checkout.request.customerEmail, }; } -} \ No newline at end of file +} diff --git a/src/checkout/src/checkout/orders/index.ts b/src/checkout/src/checkout/orders/index.ts index c76db3415..494c7d18a 100644 --- a/src/checkout/src/checkout/orders/index.ts +++ b/src/checkout/src/checkout/orders/index.ts @@ -16,6 +16,6 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -export {HttpOrdersService} from './HttpOrdersService' -export {MockOrdersService} from './MockOrdersService' -export {IOrdersService} from './IOrdersService' \ No newline at end of file +export { HttpOrdersService } from './HttpOrdersService'; +export { MockOrdersService } from './MockOrdersService'; +export { IOrdersService } from './IOrdersService'; diff --git a/src/checkout/src/checkout/repositories/ICheckoutRepository.ts b/src/checkout/src/checkout/repositories/ICheckoutRepository.ts index e338c0f51..157c424c1 100644 --- a/src/checkout/src/checkout/repositories/ICheckoutRepository.ts +++ b/src/checkout/src/checkout/repositories/ICheckoutRepository.ts @@ -17,7 +17,7 @@ */ export interface ICheckoutRepository { - get(key : string) : Promise; - set(key : string, value : string) : Promise; - remove(key : string) : Promise; -} \ No newline at end of file + get(key: string): Promise; + set(key: string, value: string): Promise; + remove(key: string): Promise; +} diff --git a/src/checkout/src/checkout/repositories/InMemoryCheckoutRepository.ts b/src/checkout/src/checkout/repositories/InMemoryCheckoutRepository.ts index 7f19196af..acfcd71cc 100644 --- a/src/checkout/src/checkout/repositories/InMemoryCheckoutRepository.ts +++ b/src/checkout/src/checkout/repositories/InMemoryCheckoutRepository.ts @@ -21,26 +21,25 @@ import { ICheckoutRepository } from './ICheckoutRepository'; @Injectable() export class InMemoryCheckoutRepository implements ICheckoutRepository { + map = new Map(); - map = new Map(); - - async get(key : string) : Promise { - if(this.map.has(key)) { + async get(key: string): Promise { + if (this.map.has(key)) { return Promise.resolve(this.map.get(key)); } return null; } - async set(key : string, value : string) : Promise { + async set(key: string, value: string): Promise { this.map.set(key, value); return Promise.resolve(value); } - async remove(key : string) : Promise { + async remove(key: string): Promise { this.map.delete(key); return Promise.resolve(null); } -} \ No newline at end of file +} diff --git a/src/checkout/src/checkout/repositories/RedisCheckoutRepository.ts b/src/checkout/src/checkout/repositories/RedisCheckoutRepository.ts index 61bfafd65..eda2af860 100644 --- a/src/checkout/src/checkout/repositories/RedisCheckoutRepository.ts +++ b/src/checkout/src/checkout/repositories/RedisCheckoutRepository.ts @@ -22,47 +22,49 @@ import { Injectable } from '@nestjs/common'; @Injectable() export class RedisCheckoutRepository implements ICheckoutRepository { + private _client: RedisClientType; - private _client : RedisClientType; + private _readClient: RedisClientType; - private _readClient : RedisClientType; - - constructor(private url: string, private readerUrl: string) { } + constructor( + private url: string, + private readerUrl: string, + ) {} async client() { - if(!this._client) { - this._client = createClient({url: this.url}); + if (!this._client) { + this._client = createClient({ url: this.url }); - await this._client.connect() + await this._client.connect(); } return this._client; } async readClient() { - if(!this._readClient) { - this._readClient = createClient({url: this.readerUrl}); + if (!this._readClient) { + this._readClient = createClient({ url: this.readerUrl }); - await this._readClient.connect() + await this._readClient.connect(); } return this._readClient; } - async get(key : string) : Promise { - const client = await this.readClient() + async get(key: string): Promise { + const client = await this.readClient(); return client.get(key); } - async set(key : string, value : string) : Promise { - const client = await this.client() + async set(key: string, value: string): Promise { + const client = await this.client(); return client.set(key, value); } - async remove(key : string) : Promise { - const client = await this.client() + async remove(key: string): Promise { + const client = await this.client(); await client.del(key); @@ -74,5 +76,4 @@ export class RedisCheckoutRepository implements ICheckoutRepository { // https://github.com/dannydavidson/k8s-neo-api/blob/master/annotely-graph/apps/ops/health.js return true; } - -} \ No newline at end of file +} diff --git a/src/checkout/src/checkout/repositories/index.ts b/src/checkout/src/checkout/repositories/index.ts index eb7630554..fceb57c78 100644 --- a/src/checkout/src/checkout/repositories/index.ts +++ b/src/checkout/src/checkout/repositories/index.ts @@ -16,6 +16,6 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -export {RedisCheckoutRepository} from './RedisCheckoutRepository' -export {InMemoryCheckoutRepository} from './InMemoryCheckoutRepository' -export {ICheckoutRepository} from './ICheckoutRepository' \ No newline at end of file +export { RedisCheckoutRepository } from './RedisCheckoutRepository'; +export { InMemoryCheckoutRepository } from './InMemoryCheckoutRepository'; +export { ICheckoutRepository } from './ICheckoutRepository'; diff --git a/src/checkout/src/checkout/shipping/IShippingService.ts b/src/checkout/src/checkout/shipping/IShippingService.ts index 4a6f72ae0..2ed5dd7dc 100644 --- a/src/checkout/src/checkout/shipping/IShippingService.ts +++ b/src/checkout/src/checkout/shipping/IShippingService.ts @@ -20,5 +20,5 @@ import { CheckoutRequest } from '../models/CheckoutRequest'; import { ShippingRates } from '../models/ShippingRates'; export interface IShippingService { - getShippingRates(request : CheckoutRequest) : Promise; -} \ No newline at end of file + getShippingRates(request: CheckoutRequest): Promise; +} diff --git a/src/checkout/src/checkout/shipping/MockShippingService.ts b/src/checkout/src/checkout/shipping/MockShippingService.ts index 1cacede68..bb148615a 100644 --- a/src/checkout/src/checkout/shipping/MockShippingService.ts +++ b/src/checkout/src/checkout/shipping/MockShippingService.ts @@ -21,34 +21,36 @@ import { ShippingRates } from '../models/ShippingRates'; import { IShippingService } from './IShippingService'; export class MockShippingService implements IShippingService { + constructor(private prefix: string) {} - constructor(private prefix: string) { } - - async getShippingRates(request : CheckoutRequest) : Promise { + async getShippingRates(request: CheckoutRequest): Promise { return Promise.resolve({ shipmentId: this.makeid(32), - rates: [{ - name: `${this.prefix}Priority Mail`, - amount: 5, - token: "priority-mail", - estimatedDays: 10 - }, { - name: `${this.prefix}Priority Mail Express`, - amount: 15, - token: "priority-mail-express", - estimatedDays: 5 - }] + rates: [ + { + name: `${this.prefix}Priority Mail`, + amount: 5, + token: 'priority-mail', + estimatedDays: 10, + }, + { + name: `${this.prefix}Priority Mail Express`, + amount: 15, + token: 'priority-mail-express', + estimatedDays: 5, + }, + ], }); } - private makeid(length) { - let result = ''; - const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; + let result = ''; + const characters = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; const charactersLength = characters.length; - for ( let i = 0; i < length; i++ ) { + for (let i = 0; i < length; i++) { result += characters.charAt(Math.floor(Math.random() * charactersLength)); } return result; } -} \ No newline at end of file +} diff --git a/src/checkout/src/checkout/shipping/index.ts b/src/checkout/src/checkout/shipping/index.ts index b9a0e6afe..a2d96bed4 100644 --- a/src/checkout/src/checkout/shipping/index.ts +++ b/src/checkout/src/checkout/shipping/index.ts @@ -16,5 +16,5 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -export {MockShippingService} from './MockShippingService' -export {IShippingService} from './IShippingService' \ No newline at end of file +export { MockShippingService } from './MockShippingService'; +export { IShippingService } from './IShippingService'; diff --git a/src/checkout/src/clients/orders/api.ts b/src/checkout/src/clients/orders/api.ts index 319fd3d43..48b782fc0 100644 --- a/src/checkout/src/clients/orders/api.ts +++ b/src/checkout/src/clients/orders/api.ts @@ -18,4 +18,4 @@ // This is the entrypoint for the package export * from './api/apis'; -export * from './model/models'; \ No newline at end of file +export * from './model/models'; diff --git a/src/checkout/src/clients/orders/api/apis.ts b/src/checkout/src/clients/orders/api/apis.ts index 5c4b4ce22..ff65fc89f 100644 --- a/src/checkout/src/clients/orders/api/apis.ts +++ b/src/checkout/src/clients/orders/api/apis.ts @@ -22,18 +22,22 @@ import * as fs from 'fs'; import * as http from 'http'; export class HttpError extends Error { - constructor (public response: http.IncomingMessage, public body: any, public statusCode?: number) { - super('HTTP request failed'); - this.name = 'HttpError'; - } + constructor( + public response: http.IncomingMessage, + public body: any, + public statusCode?: number, + ) { + super('HTTP request failed'); + this.name = 'HttpError'; + } } export interface RequestDetailedFile { - value: Buffer; - options?: { - filename?: string; - contentType?: string; - } + value: Buffer; + options?: { + filename?: string; + contentType?: string; + }; } export type RequestFile = string | Buffer | fs.ReadStream | RequestDetailedFile; diff --git a/src/checkout/src/clients/orders/api/ordersApi.ts b/src/checkout/src/clients/orders/api/ordersApi.ts index 570e5ce89..6b2d5238c 100644 --- a/src/checkout/src/clients/orders/api/ordersApi.ts +++ b/src/checkout/src/clients/orders/api/ordersApi.ts @@ -35,7 +35,12 @@ import http = require('http'); import { ExistingOrder } from '../model/existingOrder'; import { Order } from '../model/order'; -import { ObjectSerializer, Authentication, VoidAuth, Interceptor } from '../model/models'; +import { + ObjectSerializer, + Authentication, + VoidAuth, + Interceptor, +} from '../model/models'; import { HttpError, RequestFile } from './apis'; @@ -45,193 +50,231 @@ let defaultBasePath = 'http://localhost:8080'; // This file is autogenerated - Please do not edit // =============================================== -export enum OrdersApiApiKeys { -} +export enum OrdersApiApiKeys {} export class OrdersApi { - protected _basePath = defaultBasePath; - protected _defaultHeaders : any = {}; - protected _useQuerystring : boolean = false; - - protected authentications = { - 'default': new VoidAuth(), - } - - protected interceptors: Interceptor[] = []; - - constructor(basePath?: string); - constructor(basePathOrUsername: string, password?: string, basePath?: string) { - if (password) { - if (basePath) { - this.basePath = basePath; - } - } else { - if (basePathOrUsername) { - this.basePath = basePathOrUsername - } - } + protected _basePath = defaultBasePath; + protected _defaultHeaders: any = {}; + protected _useQuerystring: boolean = false; + + protected authentications = { + default: new VoidAuth(), + }; + + protected interceptors: Interceptor[] = []; + + constructor(basePath?: string); + constructor( + basePathOrUsername: string, + password?: string, + basePath?: string, + ) { + if (password) { + if (basePath) { + this.basePath = basePath; + } + } else { + if (basePathOrUsername) { + this.basePath = basePathOrUsername; + } } - - set useQuerystring(value: boolean) { - this._useQuerystring = value; - } - - set basePath(basePath: string) { - this._basePath = basePath; - } - - set defaultHeaders(defaultHeaders: any) { - this._defaultHeaders = defaultHeaders; - } - - get defaultHeaders() { - return this._defaultHeaders; - } - - get basePath() { - return this._basePath; + } + + set useQuerystring(value: boolean) { + this._useQuerystring = value; + } + + set basePath(basePath: string) { + this._basePath = basePath; + } + + set defaultHeaders(defaultHeaders: any) { + this._defaultHeaders = defaultHeaders; + } + + get defaultHeaders() { + return this._defaultHeaders; + } + + get basePath() { + return this._basePath; + } + + public setDefaultAuthentication(auth: Authentication) { + this.authentications.default = auth; + } + + public setApiKey(key: OrdersApiApiKeys, value: string) { + (this.authentications as any)[OrdersApiApiKeys[key]].apiKey = value; + } + + public addInterceptor(interceptor: Interceptor) { + this.interceptors.push(interceptor); + } + + /** + * + * @summary Create an order + * @param orderRequest orderRequest + */ + public async createOrder( + orderRequest: Order, + options: { headers: { [name: string]: string } } = { headers: {} }, + ): Promise<{ response: http.IncomingMessage; body: ExistingOrder }> { + const localVarPath = this.basePath + '/orders'; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign( + {}, + this._defaultHeaders, + ); + const produces = ['*/*']; + // give precedence to 'application/json' + if (produces.indexOf('application/json') >= 0) { + localVarHeaderParams.Accept = 'application/json'; + } else { + localVarHeaderParams.Accept = produces.join(','); } + let localVarFormParams: any = {}; - public setDefaultAuthentication(auth: Authentication) { - this.authentications.default = auth; + // verify required parameter 'orderRequest' is not null or undefined + if (orderRequest === null || orderRequest === undefined) { + throw new Error( + 'Required parameter orderRequest was null or undefined when calling createOrder.', + ); } - public setApiKey(key: OrdersApiApiKeys, value: string) { - (this.authentications as any)[OrdersApiApiKeys[key]].apiKey = value; + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'POST', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + body: ObjectSerializer.serialize(orderRequest, 'Order'), + }; + let authenticationPromise = Promise.resolve(); + authenticationPromise = authenticationPromise.then(() => + this.authentications.default.applyToRequest(localVarRequestOptions), + ); + + let interceptorPromise = authenticationPromise; + for (const interceptor of this.interceptors) { + interceptorPromise = interceptorPromise.then(() => + interceptor(localVarRequestOptions), + ); } - public addInterceptor(interceptor: Interceptor) { - this.interceptors.push(interceptor); - } - - /** - * - * @summary Create an order - * @param orderRequest orderRequest - */ - public async createOrder (orderRequest: Order, options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: ExistingOrder; }> { - const localVarPath = this.basePath + '/orders'; - let localVarQueryParameters: any = {}; - let localVarHeaderParams: any = (Object).assign({}, this._defaultHeaders); - const produces = ['*/*']; - // give precedence to 'application/json' - if (produces.indexOf('application/json') >= 0) { - localVarHeaderParams.Accept = 'application/json'; + return interceptorPromise.then(() => { + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; } else { - localVarHeaderParams.Accept = produces.join(','); + localVarRequestOptions.form = localVarFormParams; } - let localVarFormParams: any = {}; - - // verify required parameter 'orderRequest' is not null or undefined - if (orderRequest === null || orderRequest === undefined) { - throw new Error('Required parameter orderRequest was null or undefined when calling createOrder.'); - } - - (Object).assign(localVarHeaderParams, options.headers); - - let localVarUseFormData = false; - - let localVarRequestOptions: localVarRequest.Options = { - method: 'POST', - qs: localVarQueryParameters, - headers: localVarHeaderParams, - uri: localVarPath, - useQuerystring: this._useQuerystring, - json: true, - body: ObjectSerializer.serialize(orderRequest, "Order") - }; - let authenticationPromise = Promise.resolve(); - authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); - - let interceptorPromise = authenticationPromise; - for (const interceptor of this.interceptors) { - interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); - } - - return interceptorPromise.then(() => { - if (Object.keys(localVarFormParams).length) { - if (localVarUseFormData) { - (localVarRequestOptions).formData = localVarFormParams; - } else { - localVarRequestOptions.form = localVarFormParams; - } + } + return new Promise<{ + response: http.IncomingMessage; + body: ExistingOrder; + }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + body = ObjectSerializer.deserialize(body, 'ExistingOrder'); + if ( + response.statusCode && + response.statusCode >= 200 && + response.statusCode <= 299 + ) { + resolve({ response: response, body: body }); + } else { + reject(new HttpError(response, body, response.statusCode)); } - return new Promise<{ response: http.IncomingMessage; body: ExistingOrder; }>((resolve, reject) => { - localVarRequest(localVarRequestOptions, (error, response, body) => { - if (error) { - reject(error); - } else { - body = ObjectSerializer.deserialize(body, "ExistingOrder"); - if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { - resolve({ response: response, body: body }); - } else { - reject(new HttpError(response, body, response.statusCode)); - } - } - }); - }); + } }); + }); + }); + } + /** + * + * @summary List orders + */ + public async listOrders( + options: { headers: { [name: string]: string } } = { headers: {} }, + ): Promise<{ response: http.IncomingMessage; body: Array }> { + const localVarPath = this.basePath + '/orders'; + let localVarQueryParameters: any = {}; + let localVarHeaderParams: any = (Object).assign( + {}, + this._defaultHeaders, + ); + const produces = ['*/*']; + // give precedence to 'application/json' + if (produces.indexOf('application/json') >= 0) { + localVarHeaderParams.Accept = 'application/json'; + } else { + localVarHeaderParams.Accept = produces.join(','); + } + let localVarFormParams: any = {}; + + (Object).assign(localVarHeaderParams, options.headers); + + let localVarUseFormData = false; + + let localVarRequestOptions: localVarRequest.Options = { + method: 'GET', + qs: localVarQueryParameters, + headers: localVarHeaderParams, + uri: localVarPath, + useQuerystring: this._useQuerystring, + json: true, + }; + + let authenticationPromise = Promise.resolve(); + authenticationPromise = authenticationPromise.then(() => + this.authentications.default.applyToRequest(localVarRequestOptions), + ); + + let interceptorPromise = authenticationPromise; + for (const interceptor of this.interceptors) { + interceptorPromise = interceptorPromise.then(() => + interceptor(localVarRequestOptions), + ); } - /** - * - * @summary List orders - */ - public async listOrders (options: {headers: {[name: string]: string}} = {headers: {}}) : Promise<{ response: http.IncomingMessage; body: Array; }> { - const localVarPath = this.basePath + '/orders'; - let localVarQueryParameters: any = {}; - let localVarHeaderParams: any = (Object).assign({}, this._defaultHeaders); - const produces = ['*/*']; - // give precedence to 'application/json' - if (produces.indexOf('application/json') >= 0) { - localVarHeaderParams.Accept = 'application/json'; - } else { - localVarHeaderParams.Accept = produces.join(','); - } - let localVarFormParams: any = {}; - - (Object).assign(localVarHeaderParams, options.headers); - - let localVarUseFormData = false; - - let localVarRequestOptions: localVarRequest.Options = { - method: 'GET', - qs: localVarQueryParameters, - headers: localVarHeaderParams, - uri: localVarPath, - useQuerystring: this._useQuerystring, - json: true, - }; - - let authenticationPromise = Promise.resolve(); - authenticationPromise = authenticationPromise.then(() => this.authentications.default.applyToRequest(localVarRequestOptions)); - let interceptorPromise = authenticationPromise; - for (const interceptor of this.interceptors) { - interceptorPromise = interceptorPromise.then(() => interceptor(localVarRequestOptions)); + return interceptorPromise.then(() => { + if (Object.keys(localVarFormParams).length) { + if (localVarUseFormData) { + (localVarRequestOptions).formData = localVarFormParams; + } else { + localVarRequestOptions.form = localVarFormParams; } - - return interceptorPromise.then(() => { - if (Object.keys(localVarFormParams).length) { - if (localVarUseFormData) { - (localVarRequestOptions).formData = localVarFormParams; - } else { - localVarRequestOptions.form = localVarFormParams; - } + } + return new Promise<{ + response: http.IncomingMessage; + body: Array; + }>((resolve, reject) => { + localVarRequest(localVarRequestOptions, (error, response, body) => { + if (error) { + reject(error); + } else { + body = ObjectSerializer.deserialize(body, 'Array'); + if ( + response.statusCode && + response.statusCode >= 200 && + response.statusCode <= 299 + ) { + resolve({ response: response, body: body }); + } else { + reject(new HttpError(response, body, response.statusCode)); } - return new Promise<{ response: http.IncomingMessage; body: Array; }>((resolve, reject) => { - localVarRequest(localVarRequestOptions, (error, response, body) => { - if (error) { - reject(error); - } else { - body = ObjectSerializer.deserialize(body, "Array"); - if (response.statusCode && response.statusCode >= 200 && response.statusCode <= 299) { - resolve({ response: response, body: body }); - } else { - reject(new HttpError(response, body, response.statusCode)); - } - } - }); - }); + } }); - } + }); + }); + } } diff --git a/src/checkout/src/clients/orders/model/existingOrder.ts b/src/checkout/src/clients/orders/model/existingOrder.ts index a120afd73..f8ff44320 100644 --- a/src/checkout/src/clients/orders/model/existingOrder.ts +++ b/src/checkout/src/clients/orders/model/existingOrder.ts @@ -32,43 +32,47 @@ import { RequestFile } from '../api'; import { OrderItem } from './orderItem'; export class ExistingOrder { - 'email'?: string; - 'firstName'?: string; - 'id'?: string; - 'items'?: Array; - 'lastName'?: string; + 'email'?: string; + 'firstName'?: string; + 'id'?: string; + 'items'?: Array; + 'lastName'?: string; - static discriminator: string | undefined = undefined; + static discriminator: string | undefined = undefined; - static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ - { - "name": "email", - "baseName": "email", - "type": "string" - }, - { - "name": "firstName", - "baseName": "firstName", - "type": "string" - }, - { - "name": "id", - "baseName": "id", - "type": "string" - }, - { - "name": "items", - "baseName": "items", - "type": "Array" - }, - { - "name": "lastName", - "baseName": "lastName", - "type": "string" - } ]; + static attributeTypeMap: Array<{ + name: string; + baseName: string; + type: string; + }> = [ + { + name: 'email', + baseName: 'email', + type: 'string', + }, + { + name: 'firstName', + baseName: 'firstName', + type: 'string', + }, + { + name: 'id', + baseName: 'id', + type: 'string', + }, + { + name: 'items', + baseName: 'items', + type: 'Array', + }, + { + name: 'lastName', + baseName: 'lastName', + type: 'string', + }, + ]; - static getAttributeTypeMap() { - return ExistingOrder.attributeTypeMap; - } + static getAttributeTypeMap() { + return ExistingOrder.attributeTypeMap; + } } - diff --git a/src/checkout/src/clients/orders/model/models.ts b/src/checkout/src/clients/orders/model/models.ts index bcd2f3174..ba0846077 100644 --- a/src/checkout/src/clients/orders/model/models.ts +++ b/src/checkout/src/clients/orders/model/models.ts @@ -28,206 +28,231 @@ import { OrderItem } from './orderItem'; /* tslint:disable:no-unused-variable */ let primitives = [ - "string", - "boolean", - "double", - "integer", - "long", - "float", - "number", - "any" - ]; - -let enumsMap: {[index: string]: any} = { -} + 'string', + 'boolean', + 'double', + 'integer', + 'long', + 'float', + 'number', + 'any', +]; -let typeMap: {[index: string]: any} = { - "ExistingOrder": ExistingOrder, - "Order": Order, - "OrderItem": OrderItem, -} +let enumsMap: { [index: string]: any } = {}; + +let typeMap: { [index: string]: any } = { + ExistingOrder: ExistingOrder, + Order: Order, + OrderItem: OrderItem, +}; export class ObjectSerializer { - public static findCorrectType(data: any, expectedType: string) { - if (data == undefined) { - return expectedType; - } else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) { - return expectedType; - } else if (expectedType === "Date") { - return expectedType; + public static findCorrectType(data: any, expectedType: string) { + if (data == undefined) { + return expectedType; + } else if (primitives.indexOf(expectedType.toLowerCase()) !== -1) { + return expectedType; + } else if (expectedType === 'Date') { + return expectedType; + } else { + if (enumsMap[expectedType]) { + return expectedType; + } + + if (!typeMap[expectedType]) { + return expectedType; // w/e we don't know the type + } + + // Check the discriminator + let discriminatorProperty = typeMap[expectedType].discriminator; + if (discriminatorProperty == null) { + return expectedType; // the type does not have a discriminator. use it. + } else { + if (data[discriminatorProperty]) { + var discriminatorType = data[discriminatorProperty]; + if (typeMap[discriminatorType]) { + return discriminatorType; // use the type given in the discriminator + } else { + return expectedType; // discriminator did not map to a type + } } else { - if (enumsMap[expectedType]) { - return expectedType; - } - - if (!typeMap[expectedType]) { - return expectedType; // w/e we don't know the type - } - - // Check the discriminator - let discriminatorProperty = typeMap[expectedType].discriminator; - if (discriminatorProperty == null) { - return expectedType; // the type does not have a discriminator. use it. - } else { - if (data[discriminatorProperty]) { - var discriminatorType = data[discriminatorProperty]; - if(typeMap[discriminatorType]){ - return discriminatorType; // use the type given in the discriminator - } else { - return expectedType; // discriminator did not map to a type - } - } else { - return expectedType; // discriminator was not present (or an empty string) - } - } + return expectedType; // discriminator was not present (or an empty string) } + } } + } - public static serialize(data: any, type: string) { - if (data == undefined) { - return data; - } else if (primitives.indexOf(type.toLowerCase()) !== -1) { - return data; - } else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6 - let subType: string = type.replace("Array<", ""); // Array => Type> - subType = subType.substring(0, subType.length - 1); // Type> => Type - let transformedData: any[] = []; - for (let index in data) { - let date = data[index]; - transformedData.push(ObjectSerializer.serialize(date, subType)); - } - return transformedData; - } else if (type === "Date") { - return data.toISOString(); - } else { - if (enumsMap[type]) { - return data; - } - if (!typeMap[type]) { // in case we dont know the type - return data; - } - - // Get the actual type of this object - type = this.findCorrectType(data, type); - - // get the map for the correct type. - let attributeTypes = typeMap[type].getAttributeTypeMap(); - let instance: {[index: string]: any} = {}; - for (let index in attributeTypes) { - let attributeType = attributeTypes[index]; - instance[attributeType.baseName] = ObjectSerializer.serialize(data[attributeType.name], attributeType.type); - } - return instance; - } + public static serialize(data: any, type: string) { + if (data == undefined) { + return data; + } else if (primitives.indexOf(type.toLowerCase()) !== -1) { + return data; + } else if (type.lastIndexOf('Array<', 0) === 0) { + // string.startsWith pre es6 + let subType: string = type.replace('Array<', ''); // Array => Type> + subType = subType.substring(0, subType.length - 1); // Type> => Type + let transformedData: any[] = []; + for (let index in data) { + let date = data[index]; + transformedData.push(ObjectSerializer.serialize(date, subType)); + } + return transformedData; + } else if (type === 'Date') { + return data.toISOString(); + } else { + if (enumsMap[type]) { + return data; + } + if (!typeMap[type]) { + // in case we dont know the type + return data; + } + + // Get the actual type of this object + type = this.findCorrectType(data, type); + + // get the map for the correct type. + let attributeTypes = typeMap[type].getAttributeTypeMap(); + let instance: { [index: string]: any } = {}; + for (let index in attributeTypes) { + let attributeType = attributeTypes[index]; + instance[attributeType.baseName] = ObjectSerializer.serialize( + data[attributeType.name], + attributeType.type, + ); + } + return instance; } + } - public static deserialize(data: any, type: string) { - // polymorphism may change the actual type. - type = ObjectSerializer.findCorrectType(data, type); - if (data == undefined) { - return data; - } else if (primitives.indexOf(type.toLowerCase()) !== -1) { - return data; - } else if (type.lastIndexOf("Array<", 0) === 0) { // string.startsWith pre es6 - let subType: string = type.replace("Array<", ""); // Array => Type> - subType = subType.substring(0, subType.length - 1); // Type> => Type - let transformedData: any[] = []; - for (let index in data) { - let date = data[index]; - transformedData.push(ObjectSerializer.deserialize(date, subType)); - } - return transformedData; - } else if (type === "Date") { - return new Date(data); - } else { - if (enumsMap[type]) {// is Enum - return data; - } - - if (!typeMap[type]) { // dont know the type - return data; - } - let instance = new typeMap[type](); - let attributeTypes = typeMap[type].getAttributeTypeMap(); - for (let index in attributeTypes) { - let attributeType = attributeTypes[index]; - instance[attributeType.name] = ObjectSerializer.deserialize(data[attributeType.baseName], attributeType.type); - } - return instance; - } + public static deserialize(data: any, type: string) { + // polymorphism may change the actual type. + type = ObjectSerializer.findCorrectType(data, type); + if (data == undefined) { + return data; + } else if (primitives.indexOf(type.toLowerCase()) !== -1) { + return data; + } else if (type.lastIndexOf('Array<', 0) === 0) { + // string.startsWith pre es6 + let subType: string = type.replace('Array<', ''); // Array => Type> + subType = subType.substring(0, subType.length - 1); // Type> => Type + let transformedData: any[] = []; + for (let index in data) { + let date = data[index]; + transformedData.push(ObjectSerializer.deserialize(date, subType)); + } + return transformedData; + } else if (type === 'Date') { + return new Date(data); + } else { + if (enumsMap[type]) { + // is Enum + return data; + } + + if (!typeMap[type]) { + // dont know the type + return data; + } + let instance = new typeMap[type](); + let attributeTypes = typeMap[type].getAttributeTypeMap(); + for (let index in attributeTypes) { + let attributeType = attributeTypes[index]; + instance[attributeType.name] = ObjectSerializer.deserialize( + data[attributeType.baseName], + attributeType.type, + ); + } + return instance; } + } } export interface Authentication { - /** - * Apply authentication settings to header and query params. - */ - applyToRequest(requestOptions: localVarRequest.Options): Promise | void; + /** + * Apply authentication settings to header and query params. + */ + applyToRequest(requestOptions: localVarRequest.Options): Promise | void; } export class HttpBasicAuth implements Authentication { - public username: string = ''; - public password: string = ''; + public username: string = ''; + public password: string = ''; - applyToRequest(requestOptions: localVarRequest.Options): void { - requestOptions.auth = { - username: this.username, password: this.password - } - } + applyToRequest(requestOptions: localVarRequest.Options): void { + requestOptions.auth = { + username: this.username, + password: this.password, + }; + } } export class HttpBearerAuth implements Authentication { - public accessToken: string | (() => string) = ''; - - applyToRequest(requestOptions: localVarRequest.Options): void { - if (requestOptions && requestOptions.headers) { - const accessToken = typeof this.accessToken === 'function' - ? this.accessToken() - : this.accessToken; - requestOptions.headers["Authorization"] = "Bearer " + accessToken; - } + public accessToken: string | (() => string) = ''; + + applyToRequest(requestOptions: localVarRequest.Options): void { + if (requestOptions && requestOptions.headers) { + const accessToken = + typeof this.accessToken === 'function' + ? this.accessToken() + : this.accessToken; + requestOptions.headers['Authorization'] = 'Bearer ' + accessToken; } + } } export class ApiKeyAuth implements Authentication { - public apiKey: string = ''; + public apiKey: string = ''; - constructor(private location: string, private paramName: string) { - } + constructor( + private location: string, + private paramName: string, + ) {} - applyToRequest(requestOptions: localVarRequest.Options): void { - if (this.location == "query") { - (requestOptions.qs)[this.paramName] = this.apiKey; - } else if (this.location == "header" && requestOptions && requestOptions.headers) { - requestOptions.headers[this.paramName] = this.apiKey; - } else if (this.location == 'cookie' && requestOptions && requestOptions.headers) { - if (requestOptions.headers['Cookie']) { - requestOptions.headers['Cookie'] += '; ' + this.paramName + '=' + encodeURIComponent(this.apiKey); - } - else { - requestOptions.headers['Cookie'] = this.paramName + '=' + encodeURIComponent(this.apiKey); - } - } + applyToRequest(requestOptions: localVarRequest.Options): void { + if (this.location == 'query') { + (requestOptions.qs)[this.paramName] = this.apiKey; + } else if ( + this.location == 'header' && + requestOptions && + requestOptions.headers + ) { + requestOptions.headers[this.paramName] = this.apiKey; + } else if ( + this.location == 'cookie' && + requestOptions && + requestOptions.headers + ) { + if (requestOptions.headers['Cookie']) { + requestOptions.headers['Cookie'] += + '; ' + this.paramName + '=' + encodeURIComponent(this.apiKey); + } else { + requestOptions.headers['Cookie'] = + this.paramName + '=' + encodeURIComponent(this.apiKey); + } } + } } export class OAuth implements Authentication { - public accessToken: string = ''; + public accessToken: string = ''; - applyToRequest(requestOptions: localVarRequest.Options): void { - if (requestOptions && requestOptions.headers) { - requestOptions.headers["Authorization"] = "Bearer " + this.accessToken; - } + applyToRequest(requestOptions: localVarRequest.Options): void { + if (requestOptions && requestOptions.headers) { + requestOptions.headers['Authorization'] = 'Bearer ' + this.accessToken; } + } } export class VoidAuth implements Authentication { - public username: string = ''; - public password: string = ''; + public username: string = ''; + public password: string = ''; - applyToRequest(_: localVarRequest.Options): void { - // Do nothing - } + applyToRequest(_: localVarRequest.Options): void { + // Do nothing + } } -export type Interceptor = (requestOptions: localVarRequest.Options) => (Promise | void); +export type Interceptor = ( + requestOptions: localVarRequest.Options, +) => Promise | void; diff --git a/src/checkout/src/clients/orders/model/order.ts b/src/checkout/src/clients/orders/model/order.ts index 43c3ec3c3..5610a9e28 100644 --- a/src/checkout/src/clients/orders/model/order.ts +++ b/src/checkout/src/clients/orders/model/order.ts @@ -32,37 +32,41 @@ import { RequestFile } from '../api'; import { OrderItem } from './orderItem'; export class Order { - 'email'?: string; - 'firstName'?: string; - 'items'?: Array; - 'lastName'?: string; + 'email'?: string; + 'firstName'?: string; + 'items'?: Array; + 'lastName'?: string; - static discriminator: string | undefined = undefined; + static discriminator: string | undefined = undefined; - static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ - { - "name": "email", - "baseName": "email", - "type": "string" - }, - { - "name": "firstName", - "baseName": "firstName", - "type": "string" - }, - { - "name": "items", - "baseName": "items", - "type": "Array" - }, - { - "name": "lastName", - "baseName": "lastName", - "type": "string" - } ]; + static attributeTypeMap: Array<{ + name: string; + baseName: string; + type: string; + }> = [ + { + name: 'email', + baseName: 'email', + type: 'string', + }, + { + name: 'firstName', + baseName: 'firstName', + type: 'string', + }, + { + name: 'items', + baseName: 'items', + type: 'Array', + }, + { + name: 'lastName', + baseName: 'lastName', + type: 'string', + }, + ]; - static getAttributeTypeMap() { - return Order.attributeTypeMap; - } + static getAttributeTypeMap() { + return Order.attributeTypeMap; + } } - diff --git a/src/checkout/src/clients/orders/model/orderItem.ts b/src/checkout/src/clients/orders/model/orderItem.ts index 16fbad9d6..4e7421c22 100644 --- a/src/checkout/src/clients/orders/model/orderItem.ts +++ b/src/checkout/src/clients/orders/model/orderItem.ts @@ -31,42 +31,46 @@ import { RequestFile } from '../api'; export class OrderItem { - 'price'?: number; - 'productId'?: string; - 'quantity'?: number; - 'totalCost'?: number; - 'name'?: string; - static discriminator: string | undefined = undefined; + 'price'?: number; + 'productId'?: string; + 'quantity'?: number; + 'totalCost'?: number; + 'name'?: string; + static discriminator: string | undefined = undefined; - static attributeTypeMap: Array<{name: string, baseName: string, type: string}> = [ - { - "name": "unitCost", - "baseName": "price", - "type": "number" - }, - { - "name": "id", - "baseName": "productId", - "type": "string" - }, - { - "name": "name", - "baseName": "name", - "type": "string" - }, - { - "name": "totalCost", - "baseName": "totalCost", - "type": "number" - }, - { - "name": "quantity", - "baseName": "quantity", - "type": "number" - } ]; + static attributeTypeMap: Array<{ + name: string; + baseName: string; + type: string; + }> = [ + { + name: 'unitCost', + baseName: 'price', + type: 'number', + }, + { + name: 'id', + baseName: 'productId', + type: 'string', + }, + { + name: 'name', + baseName: 'name', + type: 'string', + }, + { + name: 'totalCost', + baseName: 'totalCost', + type: 'number', + }, + { + name: 'quantity', + baseName: 'quantity', + type: 'number', + }, + ]; - static getAttributeTypeMap() { - return OrderItem.attributeTypeMap; - } + static getAttributeTypeMap() { + return OrderItem.attributeTypeMap; + } } - diff --git a/src/checkout/src/config/configuration.ts b/src/checkout/src/config/configuration.ts index b727ef491..28ad35024 100644 --- a/src/checkout/src/config/configuration.ts +++ b/src/checkout/src/config/configuration.ts @@ -18,15 +18,15 @@ export default () => ({ endpoints: { - orders: process.env.ENDPOINTS_ORDERS || '' + orders: process.env.ENDPOINTS_ORDERS || '', }, redis: { url: process.env.REDIS_URL || '', reader: { url: process.env.REDIS_READER_URL || '', - } + }, }, shipping: { - prefix: process.env.SHIPPING_NAME_PREFIX || '' - } -}); \ No newline at end of file + prefix: process.env.SHIPPING_NAME_PREFIX || '', + }, +}); diff --git a/src/checkout/src/main.ts b/src/checkout/src/main.ts index 64a8d451e..bbe6ace63 100644 --- a/src/checkout/src/main.ts +++ b/src/checkout/src/main.ts @@ -25,7 +25,7 @@ import { AppModule } from './app.module'; async function bootstrap() { // Start SDK before nestjs factory create await otelSDK.start(); - + const app = await NestFactory.create(AppModule); app.useGlobalPipes(new ValidationPipe()); @@ -41,7 +41,7 @@ async function bootstrap() { // Starts listening for shutdown hooks app.enableShutdownHooks(); - const port = process.env.PORT || 8080 + const port = process.env.PORT || 8080; await app.listen(port); } diff --git a/src/checkout/src/middleware/logger.middleware.ts b/src/checkout/src/middleware/logger.middleware.ts index 88252df5b..e30170e3d 100644 --- a/src/checkout/src/middleware/logger.middleware.ts +++ b/src/checkout/src/middleware/logger.middleware.ts @@ -39,4 +39,4 @@ export class LoggerMiddleware implements NestMiddleware { next(); } -} \ No newline at end of file +} diff --git a/src/checkout/src/tracing.ts b/src/checkout/src/tracing.ts index 1ad56de37..ce61fe992 100644 --- a/src/checkout/src/tracing.ts +++ b/src/checkout/src/tracing.ts @@ -1,6 +1,4 @@ -import { - CompositePropagator, -} from '@opentelemetry/core'; +import { CompositePropagator } from '@opentelemetry/core'; import { SimpleSpanProcessor } from '@opentelemetry/sdk-trace-base'; import { getNodeAutoInstrumentations } from '@opentelemetry/auto-instrumentations-node'; import { B3InjectEncoding, B3Propagator } from '@opentelemetry/propagator-b3'; @@ -14,14 +12,9 @@ import { AWSXRayIdGenerator } from '@opentelemetry/id-generator-aws-xray'; const otelSDK = new NodeSDK({ traceExporter: new OTLPTraceExporter(), - spanProcessor: new SimpleSpanProcessor( - new OTLPTraceExporter() - ), + spanProcessor: new SimpleSpanProcessor(new OTLPTraceExporter()), contextManager: new AsyncLocalStorageContextManager(), - resourceDetectors: [ - envDetector, - awsEc2Detector, - ], + resourceDetectors: [envDetector, awsEc2Detector], instrumentations: [getNodeAutoInstrumentations()], idGenerator: new AWSXRayIdGenerator(), }); @@ -35,7 +28,7 @@ process.on('SIGTERM', () => { .shutdown() .then( () => console.log('SDK shut down successfully'), - err => console.log('Error shutting down SDK', err) + (err) => console.log('Error shutting down SDK', err), ) .finally(() => process.exit(0)); -}); \ No newline at end of file +}); diff --git a/src/checkout/test/app.e2e-spec.ts b/src/checkout/test/app.e2e-spec.ts index 8ed69d4a7..568fad7ec 100644 --- a/src/checkout/test/app.e2e-spec.ts +++ b/src/checkout/test/app.e2e-spec.ts @@ -34,15 +34,11 @@ describe('AppController (e2e)', () => { }); it('/health (GET)', () => { - return request(app.getHttpServer()) - .get('/health') - .expect(200); + return request(app.getHttpServer()).get('/health').expect(200); }); it('/checkout/test123 (GET)', () => { - return request(app.getHttpServer()) - .get('/checkout/test123') - .expect(404); + return request(app.getHttpServer()).get('/checkout/test123').expect(404); }); it('/checkout/test124 (POST)', () => { @@ -56,31 +52,31 @@ describe('AppController (e2e)', () => { const valid = { customerEmail: 'asdasd@asdasd.com', items: [ - { - id: 'a1', - name: 'A1', - quantity: 1, - unitCost: 123, - totalCost: 123, - imageUrl: "localhost:8080/image.jpg" - }, - { - id: 'b1', - name: 'B1', - quantity: 1, - unitCost: 123, - totalCost: 123, - imageUrl: "localhost:8080/image.jpg" - } + { + id: 'a1', + name: 'A1', + quantity: 1, + unitCost: 123, + totalCost: 123, + imageUrl: 'localhost:8080/image.jpg', + }, + { + id: 'b1', + name: 'B1', + quantity: 1, + unitCost: 123, + totalCost: 123, + imageUrl: 'localhost:8080/image.jpg', + }, ], shippingAddress: { - 'firstName': 'John', - 'lastName': 'Doe', - 'address1': '999 Main St.', - 'address2': '#123', - 'city': 'Sometown', - 'state': 'AB', - 'zip': '12345' + firstName: 'John', + lastName: 'Doe', + address1: '999 Main St.', + address2: '#123', + city: 'Sometown', + state: 'AB', + zip: '12345', }, - subtotal: 492 -}; \ No newline at end of file + subtotal: 492, +}; diff --git a/src/e2e/README.md b/src/e2e/README.md index e1ba59fa3..f5ac9ef43 100644 --- a/src/e2e/README.md +++ b/src/e2e/README.md @@ -27,6 +27,7 @@ To run against Docker Compose running locally: ### NPM The tests can be run locally using NPM. To do so the following components must be installed: + - NodeJS >= 16 & NPM - Chrome web browser @@ -36,4 +37,4 @@ npm install ENDPOINT='http://endpoint:8080' npm test ``` -Where the `ENDPOINT` environment variable should be adjusted to point at the endpoint of the UI service. \ No newline at end of file +Where the `ENDPOINT` environment variable should be adjusted to point at the endpoint of the UI service. diff --git a/src/e2e/cart.spec.js b/src/e2e/cart.spec.js index 26b6a60f1..fc878c950 100644 --- a/src/e2e/cart.spec.js +++ b/src/e2e/cart.spec.js @@ -17,61 +17,59 @@ */ browser.waitForAngularEnabled(false); -var baseUrl = browser.params.baseUrl +var baseUrl = browser.params.baseUrl; -let Cart = require('./pages/Cart'); -let CartItem = require('./pages/CartItem') -let Product = require('./pages/Product'); +let Cart = require("./pages/Cart"); +let CartItem = require("./pages/CartItem"); +let Product = require("./pages/Product"); var cart = new Cart(baseUrl); -var product = new Product(baseUrl, '510a0d7e-8e83-4193-b483-e27e09ddc34d'); +var product = new Product(baseUrl, "510a0d7e-8e83-4193-b483-e27e09ddc34d"); -describe('when on cart', function() { - beforeAll(function() { +describe("when on cart", function () { + beforeAll(function () { browser.manage().deleteAllCookies(); cart.go(); }); - it('should have title', function() { - expect(cart.getTitle()).toEqual('Retail Store Sample App'); + it("should have title", function () { + expect(cart.getTitle()).toEqual("Retail Store Sample App"); }); - it('should have breadcrumb', function() { - expect(cart.getBreadcrumb().getText()) - .toEqual('Cart'); + it("should have breadcrumb", function () { + expect(cart.getBreadcrumb().getText()).toEqual("Cart"); }); - it('should be empty', function() { + it("should be empty", function () { expect(cart.getItems().count()).toEqual(0); }); - describe('and add item', function() { - beforeAll(function() { + describe("and add item", function () { + beforeAll(function () { browser.manage().deleteAllCookies(); product.go(); product.addToCart(); }); - it('should show cart', function() { - expect(browser.getCurrentUrl()) - .toBe(cart.getUrl()); + it("should show cart", function () { + expect(browser.getCurrentUrl()).toBe(cart.getUrl()); }); - it('should show the item', function() { + it("should show the item", function () { expect(cart.getItems().count()).toEqual(1); let item = new CartItem(cart.getItems().get(0)); - expect(item.getName()).toEqual('Gentleman'); - expect(item.getPrice()).toEqual('$ 795'); + expect(item.getName()).toEqual("Gentleman"); + expect(item.getPrice()).toEqual("$ 795"); }); }); - describe('and remove item', function() { - beforeAll(function() { + describe("and remove item", function () { + beforeAll(function () { browser.manage().deleteAllCookies(); - + product.go(); product.addToCart(); @@ -80,13 +78,12 @@ describe('when on cart', function() { item.remove(); }); - it('should show cart', function() { - expect(browser.getCurrentUrl()) - .toBe(cart.getUrl()); + it("should show cart", function () { + expect(browser.getCurrentUrl()).toBe(cart.getUrl()); }); - it('should be empty', function() { + it("should be empty", function () { expect(cart.getItems().count()).toEqual(0); }); }); -}); \ No newline at end of file +}); diff --git a/src/e2e/catalog.spec.js b/src/e2e/catalog.spec.js index 79a0c3a26..4c2c5ffd6 100644 --- a/src/e2e/catalog.spec.js +++ b/src/e2e/catalog.spec.js @@ -17,89 +17,82 @@ */ browser.waitForAngularEnabled(false); -var baseUrl = browser.params.baseUrl +var baseUrl = browser.params.baseUrl; -let Catalog = require('./pages/Catalog'); -let Product = require('./pages/Product'); +let Catalog = require("./pages/Catalog"); +let Product = require("./pages/Product"); var catalog = new Catalog(baseUrl); -var product = new Product(baseUrl, '510a0d7e-8e83-4193-b483-e27e09ddc34d'); +var product = new Product(baseUrl, "510a0d7e-8e83-4193-b483-e27e09ddc34d"); -describe('when on catalog', function() { - beforeAll(function() { +describe("when on catalog", function () { + beforeAll(function () { catalog.go(); }); - it('should have title', function() { - expect(catalog.getTitle()).toEqual('Retail Store Sample App'); + it("should have title", function () { + expect(catalog.getTitle()).toEqual("Retail Store Sample App"); }); - it('should have breadcrumb', function() { - expect(catalog.getBreadcrumb().getText()) - .toEqual('Catalog'); + it("should have breadcrumb", function () { + expect(catalog.getBreadcrumb().getText()).toEqual("Catalog"); }); - it('should show products', function() { - expect(catalog.getProducts().count()) - .toEqual(3); + it("should show products", function () { + expect(catalog.getProducts().count()).toEqual(3); }); - describe('and select page', function() { - beforeEach(function() { + describe("and select page", function () { + beforeEach(function () { catalog.go(); - catalog.page('2'); + catalog.page("2"); }); - it('should show page', function() { - expect(catalog.getProducts().count()) - .toEqual(3); + it("should show page", function () { + expect(catalog.getProducts().count()).toEqual(3); }); }); - describe('and select page size', function() { - beforeEach(function() { + describe("and select page size", function () { + beforeEach(function () { catalog.go(); - catalog.size('9'); + catalog.size("9"); }); - it('should show products', function() { - expect(catalog.getProducts().count()) - .toEqual(6); + it("should show products", function () { + expect(catalog.getProducts().count()).toEqual(6); }); - describe('and select tag', function() { - beforeEach(function() { - catalog.tag('Dress'); + describe("and select tag", function () { + beforeEach(function () { + catalog.tag("Dress"); }); - - it('should filter products', function() { - expect(catalog.getProducts().count()) - .toEqual(5); + + it("should filter products", function () { + expect(catalog.getProducts().count()).toEqual(5); }); }); }); - describe('and select tag', function() { - beforeEach(function() { + describe("and select tag", function () { + beforeEach(function () { catalog.go(); - catalog.tag('Luxury'); + catalog.tag("Luxury"); }); - it('should filter products', function() { - expect(catalog.getProducts().count()) - .toEqual(1); + it("should filter products", function () { + expect(catalog.getProducts().count()).toEqual(1); }); }); - describe('and select item', function() { - beforeEach(async function() { + describe("and select item", function () { + beforeEach(async function () { catalog.go(); catalog.product(0); }); - it('should show product page', function() { - expect(browser.getCurrentUrl()) - .toBe(product.getUrl()); + it("should show product page", function () { + expect(browser.getCurrentUrl()).toBe(product.getUrl()); }); }); -}); \ No newline at end of file +}); diff --git a/src/e2e/checkout.spec.js b/src/e2e/checkout.spec.js index 1f76ab1b7..fc5c12f2f 100644 --- a/src/e2e/checkout.spec.js +++ b/src/e2e/checkout.spec.js @@ -17,26 +17,25 @@ */ browser.waitForAngularEnabled(false); -var baseUrl = browser.params.baseUrl +var baseUrl = browser.params.baseUrl; -let CheckoutAddress = require('./pages/CheckoutAddress'); -let CheckoutDelivery = require('./pages/CheckoutDelivery'); -let CheckoutPayment = require('./pages/CheckoutPayment'); -let CheckoutReview = require('./pages/CheckoutReview'); -let CheckoutSuccess = require('./pages/CheckoutSuccess'); -let Product = require('./pages/Product'); +let CheckoutAddress = require("./pages/CheckoutAddress"); +let CheckoutDelivery = require("./pages/CheckoutDelivery"); +let CheckoutPayment = require("./pages/CheckoutPayment"); +let CheckoutReview = require("./pages/CheckoutReview"); +let CheckoutSuccess = require("./pages/CheckoutSuccess"); +let Product = require("./pages/Product"); var checkoutAddress = new CheckoutAddress(baseUrl); var checkoutDelivery = new CheckoutDelivery(baseUrl); var checkoutPayment = new CheckoutPayment(baseUrl); var checkoutReview = new CheckoutReview(baseUrl); var checkoutSuccess = new CheckoutSuccess(baseUrl); -var product = new Product(baseUrl, '510a0d7e-8e83-4193-b483-e27e09ddc34d'); +var product = new Product(baseUrl, "510a0d7e-8e83-4193-b483-e27e09ddc34d"); -describe('when on checkout', function() { - - describe('with product in cart', function() { - beforeAll(function() { +describe("when on checkout", function () { + describe("with product in cart", function () { + beforeAll(function () { browser.manage().deleteAllCookies(); product.go(); @@ -45,25 +44,32 @@ describe('when on checkout', function() { checkoutAddress.go(); }); - it('should show checkout', function() { - expect(browser.getCurrentUrl()) - .toBe(checkoutAddress.getUrl()); + it("should show checkout", function () { + expect(browser.getCurrentUrl()).toBe(checkoutAddress.getUrl()); }); - it('should process checkout address', async() => { - await checkoutAddress.populate('John', 'Doe', 'jdoe@example.com', '123 Main Street', 'Santa Barbara', 'California', '95133'); + it("should process checkout address", async () => { + await checkoutAddress.populate( + "John", + "Doe", + "jdoe@example.com", + "123 Main Street", + "Santa Barbara", + "California", + "95133", + ); await checkoutAddress.next(); - await checkoutDelivery.populate('token1'); + await checkoutDelivery.populate("token1"); await checkoutDelivery.next(); - await checkoutPayment.populate('John Doe', '1234567890', '12/20', '123'); + await checkoutPayment.populate("John Doe", "1234567890", "12/20", "123"); await checkoutPayment.next(); await checkoutReview.next(); }); }); -}); \ No newline at end of file +}); diff --git a/src/e2e/conf.js b/src/e2e/conf.js index 38fbef5d3..3ab4e5cf0 100644 --- a/src/e2e/conf.js +++ b/src/e2e/conf.js @@ -16,43 +16,50 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -var { SpecReporter } = require('jasmine-spec-reporter'); +var { SpecReporter } = require("jasmine-spec-reporter"); exports.config = { - framework: 'jasmine', - specs: ['*.spec.js'], + framework: "jasmine", + specs: ["*.spec.js"], params: { - baseUrl: process.env.ENDPOINT || 'http://localhost' + baseUrl: process.env.ENDPOINT || "http://localhost", }, capabilities: { - browserName: 'chrome', + browserName: "chrome", chromeOptions: { - args: ['--headless', '--disable-gpu', '--window-size=1024,768', '--no-sandbox'] // Need minimum windows size or the responsive layout breaks navigation assumptions - } + args: [ + "--headless", + "--disable-gpu", + "--window-size=1024,768", + "--no-sandbox", + ], // Need minimum windows size or the responsive layout breaks navigation assumptions + }, }, directConnect: true, onPrepare: function () { - jasmine.getEnv().addReporter(new SpecReporter({ - displayStacktrace: 'all', // display stacktrace for each failed assertion, values: (all|specs|summary|none) - displaySuccessesSummary: false, // display summary of all successes after execution - displayFailuresSummary: true, // display summary of all failures after execution - displayPendingSummary: true, // display summary of all pending specs after execution - displaySuccessfulSpec: true, // display each successful spec - displayFailedSpec: true, // display each failed spec - displayPendingSpec: false, // display each pending spec - displaySpecDuration: false, // display each spec duration - displaySuiteNumber: false, // display each suite number (hierarchical) - colors: { - success: 'green', - failure: 'red', - pending: 'yellow' - }, - prefixes: { - success: 'โœ“ ', - failure: 'โœ— ', - pending: '* ' - }, - customProcessors: [] - })); - } -} \ No newline at end of file + jasmine.getEnv().addReporter( + new SpecReporter({ + displayStacktrace: "all", // display stacktrace for each failed assertion, values: (all|specs|summary|none) + displaySuccessesSummary: false, // display summary of all successes after execution + displayFailuresSummary: true, // display summary of all failures after execution + displayPendingSummary: true, // display summary of all pending specs after execution + displaySuccessfulSpec: true, // display each successful spec + displayFailedSpec: true, // display each failed spec + displayPendingSpec: false, // display each pending spec + displaySpecDuration: false, // display each spec duration + displaySuiteNumber: false, // display each suite number (hierarchical) + colors: { + success: "green", + failure: "red", + pending: "yellow", + }, + prefixes: { + success: "โœ“ ", + failure: "โœ— ", + pending: "* ", + }, + customProcessors: [], + }), + ); + }, +}; diff --git a/src/e2e/homepage.spec.js b/src/e2e/homepage.spec.js index fbd74f59b..2dcb4966c 100644 --- a/src/e2e/homepage.spec.js +++ b/src/e2e/homepage.spec.js @@ -17,55 +17,52 @@ */ browser.waitForAngularEnabled(false); -var baseUrl = browser.params.baseUrl +var baseUrl = browser.params.baseUrl; -let Homepage = require('./pages/Homepage'); -let Catalog = require('./pages/Catalog'); -let Cart = require('./pages/Cart'); +let Homepage = require("./pages/Homepage"); +let Catalog = require("./pages/Catalog"); +let Cart = require("./pages/Cart"); var homepage = new Homepage(baseUrl); var catalog = new Catalog(baseUrl); var cart = new Cart(baseUrl); -describe('when on homepage', function() { - beforeAll(function() { +describe("when on homepage", function () { + beforeAll(function () { homepage.go(); }); - it('should have a title', function() { - expect(homepage.getTitle()).toEqual('Retail Store Sample App'); + it("should have a title", function () { + expect(homepage.getTitle()).toEqual("Retail Store Sample App"); }); - describe('and open Home', function() { - beforeAll(function() { + describe("and open Home", function () { + beforeAll(function () { homepage.home(); }); - it('should open the home page', function() { - expect(browser.getCurrentUrl()) - .toBe(homepage.getUrl()); + it("should open the home page", function () { + expect(browser.getCurrentUrl()).toBe(homepage.getUrl()); }); }); - describe('and open Catalog', function() { - beforeAll(function() { + describe("and open Catalog", function () { + beforeAll(function () { homepage.catalog(); }); - it('should open the catalog page', function() { - expect(browser.getCurrentUrl()) - .toBe(catalog.getUrl()); + it("should open the catalog page", function () { + expect(browser.getCurrentUrl()).toBe(catalog.getUrl()); }); }); - describe('and open Cart', function() { - beforeAll(function() { + describe("and open Cart", function () { + beforeAll(function () { homepage.cart(); }); - it('should open the cart page', function() { - expect(browser.getCurrentUrl()) - .toBe(cart.getUrl()); + it("should open the cart page", function () { + expect(browser.getCurrentUrl()).toBe(cart.getUrl()); }); }); -}); \ No newline at end of file +}); diff --git a/src/e2e/package.json b/src/e2e/package.json index 01a72e6c8..df11707b4 100644 --- a/src/e2e/package.json +++ b/src/e2e/package.json @@ -17,4 +17,4 @@ "dependencies": { "jasmine-spec-reporter": "^7.0.0" } -} \ No newline at end of file +} diff --git a/src/e2e/pages/Cart.js b/src/e2e/pages/Cart.js index 753f8738d..b892fe862 100644 --- a/src/e2e/pages/Cart.js +++ b/src/e2e/pages/Cart.js @@ -16,20 +16,19 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -let Page = require('./Page'); +let Page = require("./Page"); class Cart extends Page { - constructor(baseUrl) { super(baseUrl); } getPath() { - return '/cart'; + return "/cart"; } getItems() { - return element(by.id('basket')).all(by.css('.cart-item')); + return element(by.id("basket")).all(by.css(".cart-item")); } } -module.exports = Cart; \ No newline at end of file +module.exports = Cart; diff --git a/src/e2e/pages/CartItem.js b/src/e2e/pages/CartItem.js index f31f11d6c..986630885 100644 --- a/src/e2e/pages/CartItem.js +++ b/src/e2e/pages/CartItem.js @@ -17,25 +17,24 @@ */ class CartItem { - constructor(element) { this.element = element; } getName() { - return this.element.element(by.css('.item-name')).getText(); + return this.element.element(by.css(".item-name")).getText(); } getPrice() { - return this.element.element(by.css('.item-price')).getText(); + return this.element.element(by.css(".item-price")).getText(); } getQuantity() { - return this.element.element(by.css('.item-quantity')).getText(); + return this.element.element(by.css(".item-quantity")).getText(); } async remove() { - await this.element.element(by.css('.remove-item')).click() + await this.element.element(by.css(".remove-item")).click(); } } -module.exports = CartItem; \ No newline at end of file +module.exports = CartItem; diff --git a/src/e2e/pages/Catalog.js b/src/e2e/pages/Catalog.js index efe576407..8bc91069a 100644 --- a/src/e2e/pages/Catalog.js +++ b/src/e2e/pages/Catalog.js @@ -16,36 +16,38 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -let Page = require('./Page'); +let Page = require("./Page"); class Catalog extends Page { - constructor(baseUrl) { super(baseUrl); } getPath() { - return '/catalog'; + return "/catalog"; } tag(name) { - element(by.css('.category-menu')).element(by.linkText(name)).click(); - }; + element(by.css(".category-menu")).element(by.linkText(name)).click(); + } size(number) { - element(by.css('.products-number')).element(by.linkText(number)).click(); - }; + element(by.css(".products-number")).element(by.linkText(number)).click(); + } page(number) { - element(by.css('.pagination')).element(by.linkText(number)).click(); + element(by.css(".pagination")).element(by.linkText(number)).click(); } getProducts() { - return element(by.css('.products')).all(by.css('.product')); + return element(by.css(".products")).all(by.css(".product")); } async product(index) { - return await this.getProducts().get(index).element(by.css('.product-link')).click() + return await this.getProducts() + .get(index) + .element(by.css(".product-link")) + .click(); } } -module.exports = Catalog; \ No newline at end of file +module.exports = Catalog; diff --git a/src/e2e/pages/Checkout.js b/src/e2e/pages/Checkout.js index e2580d7c4..f0fb3c80a 100644 --- a/src/e2e/pages/Checkout.js +++ b/src/e2e/pages/Checkout.js @@ -16,16 +16,15 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -let Page = require('./Page'); +let Page = require("./Page"); class Checkout extends Page { - constructor(baseUrl) { super(baseUrl); } getPath() { - return '/checkout'; + return "/checkout"; } async populateField(name, value) { @@ -35,7 +34,7 @@ class Checkout extends Page { } async next() { - return await element(by.id('checkoutForm')).submit(); - }; + return await element(by.id("checkoutForm")).submit(); + } } -module.exports = Checkout; \ No newline at end of file +module.exports = Checkout; diff --git a/src/e2e/pages/CheckoutAddress.js b/src/e2e/pages/CheckoutAddress.js index db80be057..82d3d16b4 100644 --- a/src/e2e/pages/CheckoutAddress.js +++ b/src/e2e/pages/CheckoutAddress.js @@ -16,23 +16,22 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -let Checkout = require('./Checkout'); +let Checkout = require("./Checkout"); class CheckoutAddress extends Checkout { - constructor(baseUrl) { super(baseUrl); } async populate(firstName, lastName, email, address, city, state, zip) { - this.populateField('firstName', firstName); - this.populateField('lastName', lastName); - this.populateField('email', email); - this.populateField('address1', address); - this.populateField('city', city); - this.populateField('zip', zip); + this.populateField("firstName", firstName); + this.populateField("lastName", lastName); + this.populateField("email", email); + this.populateField("address1", address); + this.populateField("city", city); + this.populateField("zip", zip); - return element(by.cssContainingText('option', state)).click(); + return element(by.cssContainingText("option", state)).click(); } } -module.exports = CheckoutAddress; \ No newline at end of file +module.exports = CheckoutAddress; diff --git a/src/e2e/pages/CheckoutDelivery.js b/src/e2e/pages/CheckoutDelivery.js index 265f29268..06a483c5a 100644 --- a/src/e2e/pages/CheckoutDelivery.js +++ b/src/e2e/pages/CheckoutDelivery.js @@ -16,16 +16,15 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -let Checkout = require('./Checkout'); +let Checkout = require("./Checkout"); class CheckoutDelivery extends Checkout { - constructor(baseUrl) { super(baseUrl); } async populate(shippingToken) { - return element(by.css('.item-selector')).click(); + return element(by.css(".item-selector")).click(); } } -module.exports = CheckoutDelivery; \ No newline at end of file +module.exports = CheckoutDelivery; diff --git a/src/e2e/pages/CheckoutPayment.js b/src/e2e/pages/CheckoutPayment.js index 0ef3c9211..426716cce 100644 --- a/src/e2e/pages/CheckoutPayment.js +++ b/src/e2e/pages/CheckoutPayment.js @@ -16,19 +16,18 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -let Checkout = require('./Checkout'); +let Checkout = require("./Checkout"); class CheckoutPayment extends Checkout { - constructor(baseUrl) { super(baseUrl); } async populate(name, number, expiration, cvv) { - this.populateField('cc-name', name); - this.populateField('cc-number', number); - this.populateField('cc-expiration', expiration); - return this.populateField('cc-cvv', cvv); + this.populateField("cc-name", name); + this.populateField("cc-number", number); + this.populateField("cc-expiration", expiration); + return this.populateField("cc-cvv", cvv); } } -module.exports = CheckoutPayment; \ No newline at end of file +module.exports = CheckoutPayment; diff --git a/src/e2e/pages/CheckoutReview.js b/src/e2e/pages/CheckoutReview.js index 53c0c6419..f1889570f 100644 --- a/src/e2e/pages/CheckoutReview.js +++ b/src/e2e/pages/CheckoutReview.js @@ -16,12 +16,11 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -let Checkout = require('./Checkout'); +let Checkout = require("./Checkout"); class CheckoutReview extends Checkout { - constructor(baseUrl) { super(baseUrl); } } -module.exports = CheckoutReview; \ No newline at end of file +module.exports = CheckoutReview; diff --git a/src/e2e/pages/CheckoutSuccess.js b/src/e2e/pages/CheckoutSuccess.js index 6674479ac..38623ad77 100644 --- a/src/e2e/pages/CheckoutSuccess.js +++ b/src/e2e/pages/CheckoutSuccess.js @@ -16,12 +16,11 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -let Page = require('./Page'); +let Page = require("./Page"); class CheckoutSuccess extends Page { - constructor(baseUrl) { super(baseUrl); } } -module.exports = CheckoutSuccess; \ No newline at end of file +module.exports = CheckoutSuccess; diff --git a/src/e2e/pages/Homepage.js b/src/e2e/pages/Homepage.js index 026e53eca..aec9d17f8 100644 --- a/src/e2e/pages/Homepage.js +++ b/src/e2e/pages/Homepage.js @@ -16,16 +16,15 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -let Page = require('./Page'); +let Page = require("./Page"); class Homepage extends Page { - constructor(baseUrl) { super(baseUrl); } getPath() { - return '/home'; + return "/home"; } } -module.exports = Homepage; \ No newline at end of file +module.exports = Homepage; diff --git a/src/e2e/pages/Page.js b/src/e2e/pages/Page.js index bac045bad..8de314859 100644 --- a/src/e2e/pages/Page.js +++ b/src/e2e/pages/Page.js @@ -24,31 +24,31 @@ class Page { } async home() { - await element(by.id('menu-home')).click(); - }; + await element(by.id("menu-home")).click(); + } async catalog() { - await element(by.id('menu-catalog')).click(); - }; + await element(by.id("menu-catalog")).click(); + } async cart() { - await element(by.id('go-cart')).click(); - }; + await element(by.id("go-cart")).click(); + } async get(path) { return await browser.get(path); - }; + } async go() { return await this.get(this.getUrl()); - }; + } getTitle() { return browser.getTitle(); - }; + } getBreadcrumb() { - return element(by.css('.breadcrumb-item.active')) + return element(by.css(".breadcrumb-item.active")); } getPath() { @@ -56,7 +56,7 @@ class Page { } getUrl() { - return this.baseUrl+this.getPath(); + return this.baseUrl + this.getPath(); } } -module.exports = Page; \ No newline at end of file +module.exports = Page; diff --git a/src/e2e/pages/Product.js b/src/e2e/pages/Product.js index 05c5d678d..c387424e1 100644 --- a/src/e2e/pages/Product.js +++ b/src/e2e/pages/Product.js @@ -16,10 +16,9 @@ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -let Page = require('./Page'); +let Page = require("./Page"); class Product extends Page { - constructor(baseUrl, id) { super(baseUrl); @@ -27,23 +26,23 @@ class Product extends Page { } getPath() { - return '/catalog/'+this.id; + return "/catalog/" + this.id; } getRecommendations() { - return element(by.css('.recommendations')).all(by.css('.product')); + return element(by.css(".recommendations")).all(by.css(".product")); } getName() { - return element(by.id('productMain')).element(by.css('h1')); + return element(by.id("productMain")).element(by.css("h1")); } getPrice() { - return element(by.id('productMain')).element(by.css('.price')); + return element(by.id("productMain")).element(by.css(".price")); } async addToCart() { - await element(by.id('add-to-cart')).click(); - }; + await element(by.id("add-to-cart")).click(); + } } -module.exports = Product; \ No newline at end of file +module.exports = Product; diff --git a/src/e2e/product.spec.js b/src/e2e/product.spec.js index 846960ed0..868b89327 100644 --- a/src/e2e/product.spec.js +++ b/src/e2e/product.spec.js @@ -17,49 +17,45 @@ */ browser.waitForAngularEnabled(false); -var baseUrl = browser.params.baseUrl +var baseUrl = browser.params.baseUrl; let EC = protractor.ExpectedConditions; -let Product = require('./pages/Product'); -let Cart = require('./pages/Cart'); +let Product = require("./pages/Product"); +let Cart = require("./pages/Cart"); -var product = new Product(baseUrl, '510a0d7e-8e83-4193-b483-e27e09ddc34d'); +var product = new Product(baseUrl, "510a0d7e-8e83-4193-b483-e27e09ddc34d"); var cart = new Cart(baseUrl); -describe('when on product', function() { - beforeAll(function() { +describe("when on product", function () { + beforeAll(function () { product.go(); }); - it('should have title', function() { - expect(product.getTitle()).toEqual('Retail Store Sample App'); + it("should have title", function () { + expect(product.getTitle()).toEqual("Retail Store Sample App"); }); - it('should have breadcrumb', function() { - expect(product.getBreadcrumb().getText()) - .toEqual('Gentleman'); + it("should have breadcrumb", function () { + expect(product.getBreadcrumb().getText()).toEqual("Gentleman"); }); - it('should have name', function() { - expect(product.getName().getText()) - .toEqual('Gentleman'); + it("should have name", function () { + expect(product.getName().getText()).toEqual("Gentleman"); }); - it('should have price', function() { - expect(product.getPrice().getText()) - .toEqual('$795'); + it("should have price", function () { + expect(product.getPrice().getText()).toEqual("$795"); }); - describe('and add to cart', function() { - beforeAll(function() { + describe("and add to cart", function () { + beforeAll(function () { product.go(); product.addToCart(); }); - it('should show cart', function() { - expect(browser.getCurrentUrl()) - .toBe(cart.getUrl()); + it("should show cart", function () { + expect(browser.getCurrentUrl()).toBe(cart.getUrl()); }); }); -}); \ No newline at end of file +}); diff --git a/src/load-generator/helpers.js b/src/load-generator/helpers.js index e4321e335..2eca24e08 100644 --- a/src/load-generator/helpers.js +++ b/src/load-generator/helpers.js @@ -1,27 +1,27 @@ let productIds = [ -'6d62d909-f957-430e-8689-b5129c0bb75e', -'a0a4f044-b040-410d-8ead-4de0446aec7e', -'808a2de1-1aaa-4c25-a9b9-6612e8f29a38', -'510a0d7e-8e83-4193-b483-e27e09ddc34d', -'ee3715be-b4ba-11ea-b3de-0242ac130004', -'f4ebd070-b4ba-11ea-b3de-0242ac130004' -] + "6d62d909-f957-430e-8689-b5129c0bb75e", + "a0a4f044-b040-410d-8ead-4de0446aec7e", + "808a2de1-1aaa-4c25-a9b9-6612e8f29a38", + "510a0d7e-8e83-4193-b483-e27e09ddc34d", + "ee3715be-b4ba-11ea-b3de-0242ac130004", + "f4ebd070-b4ba-11ea-b3de-0242ac130004", +]; function getAllProducts(context, ee, next) { - context.vars.allProducts = productIds + context.vars.allProducts = productIds; - next() + next(); } function setRandomProductId(req, context, ee, next) { const index = Math.floor(Math.random() * productIds.length); - req.form.productId = productIds[index] + req.form.productId = productIds[index]; - next() + next(); } module.exports = { setRandomProductId, - getAllProducts -}; \ No newline at end of file + getAllProducts, +}; diff --git a/src/load-generator/scenario.yml b/src/load-generator/scenario.yml index 532a9ca94..f42b27b25 100644 --- a/src/load-generator/scenario.yml +++ b/src/load-generator/scenario.yml @@ -33,7 +33,7 @@ scenarios: lastName: Doe email: jdoe789@example.com address1: 123 Main Street - address2: + address2: city: New York state: NY zip: 12345 diff --git a/src/orders/events/order-cancelled-event.schema.json b/src/orders/events/order-cancelled-event.schema.json index d90caae45..faf5f3a4e 100644 --- a/src/orders/events/order-cancelled-event.schema.json +++ b/src/orders/events/order-cancelled-event.schema.json @@ -10,5 +10,5 @@ "$ref": "order.schema.json" } }, - "required": [ "order" ] -} \ No newline at end of file + "required": ["order"] +} diff --git a/src/orders/events/order-created-event.schema.json b/src/orders/events/order-created-event.schema.json index 64e19aa9e..639fbd1ae 100644 --- a/src/orders/events/order-created-event.schema.json +++ b/src/orders/events/order-created-event.schema.json @@ -10,5 +10,5 @@ "$ref": "order.schema.json" } }, - "required": [ "order" ] -} \ No newline at end of file + "required": ["order"] +} diff --git a/src/orders/events/order.schema.json b/src/orders/events/order.schema.json index 3cbf905ee..0aa972bb9 100644 --- a/src/orders/events/order.schema.json +++ b/src/orders/events/order.schema.json @@ -3,7 +3,7 @@ "$schema": "http://json-schema.org/draft-07/schema#", "title": "Order", "description": "An order within the store", - "required": [ "id", "firstName", "lastName" ], + "required": ["id", "firstName", "lastName"], "type": "object", "properties": { "id": { @@ -19,4 +19,4 @@ "type": "string" } } -} \ No newline at end of file +} diff --git a/src/orders/openapi.yml b/src/orders/openapi.yml index 17c048724..d8a73c558 100644 --- a/src/orders/openapi.yml +++ b/src/orders/openapi.yml @@ -16,11 +16,11 @@ paths: "200": description: OK content: - '*/*': + "*/*": schema: type: array items: - $ref: '#/components/schemas/ExistingOrder' + $ref: "#/components/schemas/ExistingOrder" post: tags: - orders @@ -30,15 +30,15 @@ paths: content: application/json: schema: - $ref: '#/components/schemas/Order' + $ref: "#/components/schemas/Order" required: true responses: "200": description: OK content: - '*/*': + "*/*": schema: - $ref: '#/components/schemas/ExistingOrder' + $ref: "#/components/schemas/ExistingOrder" components: schemas: Order: @@ -53,7 +53,7 @@ components: items: type: array items: - $ref: '#/components/schemas/OrderItem' + $ref: "#/components/schemas/OrderItem" OrderItem: type: object properties: @@ -77,6 +77,6 @@ components: items: type: array items: - $ref: '#/components/schemas/OrderItem' + $ref: "#/components/schemas/OrderItem" id: type: string diff --git a/src/orders/src/main/resources/application-debug.yml b/src/orders/src/main/resources/application-debug.yml index 2e7582ef3..a5d2e9ed3 100644 --- a/src/orders/src/main/resources/application-debug.yml +++ b/src/orders/src/main/resources/application-debug.yml @@ -15,4 +15,4 @@ logging: org: hibernate: stat: debug - type: trace \ No newline at end of file + type: trace diff --git a/src/orders/src/main/resources/application-prod.yml b/src/orders/src/main/resources/application-prod.yml index 037ed6c42..d3696f5f6 100644 --- a/src/orders/src/main/resources/application-prod.yml +++ b/src/orders/src/main/resources/application-prod.yml @@ -1,2 +1,2 @@ server: - shutdown: graceful \ No newline at end of file + shutdown: graceful diff --git a/src/ui/java-config.json b/src/ui/java-config.json index 14221a3d6..2ec005df9 100644 --- a/src/ui/java-config.json +++ b/src/ui/java-config.json @@ -1,10 +1,10 @@ { - "modelPackage" : "com.example.v3client.model", - "apiPackage" : "com.example.v3client.api", - "invokerPackage" : "com.example.v3client", - "groupId" : "com.example.v3", - "artifactId" : "v3client", - "fullJavaUtil" : true, - "dateLibrary" : "java8", - "library" : "resttemplate" + "modelPackage": "com.example.v3client.model", + "apiPackage": "com.example.v3client.api", + "invokerPackage": "com.example.v3client", + "groupId": "com.example.v3", + "artifactId": "v3client", + "fullJavaUtil": true, + "dateLibrary": "java8", + "library": "resttemplate" } diff --git a/src/ui/src/main/resources/application-prod.yml b/src/ui/src/main/resources/application-prod.yml index 51a2780a0..9e18b59f9 100644 --- a/src/ui/src/main/resources/application-prod.yml +++ b/src/ui/src/main/resources/application-prod.yml @@ -9,4 +9,4 @@ spring: max-age: 31536000 server: - shutdown: graceful \ No newline at end of file + shutdown: graceful diff --git a/src/ui/src/main/resources/application.yml b/src/ui/src/main/resources/application.yml index 22622d14c..412e1a39c 100644 --- a/src/ui/src/main/resources/application.yml +++ b/src/ui/src/main/resources/application.yml @@ -8,7 +8,7 @@ endpoints: carts: false #http://localhost:8082 orders: false #http://localhost:8083 assets: false #http://localhost:8084 - checkout: false #http://localhost:8085 + checkout: false #http://localhost:8085 logging: false http: keep-alive: true @@ -23,4 +23,4 @@ management: endpoints: web: exposure: - include: '*' \ No newline at end of file + include: "*" diff --git a/src/ui/src/main/resources/static/assets/css/styles.css b/src/ui/src/main/resources/static/assets/css/styles.css index 10d217308..8ffc9aa41 100644 --- a/src/ui/src/main/resources/static/assets/css/styles.css +++ b/src/ui/src/main/resources/static/assets/css/styles.css @@ -25,7 +25,7 @@ a { } footer a { - color: rgba(255,255,255,.7); + color: rgba(255, 255, 255, 0.7); } .p-y-lg { @@ -45,7 +45,7 @@ footer a { .breadcrumb.custom a { color: inherit; - opacity: .75; + opacity: 0.75; } .breadcrumb.custom .breadcrumb-item { @@ -54,14 +54,14 @@ footer a { .breadcrumb.custom .breadcrumb-item::before { color: #fff; - opacity: .6; + opacity: 0.6; } .breadcrumb-item.active { color: #6c7781; } -.breadcrumb-item+.breadcrumb-item { +.breadcrumb-item + .breadcrumb-item { padding-left: 10px; } @@ -87,7 +87,10 @@ footer a { flex-grow: 1; } -.icon-xs, .icon-sm, .icon-md, .home-icon { +.icon-xs, +.icon-sm, +.icon-md, +.home-icon { display: inline-flex; align-items: center; justify-content: center; @@ -144,7 +147,6 @@ footer a { width: 25px; height: 25px; border-radius: 25px; - } .stepper .text { display: block; @@ -175,7 +177,7 @@ footer a { .sidebarlist-align { display: flex; } -[class*=sidebarlist-] { +[class*="sidebarlist-"] { margin-bottom: 5px; } @@ -187,7 +189,7 @@ footer a { word-wrap: break-word; font-weight: normal; } -[class*=sidebarlist-] dd { +[class*="sidebarlist-"] dd { margin-bottom: 0; } .box { @@ -196,7 +198,8 @@ footer a { border: 1px solid #dee2e6; } .box img { - max-width: 100%} + max-width: 100%; +} .item-selector { position: relative; margin-right: 5px; @@ -215,7 +218,7 @@ footer a { z-index: 1; mix-blend-mode: darken; } -.item-selector input:checked~.item-candidate { +.item-selector input:checked ~ .item-candidate { background-color: rgba(231, 239, 255, 0.5); border-color: #0e6cf8; -} \ No newline at end of file +} diff --git a/src/ui/src/main/resources/templates/cart.html b/src/ui/src/main/resources/templates/cart.html index 95aa78983..dc3436f56 100644 --- a/src/ui/src/main/resources/templates/cart.html +++ b/src/ui/src/main/resources/templates/cart.html @@ -1,86 +1,110 @@ - - - -
-
+ + + +
+
-
-
-
-
+
+
+
+
-
- -
-
-

Shopping cart

- -
- You don't have any items in your cart! -
- - -
+
+
+
+

Shopping cart

+
+ You don't have any items in your cart!
- + +
-
+
-

-
-
- - \ No newline at end of file +

+
+
+ + diff --git a/src/ui/src/main/resources/templates/catalog.html b/src/ui/src/main/resources/templates/catalog.html index 08dbebea7..a9d802ea4 100644 --- a/src/ui/src/main/resources/templates/catalog.html +++ b/src/ui/src/main/resources/templates/catalog.html @@ -1,67 +1,119 @@ - - - -
-
+ + + +
+
-
-
-
-
+
+
+
+
-
-
-
-
Showing 12 of 25 products
-
-
-
Show - 3 - 9 -
-
-
-
-
-
-
-
-
+
+
+
+ Showing + 12 of + 25 products +
+
+
+
+ Show + 3 + 9 +
+
+
-
- +
+
+
+
+
+
+ +
+
-
- \ No newline at end of file + + diff --git a/src/ui/src/main/resources/templates/checkout-confirm.html b/src/ui/src/main/resources/templates/checkout-confirm.html index 1949ee5d2..cf34d939b 100644 --- a/src/ui/src/main/resources/templates/checkout-confirm.html +++ b/src/ui/src/main/resources/templates/checkout-confirm.html @@ -1,25 +1,43 @@ - - - -
-
+ + + +
+
-
- -
-
-

Leather Wallet for Men Original blue

1 x $123
- $400.90 -
+
+ +
+
+

Leather Wallet for Men Original blue

+ 1 x $123 + +
+ $400.90 +
+
-
-
- -
- - \ No newline at end of file +
+ +
+ + diff --git a/src/ui/src/main/resources/templates/checkout-delivery.html b/src/ui/src/main/resources/templates/checkout-delivery.html index 6ac6eadfd..836b69a7e 100644 --- a/src/ui/src/main/resources/templates/checkout-delivery.html +++ b/src/ui/src/main/resources/templates/checkout-delivery.html @@ -1,26 +1,57 @@ - - - -
-
diff --git a/src/ui/src/main/resources/templates/home.html b/src/ui/src/main/resources/templates/home.html index eedd75d8a..ee61fd9eb 100644 --- a/src/ui/src/main/resources/templates/home.html +++ b/src/ui/src/main/resources/templates/home.html @@ -1,75 +1,94 @@ - - - -
-
+ + + +
+
-

Shop for top products
in our store

-

Latest Products, Low Prices

+

+ Shop for top products
+ in our store +

+

Latest Products, Low Prices

-
-
-
-
+
+
+
+
-

Hot products!

-
-
-
-
+

Hot products!

+
+
+
+
+
-
-
-
- +
+
-

Why choose us

+

Why choose us

-
-
-
- - - -
-
-
We love our customers!
-

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.

-
-
-
-
-
-
- - - -
-
-
Lowest prices
-

Aenean commodo ligula eget dolor. Aenean massa.

-
-
-
-
-
-
- - - -
-
-
Reliable shipping
-

Com sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.

-
-
-
+
+
+
+ + + +
+
+
We love our customers!
+

Lorem ipsum dolor sit amet, consectetuer adipiscing elit.

+
+
+
+
+
+
+ + + +
+
+
Lowest prices
+

Aenean commodo ligula eget dolor. Aenean massa.

+
+
+
+
+
+
+ + + +
+
+
Reliable shipping
+

+ Com sociis natoque penatibus et magnis dis parturient montes, + nascetur ridiculus mus. +

+
+
+
-
-
- - \ No newline at end of file +
+
+ + diff --git a/src/ui/src/main/resources/templates/order.html b/src/ui/src/main/resources/templates/order.html index 349dc8d74..4444e5c33 100644 --- a/src/ui/src/main/resources/templates/order.html +++ b/src/ui/src/main/resources/templates/order.html @@ -1,30 +1,42 @@ - - - -
-
+ + + +
+
-
-
-
-
+
+
+
+
-
-
-
-

Thank you for order

-

Your order number is 123

-

A confirmation email will be sent to you@example.com - with tracking information.

-
-
+
+
+
+
+

Thank you for order

+

+ Your order number is + 123 +

+

+ A confirmation email will be sent to + you@example.com + with tracking information. +

-
+
+
+
-
-
- - \ No newline at end of file +
+ + +