Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Task 3 - Creating Product service with API Gateway and AWS Lambda #487

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,13 @@ Combination of `cloudfront:setup` and `cloudfront:build:deploy` commands with or
### `serverless:remove`

Remove an entire stack configured in `serverless.yml` via CloudFormation.

# Task 2

Result:

- CloudFrount (publicly available): https://dq27ikv1czeaj.cloudfront.net/
- S3 (publicly access denied): http://kembek-games-app-content.s3-website-eu-west-1.amazonaws.com/

Description:
The `serverless.yml` file was updated and redundant comments were deleted.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "my-store-app",
"name": "shop-react-redux-cloudfront",
"version": "1.0.0",
"private": true,
"scripts": {
Expand Down Expand Up @@ -70,4 +70,4 @@
"engines": {
"node": ">=14.0.0"
}
}
}
86 changes: 27 additions & 59 deletions serverless.yml
Original file line number Diff line number Diff line change
@@ -1,98 +1,80 @@
service: my-store-app
service: kembek-games-app-content

frameworkVersion: "3"

provider:
name: aws
runtime: nodejs14.x
region: eu-west-1
# setup profile for AWS CLI.
# profile: node-aws

plugins:
- serverless-finch
# 'serverless-single-page-app-plugin' is a custom plugin that located .serverless_plugins folder.
# Existing plugin (https://www.npmjs.com/package/serverless-single-page-app-plugin) doesn't have invalidate cache feature that often used during CI/CD events.
# How to build your own plugins: https://www.serverless.com/framework/docs/providers/aws/guide/plugins#service-local-plugin
- serverless-single-page-app-plugin
- serverless-s3-cleaner

custom:
client:
bucketName: my-store-app
bucketName: kembek-games-app-content
distributionFolder: dist
s3BucketName: ${self:custom.client.bucketName}

## Serverless-single-page-app-plugin configuration:
s3LocalPath: ${self:custom.client.distributionFolder}/
serverless-s3-cleaner:
buckets:
- ${self:custom.client.bucketName}

resources:
Resources:
## Specifying the S3 Bucket
WebAppS3Bucket:
Type: AWS::S3::Bucket
Properties:
BucketName: ${self:custom.s3BucketName}
AccessControl: PublicRead
BucketName: ${self:custom.client.bucketName}
WebsiteConfiguration:
IndexDocument: index.html
ErrorDocument: index.html
# VersioningConfiguration:
# Status: Enabled
OwnershipControls:
Rules:
- ObjectOwnership: BucketOwnerEnforced

