반응형

다음은 이 글의 동영상 강의 입니다.

https://youtu.be/g5LaZ1IPJXE

지난시간에 S3에 업로드가 완료된 파일을 이용해서 Backend API를 이용해 DB에 데이터를 저장하는 것을 진행합니다.

 

S3 파일명 유니크 하게 만들기

frontend 프로젝트에 moment 라는 패키지를 설치합니다.

yarn add moment

moment는 자바스크립트에서 날짜를 핸들링할때 유용한 패키지입니다.

vue에서 moment를 import 합니다.

/admin/index.vue

import moment from 'moment';

다음과 같이 현재 날짜와 시간을 문자열로 만들어주는 function을 methods: 아래에 추가합니다.

genDateTime() {
    return moment().format('YYYYMMDDHHmmss');
},

S3 파일 업로드 모듈을 다음과 같이 변경합니다.

await s3.upload({
    ACL: 'public-read',
    Body: this.genDateTime()+'_'+this.file1,
    Key: this.genDateTime()+'_'+this.file1.name
}

파일을 업로드 하면 다음과 같이 파일명이 생성됩니다.

 

Slider 테이블 생성

우선 MySQL Workbench를 이용해서 테이블을 생성합니다.

id: key값

image_url: S3의 url 정보

created_at: 생성일

updated_at: 수정일

 

Slider 저장용 Backend API 개발

slider-api 프로젝트에서 entity 파일을 다음과 같이 만듭니다.

/domain/slider.entity.ts

import {Column, Entity, PrimaryGeneratedColumn} from "typeorm";

@Entity('slider')
export class Slider {
    @PrimaryGeneratedColumn({type: 'int', name: 'id'})
    id: number;

    @Column('varchar', {name: 'image_url', length: 200})
    imageUrl: string;

    @Column('timestamp', {
        name: 'created_at',
        default: ()=> 'CURRENT_TIMESTAMP'
    })
    createAt: Date;

    @Column('timestamp', {
        name: 'updated_at',
        default: ()=> 'CURRENT_TIMESTAMP'
    })
    updatedAt: Date;
}

nest generator를 이용해서

slider module, controller, service를 추가합니다.

nest g module slider
nest g controller slider
nest g service slider

SliderModule에 entity를 추가합니다.

/slider/slider.module.ts

@Module({
  imports: [
    TypeOrmModule.forFeature([Slider])
  ],
  controllers: [SliderController],
  providers: [SliderService]
})

Controller에 slider api를 post로 추가합니다.

/slider/slider.controller.ts

import {BadRequestException, Body, Controller, Post, Response} from '@nestjs/common';
import {SliderService} from "./slider.service";

@Controller('slider')
export class SliderController {
    constructor(
        private sliderService: SliderService
    ) {}

    @Post('')
    async createSlider(
        @Body() createSliderDTO, @Response() res
    ): Promise<any>{
        const { imageUrl } = createSliderDTO.body;
        if(!imageUrl) throw new BadRequestException();
        await this.sliderService.createSlider({imageUrl});
        res.status(200).json({'message': 'OK'});
        return;
    }
}

Service에 createSlider method를 추가합니다.

/slider/slider.service.ts

import { Injectable } from '@nestjs/common';
import {InjectRepository} from "@nestjs/typeorm";
import {Slider} from "../domain/slider.entity";
import {Repository} from "typeorm";

@Injectable()
export class SliderService {
    constructor(
        @InjectRepository(Slider)
        private sliderRepository: Repository<Slider>
    ) {}
    async createSlider(param: { imageUrl: any }): Promise<any> {
        const {imageUrl} = param;
        await this.sliderRepository.save({imageUrl});
    }
}

 

Frontend 에서 slider API 호출하기

slider-front 프로젝트에서 s3 upload 후에 backend api를 호출하도록 소스를 변경합니다.

async saveImage(imageUrl){
    const headers = {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${this.accessToken}`
    }
    const body = {
        'imageUrl': imageUrl
    }
    await this.$axios.post(
        '/slider',
        {body},
        {headers}
    ).catch(error =>{
        console.log(error);
    })

},
async upload() {
    if(!this.file1){
        alert('File을 선택해주세요!')
    }else{
        console.log(this.file1);
        AWS.config.region = this.bucketRegion;
        AWS.config.credentials = new AWS.CognitoIdentityCredentials({
            IdentityPoolId: this.identityPoolId,
        });
        const s3 = new AWS.S3({
            apiVersion: '2006-03-01',
            params: {
                Bucket: this.bucketName+'/images'
            }
        });
        await s3.upload({
            ACL: 'public-read',
            Body: this.genDateTime()+'_'+this.file1,
            Key: this.genDateTime()+'_'+this.file1.name
        }, (error)=>{
            if(error){
                this.errorHandler(error);
            }
        }).promise().then((data)=>{
            console.log('File uploaded!!!')
            console.log(data);
            this.saveImage(data.Location);
        })
    }
}

파일 업로드 테스트를 합니다.

 

DB에 다음과 같이 데이터가 들어간것을 볼 수 있습니다.

이렇게 해서 S3 업로드 파일을 Backend API를 통해 DB에 저장하는 기능을 구현해 보았습니다.

반응형
반응형

Vue.js를 사용해서 일렉트론 앱을 만드는 법에 대해 알아봅니다.

 

Vue CLI 설치

우선 Vue cli를 전역으로 설치합니다.

  • 기존 vue/cli가 @vue/cli로 변경되었습니다.
  • 이전버전이 설치되어 있다면 삭제 후에 설치해 주세요(npm uninstall vue/cli)
npm i -g @vue/cli

설치가 완료되면 다음 명령으로 설치 버전을 확인합니다.

vue --version

 

Vue 프로젝트 생성

이제 vue 프로젝트를 만듭니다.

  • 프로젝트명 : elec-vue
vue create elec-vue
  • Vue 버전 선택 : 최신 버전인 Vue 3를 선택합니다.

  • 아래와 같이 설치가 진행됩니다.

  • 잠시 후 설치가 완료됩니다.

  • 다음 명령어로 프로젝트를 실행합니다.
yarn serve

  • http://localhost:8080으로 접속하면 다음과 같은 화면이 나옵니다.

  • ctrl + C를 눌러 실행을 종료합니다.

 

프로젝트에 Electron Builder 추가

Electron Builder는 기존 프로젝트를 Electron으로 바꿔주고 쉽게 build를 할 수 있게 돕습니다.

Vue CLI Plugin으로 제공하는 Electron을 사용하면 쉽게 설치가 가능합니다.

https://nklayman.github.io/vue-cli-plugin-electron-builder/

 

Vue CLI Plugin Electron Builder

 

nklayman.github.io

  • 다음 명령으로 Electron Builder를 추가합니다.
vue add electron-builder
  • Electron 버전 선택 : 13.0.0

  • 설치가 완료되면 package.json에 다음과 같이 스크립트가 추가됩니다.'

 

Electron 실행

  • 이제 Electron이 추가된 프로젝트를 실행합니다.(package.json 참고)
yarn electron:serve
  • 실행 화면은 다음과 같습니다.

 

Electron Build

  • 다음 명령으로 App을 Build 할 수 있습니다.
yarn electron:build
  • 빌드가 완료되면 다음과 같이 dist_electron 폴더에 실행 파일이 생성됩니다.
    • 맥의 경우 dmg 파일로, 윈도우의 경우는 exe 파일로 생성됩니다.

  • 생성된 실행파일을 더블클릭하면 다음과 같이 Application이 실행됩니다.

이렇게 vue 프로젝트에 electron builder를 추가하면 쉽게 electron+vue 프로젝트를 만들 수 있습니다.

 

반응형

+ Recent posts