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

Backend - Frontend #330

Open
wants to merge 23 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
40229fb
task2: added s3 bucket and cloudfront distribution
Ilya-Valasiuk Mar 16, 2021
50d2a7a
add comments about custom plugins
Ilya-Valasiuk Mar 17, 2021
05ca160
Merge pull request #1 from EPAM-JS-Competency-center/task-2
Mar 18, 2021
778af13
use regional domain name for s3 bucket in cf distribution
Ilya-Valasiuk Apr 3, 2021
c604116
Merge branch 'main' of github.com:EPAM-JS-Competency-center/shop-reac…
Ilya-Valasiuk Apr 3, 2021
f5749cf
Merge pull request #2 from EPAM-JS-Competency-center/task2-cf-issue
Ilya-Valasiuk Apr 10, 2021
35a645f
Update typescript version
vladshcherbin Aug 13, 2021
4553a25
Update useParams hook typings
vladshcherbin Aug 13, 2021
ae039bb
Merge pull request #29 from vladshcherbin/typescript-errors
SergeyKovalchuk Aug 15, 2021
951ebf9
Replace CRA with vite
AlexandrLi Jul 5, 2022
6260f76
Migrate to mui v5
AlexandrLi Jul 5, 2022
87523cf
Add eslint and prettier configs
AlexandrLi Jul 5, 2022
4e27f32
Migrate to react-router v6
AlexandrLi Jul 6, 2022
567c4cc
clean up code
AlexandrLi Jul 6, 2022
3ee1d97
Add msw as a mock-server
AlexandrLi Jul 6, 2022
5ab872e
Add react-query
AlexandrLi Jul 6, 2022
b8aa162
Remove redux in favor of react-query
AlexandrLi Jul 7, 2022
088b400
Migrate to React 18
AlexandrLi Jul 7, 2022
5c9a441
Migrate to the latest serverless version
AlexandrLi Jul 9, 2022
939e42f
Setup tests. Fix small issues
AlexandrLi Jul 9, 2022
ae777a2
Update README.md
AlexandrLi Jul 10, 2022
e10d6a8
Fix routing issues
AlexandrLi Jul 10, 2022
f17de8e
Merge pull request #120 from AlexandrLi/update-stack
SergeyKovalchuk Jul 14, 2022
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
4 changes: 4 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
public
vite.config.ts
serverless.yml
24 changes: 24 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"root": true,
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": "./tsconfig.json"
},
"extends": [
"plugin:@typescript-eslint/recommended",
"plugin:react/recommended",
"plugin:react/jsx-runtime",
"plugin:prettier/recommended",
"prettier"
],
"plugins": ["@typescript-eslint", "react", "prettier"],
"env": {
"browser": true,
"node": true
},
"settings": {
"react": {
"version": "detect"
}
}
}
43 changes: 21 additions & 22 deletions .gitignore
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,27 +1,26 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

# dependencies
node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
build
.serverless
coverage
dist
dist-ssr
*.local

# misc
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*

/.idea
.vscode
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
145 changes: 145 additions & 0 deletions .serverless_plugins/serverless-single-page-app-plugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
"use strict";

const spawnSync = require("child_process").spawnSync;