## Specifying the policies to make sure all files inside the Bucket are avaialble to CloudFront
WebAppS3BucketPolicy:
Type: AWS::S3::BucketPolicy
Properties:
Bucket:
Ref: WebAppS3Bucket
Bucket: !Ref WebAppS3Bucket
PolicyDocument:
Statement:
- Sid: "AllowCloudFrontAccessIdentity"
- Sid: "AllowCloudFrontServicePrincipal"
Effect: Allow
Action: s3:GetObject
Resource: arn:aws:s3:::${self:custom.s3BucketName}/*
Principal:
AWS:
Fn::Join:
- " "
- - "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity"
- !Ref OriginAccessIdentity
Service: cloudfront.amazonaws.com
Action: s3:GetObject
Resource: "arn:aws:s3:::${self:custom.client.bucketName}/*"
Condition:
StringEquals:
AWS:SourceArn: !Sub "arn:aws:cloudfront::${AWS::AccountId}:distribution/${WebAppCloudFrontDistribution}"

OriginAccessIdentity:
Type: AWS::CloudFront::CloudFrontOriginAccessIdentity
OriginAccessControlPolicy:
Type: AWS::CloudFront::OriginAccessControl
Properties:
CloudFrontOriginAccessIdentityConfig:
Comment: Access identity between CloudFront and S3 bucket
OriginAccessControlConfig:
OriginAccessControlOriginType: s3
Name: ${self:custom.client.bucketName}-OAC
SigningProtocol: sigv4
SigningBehavior: always
Description: Access control for CloudFront to S3

## Specifying the CloudFront Distribution to server your Web Application
WebAppCloudFrontDistribution:
Type: AWS::CloudFront::Distribution
Properties:
DistributionConfig:
Origins:
- DomainName: !GetAtt WebAppS3Bucket.RegionalDomainName
## An identifier for the origin which must be unique within the distribution
Id: myS3Origin
## In case you don't want to restrict the bucket access use CustomOriginConfig and remove S3OriginConfig
Id: ${self:custom.client.bucketName}-Origin
OriginAccessControlId: !Ref OriginAccessControlPolicy
S3OriginConfig:
OriginAccessIdentity: !Sub origin-access-identity/cloudfront/${OriginAccessIdentity}
# CustomOriginConfig:
# HTTPPort: 80
# HTTPSPort: 443
# OriginProtocolPolicy: https-only
OriginAccessIdentity: ""
Enabled: true
IPV6Enabled: true
HttpVersion: http2
## Uncomment the following section in case you are using a custom domain
# Aliases:
# - mysite.example.com
DefaultRootObject: index.html
## Since the Single Page App is taking care of the routing we need to make sure ever path is served with index.html
## The only exception are files that actually exist e.h. app.js, reset.css
CustomErrorResponses:
- ErrorCode: 404
ResponseCode: 200
Expand All @@ -101,31 +83,17 @@ resources:
AllowedMethods: ["GET", "HEAD", "OPTIONS"]
CachedMethods: ["GET", "HEAD", "OPTIONS"]
ForwardedValues:
Headers:
- Access-Control-Request-Headers
- Access-Control-Request-Method
- Origin
- Authorization
## Defining if and how the QueryString and Cookies are forwarded to the origin which in this case is S3
Headers: ["Access-Control-Request-Headers", "Origin"]
QueryString: false
Cookies:
Forward: none
## The origin id defined above
TargetOriginId: myS3Origin
## The protocol that users can use to access the files in the origin. To allow HTTP use `allow-all`
TargetOriginId: ${self:custom.client.bucketName}-Origin
ViewerProtocolPolicy: redirect-to-https
Compress: true
DefaultTTL: 0
## The certificate to use when viewers use HTTPS to request objects.
ViewerCertificate:
CloudFrontDefaultCertificate: true
## Uncomment the following section in case you want to enable logging for CloudFront requests
# Logging:
# IncludeCookies: 'false'
# Bucket: mylogs.s3.amazonaws.com
# Prefix: myprefix

## In order to print out the hosted domain via `serverless info` we need to define the DomainName output for CloudFormation
Outputs:
WebAppS3BucketOutput:
Value: !Ref WebAppS3Bucket
Expand Down
2 changes: 1 addition & 1 deletion src/components/App/App.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ test("Renders products list", async () => {
},
];
server.use(
rest.get(`${API_PATHS.bff}/product/available`, (req, res, ctx) => {
rest.get(`${API_PATHS.bff}/products`, (req, res, ctx) => {
return res(
ctx.status(200),
ctx.delay(),
Expand Down
2 changes: 1 addition & 1 deletion src/components/pages/PageOrder/PageOrder.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export default function PageOrder() {
queryKey: "products",
queryFn: async () => {
const res = await axios.get<AvailableProduct[]>(
`${API_PATHS.bff}/product/available`
`${API_PATHS.bff}/products`
);
return res.data;
},
Expand Down
10 changes: 5 additions & 5 deletions src/constants/apiPaths.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const API_PATHS = {
product: "https://.execute-api.eu-west-1.amazonaws.com/dev",
order: "https://.execute-api.eu-west-1.amazonaws.com/dev",
import: "https://.execute-api.eu-west-1.amazonaws.com/dev",
bff: "https://.execute-api.eu-west-1.amazonaws.com/dev",
cart: "https://.execute-api.eu-west-1.amazonaws.com/dev",
product: "https://6ohm6rxov1.execute-api.eu-west-1.amazonaws.com/dev",
order: "https://6ohm6rxov1.execute-api.eu-west-1.amazonaws.com/dev",
import: "https://6ohm6rxov1.execute-api.eu-west-1.amazonaws.com/dev",
bff: "https://6ohm6rxov1.execute-api.eu-west-1.amazonaws.com/dev",
cart: "https://6ohm6rxov1.execute-api.eu-west-1.amazonaws.com/dev",
};

export default API_PATHS;
20 changes: 10 additions & 10 deletions src/mocks/data.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,34 +5,34 @@ import { AvailableProduct, Product } from "~/models/Product";

export const products: Product[] = [
{
description: "Short Product Description1",
description: "Short Mortal Combat X Description",
id: "7567ec4b-b10c-48c5-9345-fc73c48a80aa",
price: 24,
title: "ProductOne",
title: "Mortal Combat X",
},
{
description: "Short Product Description7",
description: "Short GrandTour Description",
id: "7567ec4b-b10c-48c5-9345-fc73c48a80a1",
price: 15,
title: "ProductTitle",
title: "GrandTour",
},
{
description: "Short Product Description2",
description: "Short GTA V Description",
id: "7567ec4b-b10c-48c5-9345-fc73c48a80a3",
price: 23,
title: "Product",
title: "GTA V",
},
{
description: "Short Product Description4",
description: "Short CS:GO Description",
id: "7567ec4b-b10c-48c5-9345-fc73348a80a1",
price: 15,
title: "ProductTest",
title: "CS:GO",
},
{
description: "Short Product Descriptio1",
description: "Short Rust Description",
id: "7567ec4b-b10c-48c5-9445-fc73c48a80a2",
price: 23,
title: "Product2",
title: "Rust",
},
{
description: "Short Product Description7",
Expand Down
2 changes: 1 addition & 1 deletion src/mocks/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export const handlers = [
rest.delete(`${API_PATHS.bff}/product/:id`, (req, res, ctx) => {
return res(ctx.status(200));
}),
rest.get(`${API_PATHS.bff}/product/available`, (req, res, ctx) => {
rest.get(`${API_PATHS.bff}/products`, (req, res, ctx) => {
return res(
ctx.status(200),
ctx.delay(),
Expand Down
17 changes: 7 additions & 10 deletions src/queries/products.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,18 @@ import { useQuery, useQueryClient, useMutation } from "react-query";
import React from "react";

export function useAvailableProducts() {
return useQuery<AvailableProduct[], AxiosError>(
"available-products",
async () => {
const res = await axios.get<AvailableProduct[]>(
`${API_PATHS.bff}/product/available`
);
return res.data;
}
);
return useQuery<AvailableProduct[], AxiosError>("products", async () => {
const res = await axios.get<AvailableProduct[]>(
`${API_PATHS.bff}/products`
);
return res.data;
});
}

export function useInvalidateAvailableProducts() {
const queryClient = useQueryClient();
return React.useCallback(
() => queryClient.invalidateQueries("available-products", { exact: true }),
() => queryClient.invalidateQueries("products", { exact: true }),
[]
);
}
Expand Down