dailyFocus - Frontend

  


: Serverless web application 개발 흐름을 가볍게 이해할수 있도록 진행한 프로젝트로 가이드가 되도록  작성하였습니다.


프론트엔드 파트 ~!

<목차>

  • Web Application 소개
  • Front-end 계획하기
  • Front-end 구현하기
  • Front-end 배포하기
  • Front-end 자동 배포하기
  • 참고

Web Application 소개

DailyFocus

링크 : http://kd-sp3-dailyfocus.s3-website.ap-northeast-2.amazonaws.com/

Git : https://github.com/jgcman3/dailyfocus-app-frontend


가이드를 위해 만든 Web App 은 'Daily Focus' 입니다.

  • 몰입을 돕는 시간관리 툴
  • "한가지 일에 집중하라"
  • 역활 1 : 하나의 mission 을 생성하고  mission 완료시 몰입한 시간을 기록한다.
  • 역활 2 : 진행한 mision 들을 보여준다.  

UX/UI 화면















Front-end 계획하기

구성 요소

AWS 에서는 serverless 아키텍처로 제공하는 서비스들을 이용하여 구성할 수 있습니다.



웹 호스팅

  • S3 의 정적 웹 호스팅 서비스를 이용합니다.

구현 방식

  • 언어 : html, css, javascript
  • 라이브러리 : react, react-router, react-redux, react-bootstrap
  • aws 연동 : AWS amplify



Front-end 구현하기

front-end 구현하기

  • 소스 코드 다운로드

    $ git clone https://github.com/jgcman3/dailyfocus-app-frontend
  • aws-amplify 설치하기

    $ npm install aws-amplify --save
  • 의존성 npm package들 설치

    $ npm install

Amplify 를 통해 Back-end 연결하기

  • AWS Resources 명시하기 ( src/config.js )

    // back-end 배포시에 출력된 resource 값들로 아래 정보들을 변경 하세요.
     
    export default {
      s3: {
        REGION: "YOUR_S3_UPLOADS_BUCKET_REGION",
        BUCKET: "YOUR_S3_UPLOADS_BUCKET_NAME"
      },
      apiGateway: {
        REGION: "YOUR_API_GATEWAY_REGION",
        URL: "YOUR_API_GATEWAY_URL"
      },
      cognito: {
        REGION: "YOUR_COGNITO_REGION",
        USER_POOL_ID: "YOUR_COGNITO_USER_POOL_ID",
        APP_CLIENT_ID: "YOUR_COGNITO_APP_CLIENT_ID",
        IDENTITY_POOL_ID: "YOUR_IDENTITY_POOL_ID"
      }
    };

     

  • AWS Amplify Configure 설정하기 ( src/index.js )

    import React from "react";
    import ReactDOM from "react-dom";
    import { BrowserRouter as Router } from "react-router-dom";
    import "./index.css";
    import App from "./App";
     
    import Amplify from "aws-amplify";
    import config from "./config";
     
    Amplify.configure({
      Auth: {
        mandatorySignIn: true,
        region: config.cognito.REGION,
        userPoolId: config.cognito.USER_POOL_ID,
        identityPoolId: config.cognito.IDENTITY_POOL_ID,
        userPoolWebClientId: config.cognito.APP_CLIENT_ID
      },
      Storage: {
        region: config.s3.REGION,
        bucket: config.s3.BUCKET,
        identityPoolId: config.cognito.IDENTITY_POOL_ID
      },
      API: {
        endpoints: [
          {
            name: "notes",
            endpoint: config.apiGateway.URL,
            region: config.apiGateway.REGION
          }
        ]
      }
    });
     
    ReactDOM.render(
      <Router>
        <App />
      </Router>,
      document.getElementById("root")
    );
  • amplify 를 사용하는 코드 ( 예 : 로그인 , src/Containers/Login.js )

    import React, { useState } from "react";
    import { Auth } from "aws-amplify";
    import { FormGroup, FormControl, ControlLabel } from "react-bootstrap";
    import LoaderButton from "../Components/LoaderButton";
    import { useFormFields } from "../libs/hooksLib";
    import "./Login.css";
     
    export default function Login(props) {
      const [isLoading, setIsLoading] = useState(false);
      const [fields, handleFieldChange] = useFormFields({
        email: "",
        password: ""
      });
     
      function validateForm() {
        return fields.email.length > 0 && fields.password.length > 0;
      }
     
      async function handleSubmit(event) {
        event.preventDefault();
     
        setIsLoading(true);
     
        try {
          await Auth.signIn(fields.email, fields.password);
          props.userHasAuthenticated(true);
          props.history.push("/");
        catch (e) {
          alert(e.message);
          setIsLoading(false);
        }
      }
     
      return (
        <div className="Login">
          <form onSubmit={handleSubmit}>
            <FormGroup controlId="email" bsSize="large">
              <ControlLabel>Email</ControlLabel>
              <FormControl
                autoFocus
                type="email"
                value={fields.email}
                onChange={handleFieldChange}
              />
            </FormGroup>
            <FormGroup controlId="password" bsSize="large">
              <ControlLabel>Password</ControlLabel>
              <FormControl
                type="password"
                value={fields.password}
                onChange={handleFieldChange}
              />
            </FormGroup>
            <LoaderButton
              block
              type="submit"
              bsSize="large"
              isLoading={isLoading}
              disabled={!validateForm()}
            >
              Login
            </LoaderButton>
          </form>
        </div>
      );
    }
  • web application 실행하기

    $ npm start

Front-end 배포하기

web console 에서 배포 하기

  • S3 bucket 생성하기
  • 퍼블릭 엑세스 차단 비활성화
  • 정적 웹사이트 호스팅 허용
  • 권한 > 버킷정책에 s3:GetObject Action 에 대한 허용 정책 추가

    {
        "Version""2012-10-17",
        "Statement": [
            {
                "Effect""Allow",
                "Principal""*",
                "Action""s3:GetObject",
                "Resource""arn:aws:s3:::{ 버킷 이름 }/*"
            }
        ]
    }
  • front-end 소스코드 빌드하기

    $ npm run-script build
  • build 폴더에 생성된 파일들을 S3 bucket에 업로드 하기
  • 정적 웹 사이트 호스팅 앤드포인트로 접속 하기



Front-end 자동 배포하기

git 저장소 서비스를 이용하여 S3에 자동 배포하기

  • github action
  • bitbucket pipeline
  • gitlab pipeline

github 'action' 을 이용해 S3에 자동 배포 설정하기

  • .github/workflows/mail.yml 파일 생성 및 편집

    name: React build
    on:
      push: # master Branch에서 push 이벤트가 일어났을 때만 실행
        branches:
          - master
     
    jobs:
      build:
        runs-on: ubuntu-18.04
        steps:
          - name: Checkout source code. # 레포지토리 체크아웃
            uses: actions/checkout@master
     
          - name: Install Dependencies # 의존 파일 설치
            run: npm install
     
          - name: Build # React Build
            run: npm run build
     
          - name: Deploy # S3에 배포하기
            env:
              AWS_ACCESS_KEY_ID: ${{ secrets.AWS_ACCESS_KEY_ID }}
              AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
            run: |
              aws s3 cp build s3://dailyfocus-app-d-frontend --recursive --region ap-northeast-2
  • repository 에 secrets 변수 추가



  • 자동 배포 하기

    $ git add *
    $ git commit -m "adding github action"
    $ git push
  • 자동 배포 동작 확인 하기






  • 정적 웹 사이트 호스팅 엔드 포인트로 확인하기





참고

링크

댓글

이 블로그의 인기 게시물

CDK - Assets

About VPC