class ServerlessPlugin {
constructor(serverless, options) {
this.serverless = serverless;
this.options = options;
this.commands = {
syncToS3: {
usage: "Deploys the `app` directory to your bucket",
lifecycleEvents: ["sync"],
},
domainInfo: {
usage: "Fetches and prints out the deployed CloudFront domain names",
lifecycleEvents: ["domainInfo"],
},
invalidateCloudFrontCache: {
usage: "Invalidates CloudFront cache",
lifecycleEvents: ["invalidateCache"],
},
};

this.hooks = {
"syncToS3:sync": this.syncDirectory.bind(this),
"domainInfo:domainInfo": this.domainInfo.bind(this),
"invalidateCloudFrontCache:invalidateCache":
this.invalidateCache.bind(this),
};
}

runAwsCommand(args) {
let command = "aws";
if (this.serverless.variables.service.provider.region) {
command = `${command} --region ${this.serverless.variables.service.provider.region}`;
}
if (this.serverless.variables.service.provider.profile) {
command = `${command} --profile ${this.serverless.variables.service.provider.profile}`;
}
const result = spawnSync(command, args, { shell: true });
const stdout = result.stdout.toString();
const sterr = result.stderr.toString();
if (stdout) {
this.serverless.cli.log(stdout);
}
if (sterr) {
this.serverless.cli.log(sterr);
}

return { stdout, sterr };
}

// syncs the `app` directory to the provided bucket
syncDirectory() {
const s3Bucket = this.serverless.variables.service.custom.s3Bucket;
const buildFolder =
this.serverless.variables.service.custom.client.distributionFolder;
const args = [
"s3",
"sync",
`${buildFolder}/`,
`s3://${s3Bucket}/`,
"--delete",
];
const { sterr } = this.runAwsCommand(args);
if (!sterr) {
this.serverless.cli.log("Successfully synced to the S3 bucket");
} else {
throw new Error("Failed syncing to the S3 bucket");
}
}

// fetches the domain name from the CloudFront outputs and prints it out
async domainInfo() {
const provider = this.serverless.getProvider("aws");
const stackName = provider.naming.getStackName(this.options.stage);
const result = await provider.request(
"CloudFormation",
"describeStacks",
{ StackName: stackName },
this.options.stage,
this.options.region
);

const outputs = result.Stacks[0].Outputs;
const output = outputs.find(
(entry) => entry.OutputKey === "WebAppCloudFrontDistributionOutput"
);

if (output && output.OutputValue) {
this.serverless.cli.log(`Web App Domain: ${output.OutputValue}`);
return output.OutputValue;
}

this.serverless.cli.log("Web App Domain: Not Found");
const error = new Error("Could not extract Web App Domain");
throw error;
}

async invalidateCache() {
const provider = this.serverless.getProvider("aws");

const domain = await this.domainInfo();

const result = await provider.request(
"CloudFront",
"listDistributions",
{},
this.options.stage,
this.options.region
);

const distributions = result.DistributionList.Items;
const distribution = distributions.find(
(entry) => entry.DomainName === domain
);

if (distribution) {
this.serverless.cli.log(
`Invalidating CloudFront distribution with id: ${distribution.Id}`
);
const args = [
"cloudfront",
"create-invalidation",
"--distribution-id",
distribution.Id,
"--paths",
'"/*"',
];
const { sterr } = this.runAwsCommand(args);
if (!sterr) {
this.serverless.cli.log("Successfully invalidated CloudFront cache");
} else {
throw new Error("Failed invalidating CloudFront cache");
}
} else {
const message = `Could not find distribution with domain ${domain}`;
const error = new Error(message);
this.serverless.cli.log(message);
throw error;
}
}
}

module.exports = ServerlessPlugin;
76 changes: 51 additions & 25 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,45 +1,71 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
# React-shop-cloudfront

This is frontend starter project for nodejs-aws mentoring program. It uses the following technologies:

- [Vite](https://vitejs.dev/) as a project bundler
- [React](https://beta.reactjs.org/) as a frontend framework
- [React-router-dom](https://reactrouterdotcom.fly.dev/) as a routing library
- [MUI](https://mui.com/) as a UI framework
- [React-query](https://react-query-v3.tanstack.com/) as a data fetching library
- [Formik](https://formik.org/) as a form library
- [Yup](https://github.com/jquense/yup) as a validation schema
- [Serverless](https://serverless.com/) as a serverless framework
- [Vitest](https://vitest.dev/) as a test runner
- [MSW](https://mswjs.io/) as an API mocking library
- [Eslint](https://eslint.org/) as a code linting tool
- [Prettier](https://prettier.io/) as a code formatting tool
- [TypeScript](https://www.typescriptlang.org/) as a type checking tool

## Available Scripts

In the project directory, you can run:
You can use NPM instead of YARN (Up to you)
### `start`

### `yarn start` OR `npm run start`
Starts the project in dev mode with mocked API on local environment.

Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.
### `build`

The page will reload if you make edits.<br />
You will also see any lint errors in the console.
Builds the project for production in `dist` folder.

### `yarn test` OR `npm run test`
### `preview`

Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
Starts the project in production mode on local environment.

### `yarn build` OR `npm run build`
### `test`, `test:ui`, `test:coverage`

Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.
Runs tests in console, in browser or with coverage.

The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!
### `lint`, `prettier`

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
Runs linting and formatting for all files in `src` folder.

### `yarn eject` OR `npm run eject`
### `client:deploy`, `client:deploy:nc`

**Note: this is a one-way operation. Once you `eject`, you can’t go back!**
Deploy the project build from `dist` folder to configured in `serverless.yml` AWS S3 bucket with or without confirmation.

If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
### `client:build:deploy`, `client:build:deploy:nc`

Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.
Combination of `build` and `client:deploy` commands with or without confirmation.

You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.
### `cloudfront:setup`

## Learn More
Deploy configured in `serverless.yml` stack via CloudFormation.

You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
### `cloudfront:domainInfo`

To learn React, check out the [React documentation](https://reactjs.org/).
Display cloudfront domain information in console.

### `cloudfront:invalidateCache`

Invalidate cloudfront cache.

### `cloudfront:build:deploy`, `cloudfront:build:deploy:nc`

Combination of `client:build:deploy` and `cloudfront:invalidateCache` commands with or without confirmation.

### `cloudfront:update:build:deploy`, `cloudfront:update:build:deploy:nc`

Combination of `cloudfront:setup` and `cloudfront:build:deploy` commands with or without confirmation.

### `serverless:remove`

Remove an entire stack configured in `serverless.yml` via CloudFormation.
13 changes: 13 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/src/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My shop</title>
</head>
<body>
<div id="app"></div>
<script type="module" src="/src/index.tsx"></script>
</body>
</html>
Loading