<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[CrocusEnergy - Medium]]></title>
        <description><![CDATA[Crocus Tech Blog — We are motivated to provide AI solutions that can achieve our mission. - Medium]]></description>
        <link>https://medium.com/crocusenergy?source=rss----35f311588f8a---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>CrocusEnergy - Medium</title>
            <link>https://medium.com/crocusenergy?source=rss----35f311588f8a---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 20:34:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/crocusenergy" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[TypeORM + MongoDB 적용 및 사용하지 않게 된 이유]]></title>
            <link>https://medium.com/crocusenergy/typeorm-mongodb-%EC%A0%81%EC%9A%A9%EA%B3%BC-%EC%93%B0%EC%A7%80-%EC%95%8A%EA%B2%8C%EB%90%9C-%EC%9D%B4%EC%9C%A0-d3ce790b1455?source=rss----35f311588f8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/d3ce790b1455</guid>
            <category><![CDATA[typeorm]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[JongInKoo]]></dc:creator>
            <pubDate>Fri, 01 Oct 2021 02:41:57 GMT</pubDate>
            <atom:updated>2021-10-01T02:42:42.746Z</atom:updated>
            <content:encoded><![CDATA[<p>TypeORM을 사용할 때 왜 Mongodb는 잘 안쓰는지에 대해 궁금해서 직접 알아보기 위해 적용해본 내용을 기록 하였습니다.</p><h4>진행하던 프로젝트의 포함되는 패키지는 다음과 같습니다.</h4><ol><li>Nestjs : v8@nestjs/core&quot;: &quot;^8.0.7&quot;</li><li>Mongodb(+4 Native) + Mongodb Package(4.1.2)</li><li>TypeORM : v0.2.37 @nestjs/typeorm&quot;: &quot;^8.0.2</li></ol><h3><strong>진행 전 사용 가능성에 대해 알아 보기</strong></h3><p>먼저 TypeORM을 지원하는 Platform은 다음과 같습니다.<br><strong>TypeORM — Supported platforms</strong></p><p><a href="https://typeorm.io/#/supported-platforms">TypeORM — Amazing ORM for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.</a></p><p>두번째로 TypeORM의 Mongodb Support입니다.<br><strong>TypeORM — MongoDB support</strong></p><p><a href="https://typeorm.io/#/mongodb/mongodb-support">TypeORM — Amazing ORM for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.</a></p><p>TypeORM has basic MongoDB support. Most of TypeORM functionality is RDBMS-specific, this page contains all MongoDB-specific functionality documentation.</p><blockquote><em>TypeORM은 기본 MongoDB를 지원합니다. TypeORM 기능의 대부분은 RDBMS에 고유하며 이 페이지에는 모든 MongoDB 관련 기능 설명서가 포함되어 있습니다.</em></blockquote><p><strong>지원하는 version은 공식 문서에 작성되어있지 않지만, TypeORM을 사용하지 않게 된 이유가 여기에 있습니다.( 글 작성일 기준으로 Typeorm은 Mongdb version3까지만 지원합니다.)</strong></p><p>(적용 당시에는 지원 버전을 몰랐기 때문에 계속 진행하였습니다.)</p><h3>Nest Framework 위에 TypeORM 적용하기</h3><ol><li>TypeORM Modulize</li></ol><p>database.module.ts</p><pre>import { Module } from &#39;<a href="http://twitter.com/nestjs/common">@nestjs/common</a>&#39;;<br>import { TypeOrmModule } from &#39;<a href="http://twitter.com/nestjs/typeorm">@nestjs/typeorm</a>&#39;;<br>import { Connection } from &#39;typeorm&#39;;</pre><pre>/**<br> * 데이터베이스 모듈<br> */<br><a href="http://twitter.com/Module">@Module</a>({<br>  imports: [<br>    TypeOrmModule.forRootAsync({<br>      useFactory: async () =&gt; ({<br>        type: &#39;mongodb&#39;,<br>        host: &#39;--------&#39;,<br>        port: 27017,<br>        username: &#39;--------&#39;,<br>        password: &#39;--------&#39;,<br>        database: &#39;databaseName&#39;,<br>        entities: [&#39;**/*.entity{.ts,.js}&#39;],<br>      }),<br>    }),<br>  ],<br>  providers: [DatabaseService],<br>  exports: [TypeOrmModule],<br>})<br>export class DatabaseModule {<br>  constructor(connection: Connection) {}<br>}</pre><p>2. Inject Database Module on AppModule</p><p>app.module.ts</p><pre><a href="http://twitter.com/Module">@Module</a>({<br>  imports: [<br>    ConfigModule.forRoot({<br>      isGlobal: true,<br>      envFilePath: &#39;.env.local&#39;,<br>      // ignoreEnvFile: process.env.NODE_ENV !== &#39;local&#39;,<br>      validationSchema: Joi.object({<br>        MONGODB_HOST: Joi.string().required(),<br>      }),<br>    }),<br>    DatabaseModule,<br>    TypeOrmModule.forFeature([Parameter]),<br>  ],<br>  controllers: [AppController],<br>  providers: [<br>    {<br>      provide: APP_FILTER,<br>      useClass: HttpExceptionFilter,<br>    },<br>    {<br>      provide: APP_INTERCEPTOR,<br>      useClass: HttpResponseInterceptor,<br>    },<br>    AppService,<br>  ],<br>})<br>export class AppModule {}</pre><p>3. Project Hierarchy</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/1*EMA5DKmQ7p_6MYbwSGyWGQ.png" /></figure><p>4. Run Application</p><pre>$ nest start</pre><p>여기까지 진행을 하고 실행을 하니 아래 에러가 발생하였습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CaO9dMRW8Uh-6w0pyg6sQQ.png" /></figure><pre>{ProjectPath}/src/parameters/parameters.entity.ts:1<br>import { Column, Entity, ObjectID, ObjectIdColumn } from &#39;typeorm&#39;;<br>^^^^^^</pre><pre>SyntaxError: Cannot use import statement outside a module</pre><p>에러는 SyntaxError였고 내용은 Cannot use import statement outside a module였습니다. (js에서 import 문법 못써서 발생)</p><p>원인은 프로젝트가 Typescript프로젝트여서 였습니다.</p><p>TypeORM은 어플리케이션 실행시 Entity를 초기화하는 작업을 수행합니다.</p><p>이때 Entity가 작성된 파일은 Javascript여야하며, 이유는 TypeORM이 초기화하는 작업이 수행되는 코어가 Javascript Base이기 때문입니다.</p><p>구글링해보니 몇가지 해결법들이 공유되고 있었습니다.</p><p><a href="https://stackoverflow.com/questions/59435293/typeorm-entity-in-nestjs-cannot-use-import-statement-outside-a-module">TypeORM Entity in NESTJS — Cannot use import statement outside a module</a></p><ol><li>TypeORM Module Configuration의 entities 설정 path를 다음과 같이 수정하세요.</li></ol><pre>entities: [&#39;src/**/*.entity.{ts,js}&#39;]</pre><p>2. TypeORM Module Configuration의 entities 설정 path를 다음과 같이 수정하세요.</p><pre>entities: [&#39;../**/*.entity.{ts,js}&#39;]</pre><p>3. The error you are getting is because you are attempting to import a ts file in a js context. So long as you aren&#39;t using webpack you can use this instead so that you get the correct files (가져오는 오류는 js 컨텍스트에서 ts 파일을 가져오려고 하기 때문입니다. webpack을 사용하지 않는 한 올바른 파일을 얻기 위해 이것을 대신 사용할 수 있습니다.)</p><pre>entities: [join(__dirname, &#39;**&#39;, &#39;*.entity.{ts,js}&#39;)]</pre><p>시도해본 결과 1,2,3번 모두 계속해서 문제가 해결되지 않았습니다.</p><p>그러나 3번에서 말하듯 webpack이나 별도 transpiling(ts to js)을 할 수 있다면, js로 Entity를 load하면 되기 때문에 문제가 해결될 것 같아 Nest가 Build Time을 지나고 만들어내는 dist 폴더의 Entity(js file)로 연결하는 방법을 시도 하였습니다.</p><p>최종적으로 아래 형태의 코드로 수정했습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYWrE0m_3SaQy_NUzv8eOw.png" /></figure><p>수정한 코드로 실행해보니 Database 연결까지 정상적으로 됬습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wo9kP6-CFMMdy5Y4Acgu9w.png" /></figure><p>마지막으로 구성해둔 Database의 데이터를 조회하는 것을 테스트해보겠습니다.</p><pre>import { Controller, Get, HttpCode } from &#39;<a href="http://twitter.com/nestjs/common">@nestjs/common</a>&#39;;<br>import { AppService } from &#39;./app.service&#39;;<br>import { InjectRepository } from &#39;<a href="http://twitter.com/nestjs/typeorm">@nestjs/typeorm</a>&#39;;<br>import { MongoRepository } from &#39;typeorm&#39;;<br>import { Parameter } from &#39;./parameters/parameters.entity&#39;;</pre><pre><a href="http://twitter.com/Controller">@Controller</a>()<br>export class AppController {<br>  constructor(<br>    private readonly appService: AppService,<br>    <a href="http://twitter.com/InjectRepository">@InjectRepository</a>(Parameter)<br>    private readonly parametersRepository: MongoRepository&lt;Parameter&gt;,<br>  ) {}</pre><pre><a href="http://twitter.com/Get">@Get</a>(&#39;/&#39;)<br>  async test() {<br>    const result = await this.parametersRepository.find({});<br>    console.log(result);<br>    return &#39;ok&#39;;<br>  }<br>}</pre><p>간단하게 AppController에 / Endpoint로 GET요청시 find된 data를 반환하는 코드입니다.</p><p>시도해보니 아래 에러가 발생했습니다.</p><p><strong>TypeError: Cannot read property ‘prototype’ of undefined</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wl9lrNaUR7YBAUMOpbAVxA.png" /></figure><p>검색해보니 TypeORM은 Mongodb v4를 지원하지 않는다고 합니다.</p><p><a href="https://stackoverflow.com/questions/68908467/typeorm-and-mongodb-and-repositories-cannot-read-property-prototype-of-undefi?noredirect=1">TypeORM and MongoDB and Repositories: Cannot read property ‘prototype’ of undefined</a></p><p>제가 사용했던 버전은 v4였기 때문에 발생한 문제였고, 잘못된 정보가 아닌가 싶어 공식 문서를 찾아보니</p><p>버전에 대한 내용은 존재하지 않았습니다. 그래서 TypeORM Github에서 확인한 결과 저와 동일한 이슈들에 대해 다른 사람들도 겪고있었으며, Mongodb를 사용하기 위해서는 현재(작성일 2021.09.30)는 버전을 내리는 방법밖에 없다고 합니다.</p><blockquote><em>이슈 링크</em></blockquote><blockquote><a href="https://github.com/typeorm/typeorm/issues/8146">find() throws error while using mongodb · Issue #8146 · typeorm/typeorm</a></blockquote><p>Nestjs 공식 문서에도 테스트 코드가 Mongodb는 Mongoose로 되어있고,</p><p>TypeORM의 버전도 0.2인걸로 보아 TypeORM + Mongodb는 아직 쓰기엔 시기상조인 것 같아 보입니다.</p><p>그래서 TypeORM + Mongodb의 실험은 여기서 종료를 하고, Mongoose로 개발을 진행할 계획입니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3ce790b1455" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crocusenergy/typeorm-mongodb-%EC%A0%81%EC%9A%A9%EA%B3%BC-%EC%93%B0%EC%A7%80-%EC%95%8A%EA%B2%8C%EB%90%9C-%EC%9D%B4%EC%9C%A0-d3ce790b1455">TypeORM + MongoDB 적용 및 사용하지 않게 된 이유</a> was originally published in <a href="https://medium.com/crocusenergy">CrocusEnergy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[데이터 사이언스를 위한 푸리에 변환]]></title>
            <link>https://medium.com/crocusenergy/%EB%8D%B0%EC%9D%B4%ED%84%B0-%EC%82%AC%EC%9D%B4%EC%96%B8%EC%8A%A4%EB%A5%BC-%EC%9C%84%ED%95%9C-%ED%91%B8%EB%A6%AC%EC%97%90-%EB%B3%80%ED%99%98-d7800805f80b?source=rss----35f311588f8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/d7800805f80b</guid>
            <category><![CDATA[timeseries]]></category>
            <category><![CDATA[fourier-transform]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[power-forecasting]]></category>
            <category><![CDATA[decomposition]]></category>
            <dc:creator><![CDATA[Boknyun Kim]]></dc:creator>
            <pubDate>Mon, 12 Apr 2021 02:29:22 GMT</pubDate>
            <atom:updated>2021-04-12T02:29:22.088Z</atom:updated>
            <content:encoded><![CDATA[<p>시계열을 분석하기 위해 쓰이는 푸리에 변환에 대해 알아보고 Python으로 간단하게 구현해보겠습니다.</p><p>전력 소비량과 같은 시계열은 여러 요인들에 의해 영향을 받고 있지만, 요인들에 대한 정보가 없을 때는 분석하기가 쉽지 않습니다. 시계열은 여러 요인들의 혼합된 결과값이라고 할 때, 주파수 분해를 통해 의미있는 결과를 도출할 수 있습니다. 주파수 분해라는 것은 시계열에서 주기가 서로 다른 파동들을 분해하는 것입니다. 대표적인 주파수 분해 방법이 Fourier Transform(푸리에 변환)입니다.</p><p>Fourier Transform(푸리에 변환)</p><p>푸리에 변환은 아래와 같이 시간의 영역에 존재하는 시계열(검정)을 주파수(빨강) 영역으로 변환시킵니다. 푸리에 변환을 통해 시계열에 존재하는주파수를 찾을 수 있으며, 이를 통해 시계열을 구성하는 서로 다른 주기를 가진 파동(파랑)을 분해할 수 있습니다. 분해된 파동은 서로 다른 주파수를 가지는 정현파(사인파)입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*v8gg7ENvIMlvZgV7DWukgA.png" /></figure><p>이제 scipy에서 제공하는 fast fourier transform(fft)를 이용하여 간단히 실습해보겠습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06d35029f38262b2980778fcbd479d5d/href">https://medium.com/media/06d35029f38262b2980778fcbd479d5d/href</a></iframe><p>실습에 필요한 matplotlib, numpy, scipy를 불러옵니다.</p><p>구간[0,1]에서 N개를 등간격으로 샘플링하여 xa를 생성합니다. 0이상 1이하의 범위에서 총 1000개의 값이 만들어졌습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39949d4ab6006ced86490dba54905ffb/href">https://medium.com/media/39949d4ab6006ced86490dba54905ffb/href</a></iframe><p>x를 대입하고 주기를 각각 1/10, 1/20, 1/50/ 1/70으로 하여 주파수가 10Hz, 20Hz, 50Hz, 70Hz인 정현파값을 생성합니다.</p><p>y1, y2, y3, y4를 그래프로 나타낸면 아래와 같습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*XWnWQBtAvgXU0O3DiMM_xA.png" /></figure><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87b76aadd09af99c744fc5788b4b885d/href">https://medium.com/media/87b76aadd09af99c744fc5788b4b885d/href</a></iframe><p>y1, y2, y3, y4를 모두 더하여 새로운 시계열을 생성합니다. 따라서 시계열은 10Hz, 20Hz, 50Hz, 70Hz의 성분을 모두 포함하는 시계열입니다.</p><p>fftfreq함수를 이용하여 주파수 스펙트럼을 생성합니다. 주파수 스펙트럼은 탐색할 주파수들의 후보군으로 생각할 수 있습니다. 이번 실습에서 frequency는 1000개의 주파수로 구성된 array이고 다음과 같습니다.</p><p>[0, 1, 2, …, 499, -500, -499, … ,-2, -1]</p><p>주파수의 음수 영역을 제외하기 위해 500개 (N//2)만 취합니다.</p><p>fft함수로 amplitude (푸리에 변환 계수; 크기)를 계산합니다. amplitude는 주파수의 강도로 이해할 수 있습니다. amplitude는 샘플 개수(N)에 비례하기 때문에 정규화하기 위해서 N으로 나누어줍니다.</p><p>시계열에서 분해된 주파수를 그래프로 나타내면 아래와 같습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*59uGWb8JB-Q5D6SuG-JOCg.png" /></figure><p>분해된 주파수를 통해 각각의 주파수를 가진 정현파를 재현하면 시계열을 구성하는 서로 다른 주기의 파동을 알아 낼 수 있습니다. 위의 그래프를 보면 푸리에 변환을 통해 시계열에서 10Hz, 20Hz, 50Hz, 70Hz의 주파수를 추출했습니다.</p><p>이번에는 같은 주파수로 구성된 다른 시계열을 구현하면서 푸리에 변환의 특징을 알아보겠습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c69a2a405407ccc8a36a49dfea0bed92/href">https://medium.com/media/c69a2a405407ccc8a36a49dfea0bed92/href</a></iframe><p>이번에 생성한 시계열은 서로 다른 주파수를 가진 정현파를 시간순서대로 결합했습니다. 좀 전의 시계열과 분명히 다른 시계열임에도 불구하고, 추출되는 주파수는 같습니다. 아래 그림을 통해 알아볼 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/711/1*aE65yR-6OoiFOT0ZPYaxCw.png" /></figure><p>위에서 실행한 두 번의 푸리에 변환을 통해 푸리에 변환은 시계열에 포함된 주파수를 분해하는 것은 가능하지만, 그 주파수가 어느 시간대에 존재하는 지는 알 수 없다는 것을 알 수 있습니다. 이를, 주파수 분해능은 높지만 시간 분해능은 낮다고 말합니다. 따라서, 푸리에 변환을 통해 시계열을 분해할 때는 이 점을 주의해야합니다.</p><p>푸리에 변환이 시간 분해능이 낮기 때문에, 이를 보완하는 short time fourier transform과 wavelet transform 같은 다른 주파수 분해 방법도 있습니다. Wavelet transform은 다음 시간에 알아보겠습니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7800805f80b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crocusenergy/%EB%8D%B0%EC%9D%B4%ED%84%B0-%EC%82%AC%EC%9D%B4%EC%96%B8%EC%8A%A4%EB%A5%BC-%EC%9C%84%ED%95%9C-%ED%91%B8%EB%A6%AC%EC%97%90-%EB%B3%80%ED%99%98-d7800805f80b">데이터 사이언스를 위한 푸리에 변환</a> was originally published in <a href="https://medium.com/crocusenergy">CrocusEnergy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Conservation Voltage Reduction Factor]]></title>
            <link>https://medium.com/crocusenergy/conservation-voltage-reduction-factor-30744c992aac?source=rss----35f311588f8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/30744c992aac</guid>
            <category><![CDATA[보존전압강하]]></category>
            <category><![CDATA[energy-efficiency]]></category>
            <category><![CDATA[cvr]]></category>
            <category><![CDATA[energy]]></category>
            <category><![CDATA[voltage]]></category>
            <dc:creator><![CDATA[Boknyun Kim]]></dc:creator>
            <pubDate>Fri, 09 Apr 2021 09:11:14 GMT</pubDate>
            <atom:updated>2021-04-12T01:55:16.046Z</atom:updated>
            <content:encoded><![CDATA[<p>환경 문제가 중요해지면서 에너지 절감에 대한 관심이 많아지고 있습니다. 전력 분야에서는 에너지 절감을 위해 스마트 그리드와 같은 기술이 지속적으로 연구되고 있습니다. 그 중에 전압 절감을 위한 기술로 Conservation Voltage Reduction(CVR) 이 있습니다. CVR은 전압을 강하시키면 전력 사용량이 절감되는 기술로 1948년 미국 전력회사인 PG&amp;E에서 처음으로 실시됐고, 그 이후로 oil shock로 인해 에너지 절감이 화두가 되면서 본격적으로 미국을 시작으로 전세계에 사용되어 왔습니다. 또한, 한국전력공사도 2012년에 전국 배전용 변압기를 대상으로 CVR 실증을 실시했고, 약 2%의 전력 감축을 검증했습니다. 크로커스의 ACELO GRID는 국내 최초 인공지능 산업용 CVR 솔루션입니다.</p><p>CVR 솔루션으로 발생한 전력 절감 효과를 계량화하고 절감된 비용을 산출하기 위해서 필요한 개념이 Conservation Voltage reduction Factor(보존전압강하계수) 입니다. 산업체의 데이터를 기반으로 보존전압강하 계수를 계산하여 ROI를 추정할 수 있습니다. 이제부터는 보존전압강하계수에 대해 자세히 알아보겠습니다.</p><p>Conservation Voltage reduction Factor(보존전압강하계수, 이하 CVR factor)는 전압 변동률에 대한 전력 변동률을 의미합니다. 즉 전력 변동률을 전압 변동률로 나눈 값입니다. 예들 들어, 전압이 1% 내려갈 때, 전력이 2% 내려가면 CVR Factor는 2 입니다.</p><p>CVR factor는 전압 제어를 통한 전력 절감을 수행할 때, 절감된 전력량을 추정하기 위해 사용됩니다. 엄밀하게 전력의 절감량을 계산하기 위해서는 동일한 조건에서 전력 절감을 수행하지 않을 때의 전력 사용량과 전력 절감을 수행했을 때 사용량의 차이를 계산해야합니다. 하지만 현실에서는 전력 절감을 수행했다면, 전력 절감을 수행하지 않았을 때 사용한 전력을 알 수 없습니다. 따라서, 실제 절감량을 계산할 수 없기때문에 CVR factor를 통해 추정할 수 있습니다.</p><p>수식은 아래와 같이 표현할 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/219/1*ysVROuLefsTQMItdzm-niA.png" /><figcaption>수식 1. CVR factor</figcaption></figure><p>%∆V는 전압 변동률이고, %∆P는 전력 변동률을 나타냅니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*WlEdO6Y5QoE2HfokBjNssA.png" /><figcaption>수식 2. 전압 변동률</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/303/1*Q02JlLdhZ60dnr88Y-pY4w.png" /><figcaption>수식3. 전력 변동률</figcaption></figure><p>전압 변동률은 전압 제어가 일어난 직후의 전압(Vt)과 직전의 전압(Vt-1)의 차를 직전 전압으로 나눈 값입니다. 즉, 전압 제어가 일어나기 직전의 전압 대비 전압 제어 직후의 전압이 얼마나 변했는지를 측정한 것입니다.</p><p>전력 변동률은 전압 제어가 일어난 직후의 전력(Pt)과 직전의 전력(Pt-1)의 차를 직전 전력으로 나눈 값입니다. 즉, 전압 제어가 일어나기 직전의 전력 대비 전압 제어 직후의 전력이 얼마나 변했는지를 측정한 것입니다.</p><p>아래 그림에서 전압제어에 따른 전압과 전력의 변동을 볼 수 있습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/536/1*K0Jf6ZyWNa8By4P95yJjVQ.png" /><figcaption>그림 1. 전압과 전력의 변동</figcaption></figure><p>지금까지 간략하게 CVR factor에 대해 알아보았습니다.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30744c992aac" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crocusenergy/conservation-voltage-reduction-factor-30744c992aac">Conservation Voltage Reduction Factor</a> was originally published in <a href="https://medium.com/crocusenergy">CrocusEnergy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Github Label, Issue, Pull Request Template 적용하기]]></title>
            <link>https://medium.com/crocusenergy/github-label-issue-pull-request-template-%EC%A0%81%EC%9A%A9%ED%95%98%EA%B8%B0-931af8740792?source=rss----35f311588f8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/931af8740792</guid>
            <category><![CDATA[github]]></category>
            <category><![CDATA[github-label]]></category>
            <category><![CDATA[github-issue]]></category>
            <category><![CDATA[github-pr]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[modolee]]></dc:creator>
            <pubDate>Thu, 26 Nov 2020 01:32:23 GMT</pubDate>
            <atom:updated>2020-11-26T01:34:36.565Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*e8hM8cLvGFrnj7i4.png" /></figure><h3>반복되는 Github 초기 세팅</h3><h4>Label 세팅</h4><p>Github을 사용하다 보면 Label 관리의 필요성을 느낄 때가 있습니다. 특히 팀으로 일하는 경우 동일한 규칙에 맞춰서 Label을 정해서 사용할텐데, 매번 새로운 저장소를 만들 때 마다 세팅을 해줘야 합니다.</p><h4>Issue, PR Template 세팅</h4><p>그리고 Issue과 PR(Pull Request)의 경우도 마찬가지입니다. 특히 공개 된 저장소의 경우, 정해진 형식에 맞게 Issue와 PR을 올리는 것이 아니기 때문에 정리가 잘 안되는 경우가 많습니다.</p><h4>한방에 해결</h4><p>그래서 이런 문제를 한번에 해결하고 싶어서, Label 세팅과 Issue, PR Template 이 담긴 저장소를 만들어서 Github 저장소 자체를 템플릿으로 사용할 수 있도록 하였습니다.</p><blockquote>아래 내용을 바탕으로 세팅 된 <a href="https://github.com/modolee/github-initial-settings">Github 저장소</a> 입니다. `Use this template` 버튼으로 바로 이용하셔도 좋고, fork 후 본인에게 맞게 수정한 후 template으로 사용하셔도 좋습니다.</blockquote><h3>Github Label 세팅</h3><h4>Label 이란?</h4><ul><li>Issue, PR 에 붙여서 분류하기 위한 이름표</li></ul><h4>Github 액세스 토큰 발급</h4><ul><li><a href="https://github.com/settings/tokens">https://github.com/settings/tokens</a> 접속</li><li>`Generate new token` 클릭</li><li>원하는 이름 입력</li><li>`scopes`에서 repo 선택</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/991/0*_I3XteOtLxHlVv0N.png" /></figure><h4>Label 정의하기</h4><ul><li>`labels.json` 파일에 JSON Array 형태로 정의</li><li>`name`, `color`, `description` 을 정의할 수 있음</li></ul><pre>[<br> {<br> “name”: “Priority: Critical”,<br> “color”: “8c001a”,<br> “description”: “우선순위 긴급”<br> }<br>]</pre><h4>정의 된 Label 적용하기</h4><ul><li>`액세스 토큰`, `계정명`, `저장소 이름`을 자신의 것으로 변경</li></ul><pre>npx github-label-sync — access-token [액세스 토큰] — labels labels.json [계정명]/[저장소 이름]</pre><ul><li>Label 설정 적용 전</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6vlJE306hgota_46.png" /></figure><ul><li>Label 설정 적용 후</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8gmDd5nlMS268NP2.png" /></figure><h3>Issue Template</h3><ul><li>`Issues` 탭에서 `New issue` 버튼을 눌렀을 때 미리 정의 된 템플릿을 선택할 수 있음</li></ul><h4>Issue Template 정의하기</h4><ul><li>마크다운 형식으로 파일 생성</li><li>`name`, `about`, `title`, `labels`, `assignees`를 미리 지정할 수 있</li><li>labels 의 경우 위에서 정의 한 label name을 지정하면 됨</li></ul><h4>예시</h4><pre>---<br>name: Bug Report Template<br>about: 버그 리포트 템플릿입니다.<br>title: &#39;&#39;<br>labels: &#39;Status: To Do, Priority: Medium, Type: Bugfix/Function, Type: Bugfix/UI&#39;<br>assignees: &#39;&#39;<br>---</pre><pre># 발생 일시</pre><pre># 발생 위치</pre><pre># 증상</pre><pre># 재현 방법</pre><pre># 스크린샷</pre><h4>Issue Template 적용</h4><ul><li>추가 된 파일을 github 원격에 push 한 후 `New issue` 버튼을 누르게 되면 아래와 같이 선택 화면이 나옴</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*WEUjLgeDzxwj_X10.png" /></figure><h3>Pull Request Template</h3><ul><li>마크다운 형식으로 파일 생성</li><li>`pull_request_template.md`로 파일 이름 지정</li></ul><h4>예시</h4><pre># 반영 브랜치</pre><pre># 변경 사항</pre><pre># 확인 방법 (스크린샷 포함)</pre><h4>Pull Request Template 적용</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lw_qsxDFQh4BcrH9.png" /></figure><h3>참고</h3><ul><li><a href="https://github.com/Financial-Times/github-label-sync">github-label-sync</a></li><li><a href="https://docs.github.com/en/free-pro-team@latest/github/building-a-strong-community/using-templates-to-encourage-useful-issues-and-pull-requests">Using templates to encourage useful issues and pull requests</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=931af8740792" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crocusenergy/github-label-issue-pull-request-template-%EC%A0%81%EC%9A%A9%ED%95%98%EA%B8%B0-931af8740792">Github Label, Issue, Pull Request Template 적용하기</a> was originally published in <a href="https://medium.com/crocusenergy">CrocusEnergy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to safely add environmental variables using Bitbucket Pipelines with automated Google App…]]></title>
            <link>https://medium.com/crocusenergy/how-to-safely-add-environmental-variables-using-bitbucket-pipelines-with-automated-google-app-8bf7f5c8dc4f?source=rss----35f311588f8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/8bf7f5c8dc4f</guid>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <category><![CDATA[environment-variables]]></category>
            <category><![CDATA[google-app-engine]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[bitbucket-pipelines]]></category>
            <dc:creator><![CDATA[Jieun Jeon]]></dc:creator>
            <pubDate>Thu, 12 Nov 2020 02:13:59 GMT</pubDate>
            <atom:updated>2020-11-12T02:15:31.756Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to safely add environment variables using Bitbucket Pipelines with automated Google App Engine deployments</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*nl1OhRSEhmbnAAc-PlFRSA.png" /></figure><p>This article is translated based on a medium article written by <a href="https://medium.com/u/aa6389d71adc">modolee</a>. You can check out the original article here: <a href="https://medium.com/crocusenergy/bitbucket-pipelines%EB%A1%9C-google-app-engine%EC%97%90-%EC%9E%90%EB%8F%99-%EB%B0%B0%ED%8F%AC-%EC%8B%9C-%EC%95%88%EC%A0%84%ED%95%98%EA%B2%8C-%ED%99%98%EA%B2%BD%EB%B3%80%EC%88%98-%EC%B6%94%EA%B0%80%ED%95%98%EA%B8%B0-46bb6316fe1d">bitbucket-pipelines로-google-app-engine에-자동-배포-시-안전하게-환경변수-추가하기</a></p><p>Today, I want to introduce a safe way to add environmental variables using Bitbucket Pipelines with automated Google App Engine deployments.</p><h3>Dev/Deployments Environment setup</h3><ul><li>Server : Google App Engine<br>- runtime : custom<br>- env: flex</li><li>Source code management: Bitbucket</li><li>CI/CD: Bitbucket Pipelines</li></ul><h3>Issues</h3><ul><li>Typically, we add environmental variables to the Google App Engine configuration file (app.yaml) by storing them in key:value form in the env_variablesentry.</li><li>Sensitive data such as API key, Auth Token, etc is directly exposed to app.yaml file.</li><li>env_varibles</li><li>You need a solution which dynamically add them at the point when you deploy it, not directly store it to app.yaml file.</li><li>You need to store and access the environmental variables from either place: Bitbucket or GCP.</li></ul><h3>Trying to find solutions…</h3><ul><li>I’ve Googled various ways but I couldn’t find a suitable way to apply it.</li><li>I excluded the following option: store it to Google Datastore and calling API directly from source code, because it seemed to be too dependent on GCP.</li><li>An option to create .env file during the deployment process was working only when App Engine is in a standardenvironment, it was not working with flexenvironment.</li><li>It seemed like this option is the most suitable solution: which is to manually add environment variables to theapp.yaml file during the bitbucket pipelines execution period before deploy it to the App Engine.</li></ul><h3>Solutions</h3><ol><li>Store env variables in Bitbucket</li><li>Create a file that manages names of the env variables, and add it to the project</li><li>Create a script to load the names of the env variables then add them to the app.yamlfile</li><li>Run the script right before you deploy to Goolge App Engine through Bitbucket pipelines</li></ol><h4>Storing env variables in Bitbucket</h4><ul><li>Store all env variables in Bitbucket which were previously stored in app.yamlfile in plain text format</li><li>Go to Bibucket Repository settings &gt; PIPELINES &gt; DEPLOYMENTS page, and add env variables</li><li>Select securedoption. The saved value cannot be revisited after, so please save it in a safe place.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*uzhtvI-Em6codVGIRJxV5A.png" /></figure><h4>Add env variables-list file</h4><ul><li>Create .env.array file in project root</li><li>Add each env variable’s name line by line on the created file that needs to be included on deployment</li></ul><pre>TEST_ENV1 <br>TEST_ENV2 <br>TEST_ENV</pre><h4>Add script to add env variables</h4><ul><li>Create add-env-to-gae-conf.sh file in project root</li><li>Copy and paste the script code below</li></ul><pre>#!/bin/bash# Set default file input/output name<br>FILE_INPUT_NAME=.env.array<br>FILE_OUTPUT_NAME=app.yaml# Set file input/output name, when user add options<br>while getopts &quot;i:o:&quot; opt; do<br>  case $opt in<br>    i)<br>      FILE_INPUT_NAME=$OPTARG ;;<br>    o)<br>      FILE_OUTPUT_NAME=$OPTARG ;;<br>    *) echo &quot;usage: $0 [-i] [-o]&quot; &gt;&amp;2<br>       exit 1 ;;<br>  esac<br>done# Read all environment variables that have to be copied from input file<br>declare env_array=()while IFS= read -r line || [[ &quot;$line&quot; ]]; do<br>  env_array+=(&quot;$line&quot;)<br>done &lt; &quot;${FILE_INPUT_NAME}&quot;# Print all environment variables to output file<br>if [ &quot;${#env_array[@]}&quot; -eq 0 ]; then<br>  echo &quot;There is no environment variables&quot;;<br>else<br>  { printf &quot;\n\n&quot;; printf &quot;env_variables:&quot;; printf &quot;\n&quot;; } &gt;&gt; &quot;${FILE_OUTPUT_NAME}&quot;;for i in &quot;${env_array[@]}&quot;;<br>  do<br>    printf &quot;  %s\n&quot; &quot;${i}: ${!i}&quot; &gt;&gt; &quot;${FILE_OUTPUT_NAME}&quot;;<br>  done<br>fi;</pre><ul><li>Link to the source code repo: <a href="https://github.com/modolee/add-env-to-gae-conf">https://github.com/modolee/add-env-to-gae-conf</a></li><li>Default input file (.env.array), default output file (app.yaml) are configured, and you can modify it with -I, -o option</li><li>Read the input file (read the list of the env variables) then add them to the bottom of the output file in the form of `env_variable_name: value`</li><li>Here we are adding the whole block of env_variables, so if there is a pre-defined env_variables , then you need to remove it.</li><li>Dynamically add the stored env variables to the app.yaml file</li><li>app.yaml file will appear like below:</li></ul><pre>env_variables: <br>TEST_ENV1: test string 1 <br>TEST_ENV2: test string 2 <br>TEST_ENV3: test string 3</pre><h4>Check script to add env variables</h4><ul><li>Run the command below on your local machine to see that the env variables are added to the app.yaml file</li></ul><h4>Update Bitbucket Pipelines deployment configuration: add env variables, add script</h4><ul><li>From bitbucket-pipelines.yml, run add-env-variables script with Google App Engine deployment script</li><li>Install the bash separately using the node:alpine image as a default</li><li>Grant the ability to run the script and try to output it to verify that it has been added with no error after running the script</li></ul><pre>image: node:alpinerun-test: &amp;run-test<br>  step:<br>    name: Run jest unit test<br>    caches:<br>      - node<br>    script:<br>      - yarn<br>      - yarn testdeploy-dev: &amp;deploy-dev<br>  step:<br>    name: Deploy Develop Branch to App Engine<br>    deployment: gcp-dev<br>    script:<br>      - apk add bash<br>      - chmod +x ./add-env-to-gae-conf.sh<br>      - bash ./add-env-to-gae-conf.sh<br>      - cat ./app.yaml<br>      - pipe: atlassian/google-app-engine-deploy:0.7.3<br>        variables:<br>          KEY_FILE: $KEY_FILE<br>          PROJECT: $PROJECT<br>          STOP_PREVIOUS_VERSION: &#39;true&#39;<br>          DEBUG: &#39;true&#39;pipelines:<br>  branches:<br>    master:<br>      - &lt;&lt;: *run-test<br>    develop:<br>      - &lt;&lt;: *run-test<br>      - &lt;&lt;: *deploy-dev</pre><h4>Test it on the source code</h4><ul><li>To check it from the source code, try console.log or return in JSON format: process.env.TEST_ENV1, process.env.TEST_ENV2, process.env.TEST_ENV3</li><li>If you see the values you stored in Bitbucket, that means it is working well.</li></ul><h4>Possible Improvements</h4><ul><li>As mentioned above, it is not working if you already have env_variables in app.yaml file</li><li>It would be better if we improve it to use pre-existing env variables.</li></ul><h3>References</h3><ul><li><a href="https://community.atlassian.com/t5/Bitbucket-Pipelines-questions/Setting-app-engine-app-yaml-env-variables/qaq-p/1248306">Setting app engine app.yaml env variables</a></li><li><a href="https://medium.com/@jorn.verhaegen/environment-variables-with-google-app-engine-and-ci-cd-pipelines-e28b2c038a95">Environment variables with Google App Engine and CI/CD</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bf7f5c8dc4f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crocusenergy/how-to-safely-add-environmental-variables-using-bitbucket-pipelines-with-automated-google-app-8bf7f5c8dc4f">How to safely add environmental variables using Bitbucket Pipelines with automated Google App…</a> was originally published in <a href="https://medium.com/crocusenergy">CrocusEnergy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[NestJS 에서 path alias 설정하기 (feat. TypeORM, Jest)]]></title>
            <link>https://medium.com/crocusenergy/nestjs-path-alias-feat-typeorm-jest-de54ace86444?source=rss----35f311588f8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/de54ace86444</guid>
            <category><![CDATA[typeorm]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[alias]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[modolee]]></dc:creator>
            <pubDate>Wed, 04 Nov 2020 00:37:32 GMT</pubDate>
            <atom:updated>2020-11-04T01:16:13.219Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/0*Xujxi9GPtMEQ_8cZ.png" /></figure><h3>alias 설정 이유</h3><ul><li>상대 경로로 지저분하게 설정되어 있는 경로를 깔끔하게 정리하기 위해서 alias를 사용합니다.</li></ul><h4>alias 설정 전</h4><pre>import { AuthResDto } from ‘../../src/auth/dto/response.dto’;<br>import { AuthService } from ‘../../src/auth/auth.service’;</pre><h4>alias 설정 후</h4><pre>import { AuthResDto } from ‘<a href="http://twitter.com/auth/dto">@auth/dto</a>/response.dto’;<br>import { AuthService } from ‘<a href="http://twitter.com/auth/accounts">@auth/accounts</a>.service’;</pre><h3>프로젝트 구조</h3><ul><li>NestJS를 이용해서 만든 프로젝트의 기본 구조의 대략적으로 아래와 같습니다.</li></ul><pre>./<br>├── package.json<br>├── src<br>│   ├── auth<br>│   │   ├── auth.service.ts<br>│   │   └── auth.service.spec.ts<br>│   ├── app.controller.ts<br>│   ├── app.module.ts<br>│   └── ormconfig.ts<br>├── test<br>│   ├── app.e2e-spec.ts<br>│   └── jest-e2e.json<br>├── tsconfig.json<br>├── tsconfig.paths.json<br>└── tsconfig.paths.json</pre><h3>tsconfig.paths.json</h3><ul><li>기본적인 소스코드에 적용되는 alias 설정</li></ul><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;baseUrl&quot;: &quot;./&quot;,<br>    &quot;paths&quot;: {<br>      &quot;@root/*&quot;: [&quot;./src/*&quot;],<br>      &quot;@auth/*&quot;: [&quot;./src/auth/*&quot;]<br>    }<br>  }<br>}</pre><h3>tsconfig.json</h3><ul><li>tsconfig.paths.json을 상속 받아서 사용</li></ul><pre>{<br>  &quot;extends&quot;: &quot;./tsconfig.paths.json&quot;,<br>  <br>  ... (나머지 설정)<br>  <br>}</pre><ul><li>이렇게 2가지만 설정해도 일반적으로 사용하는데에는 문제가 없습니다.</li></ul><h3>package.json</h3><h4>TypeORM을 위한 설정</h4><ul><li>TypeORM CLI를 이용해서 Migration 명령을 사용하고 있다면 추가 설정이 필요 할 수도 있습니다.</li><li>저는 ormconfig.ts 파일에서 alias를 사용하기 때문에 아래와 같이 옵션을 추가했습니다.</li><li>yarn 또는 npm을 통해서 typeorm cli를 실행 시킬 때 추가 하는 기본적인 명령에 -r tsconfig-paths/register 옵션을 추가합니다.</li></ul><pre>// package.json<br>{<br>  ...<br>  <br>  &quot;scripts&quot;: {<br>    &quot;typeorm&quot;: &quot;node -r tsconfig-paths/register -r ts-node/register ./node_modules/typeorm/cli.js --config src/ormconfig.ts&quot;,<br>    &quot;migration:create&quot;: &quot;yarn typeorm migration:create&quot;,<br>    &quot;migration:run&quot;: &quot;yarn typeorm migration:run&quot;,<br>    &quot;migration:revert&quot;: &quot;yarn typeorm migration:revert&quot;,<br>  }<br>  <br>  ...<br>} </pre><h3>Jest Unit 테스트를 위한 설정</h3><ul><li>yarn test를 이용해 unit 테스트 할 때 에러가 발생한다면, 아래 설정을 추가해야 합니다.</li><li>설정을 추가하면 src/auth/auth.service.spec.ts 파일과 같은 unit 테스트 파일에서 alias를 사용할 수 있습니다.</li><li>package.json과 살짝 다르니 주의하세요.</li><li>경로에 src가 빠진 이유는 rootDir이 기본적으로 src로 설정되어 있기 때문입니다.</li></ul><pre>// package.json<br>{<br>  ...<br>    <br>  &quot;jest&quot;: {<br>     ...<br>     <br>    &quot;rootDir&quot;: &quot;src&quot;,<br>    &quot;moduleNameMapper&quot;: {<br>      &quot;^@root/(.*)$&quot;: &quot;&lt;rootDir&gt;/$1&quot;,<br>      &quot;^@auth/(.*)$&quot;: &quot;&lt;rootDir&gt;/auth/$1&quot;<br>    }<br>    <br>    ...<br>  }<br><br>  ...<br>}</pre><h3>jest-e2e.json</h3><ul><li>Jest End-to-End 테스트를 위한 설정</li><li>yarn test:e2e 실행 시 기본적으로 이 파일의 설정을 따릅니다. 그래서 e2e 테스트에 alias를 사용하려면 해당 파일에 설정을 추가해야합니다.</li><li>Unit 테스트를 위한 설정과 약간 다릅니다.../src가 추가 된 이유는 e2e 테스트 파일에서의 rootDir은 test 디렉터리를 의미합니다. 그래서 실행 코드가 있는 src 디렉터리를 가리키기 위해 ../src을 추가해 줘야 합니다.</li></ul><pre>{<br>  ...<br>  &quot;rootDir&quot;: &quot;.&quot;,<br>  &quot;moduleNameMapper&quot;: {<br>    &quot;^@root/(.*)$&quot;: &quot;&lt;rootDir&gt;/../src/$1&quot;,<br>    &quot;^@auth/(.*)$&quot;: &quot;&lt;rootDir&gt;/../src/auth/$1&quot;<br>  }<br>  <br>  ...<br>}</pre><h3>참고</h3><ul><li><a href="https://jestjs.io/docs/en/configuration.html#modulenamemapper-objectstring-string--arraystring">https://jestjs.io/docs/en/configuration.html#modulenamemapper-objectstring-string--arraystring</a></li><li><a href="https://github.com/typeorm/typeorm/issues/1556#issuecomment-413052095">https://github.com/typeorm/typeorm/issues/1556#issuecomment-413052095</a></li><li><a href="https://kulshekhar.github.io/ts-jest/user/config/">https://kulshekhar.github.io/ts-jest/user/config/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de54ace86444" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crocusenergy/nestjs-path-alias-feat-typeorm-jest-de54ace86444">NestJS 에서 path alias 설정하기 (feat. TypeORM, Jest)</a> was originally published in <a href="https://medium.com/crocusenergy">CrocusEnergy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[파일의 환경 변수를 실제 값으로 교체해 주는 라이브러리 envsub]]></title>
            <link>https://medium.com/crocusenergy/envsub-environment-variables-substitution-library-b855f4f04f90?source=rss----35f311588f8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/b855f4f04f90</guid>
            <category><![CDATA[google-app-engine]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[bitbucket-pipelines]]></category>
            <category><![CDATA[environment-variables]]></category>
            <dc:creator><![CDATA[modolee]]></dc:creator>
            <pubDate>Fri, 30 Oct 2020 01:03:31 GMT</pubDate>
            <atom:updated>2020-10-30T01:03:30.674Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ZMThxnpg2WEnbJq_9x-QLw.png" /></figure><h3>라이브러리를 찾게 된 계기</h3><ul><li>얼마 전 <a href="https://medium.com/crocusenergy/bitbucket-pipelines%EB%A1%9C-google-app-engine%EC%97%90-%EC%9E%90%EB%8F%99-%EB%B0%B0%ED%8F%AC-%EC%8B%9C-%EC%95%88%EC%A0%84%ED%95%98%EA%B2%8C-%ED%99%98%EA%B2%BD%EB%B3%80%EC%88%98-%EC%B6%94%EA%B0%80%ED%95%98%EA%B8%B0-46bb6316fe1d">Bitbucket Pipelines로 Google App Engine에 자동 배포 시 안전하게 환경변수 추가하기</a> 라는 글을 올렸었는데, 해당 글 마지막에 아래와 같은 글을 적어놨습니다.</li></ul><blockquote>- 위에서도 언급했지만, app.yaml 파일에 env_variables 항목이 이미 있는 경우에는 정상적으로 동작하지 않습니다.</blockquote><blockquote>- 이미 존재하는 환경변수도 함께 사용할 수 있는 방식으로 보완하면 더 좋을 것 같습니다.</blockquote><ul><li>Google App Engine으로 작업을 하다가 env_variables 이 외에 또! 유동적으로 추가해줘야 될 부분이 생겼습니다. 그래서 ‘스크립트를 범용적으로 수정해야 되나’ 하고 생각하다가, 혹시나 하고 파일에 있는 변수들을 환경변수에 설정 된 값으로 교체해 주는 라이브러리를 검색해 봤습니다.</li><li>유레카! 놀랍게도 해당 라이브러리가 존재했습니다. 스타 30개 정도를 받은 라이브러리로 많은 사람들이 사용하는 것 같진 않지만, 제가 원하는 기능은 충분히 동작했습니다.</li></ul><h3>라이브러리 소개</h3><ul><li>제가 찾은 라이브러리는 envsub 이라는 npm 라이브러리입니다.</li><li>라이브러리 사용 방법은 여러가지 방법이 있지만 저는 가장 간단한 방법으로 사용했습니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/0*RO6FIHYNOz9gthUB.png" /><figcaption>출처 : <a href="https://www.npmjs.com/package/envsub">https://www.npmjs.com/package/envsub</a></figcaption></figure><h4>사용 방법</h4><ul><li>글로벌 설치 후 실행 (yarn, npm 중 선택해서 실행)</li></ul><pre>yarn add global envsub<br>npm add -g envsub</pre><ul><li>무설치 실행</li></ul><pre>npx envsub</pre><ul><li>설치 후 envsub templateFile outputFile 명령을 실행하면 templateFile에 있던 변수가 환경변수의 값으로 교체가 됩니다.</li></ul><h4>사용 예시</h4><ul><li>파일 생성 intro.template.txt</li></ul><pre>This is ${USER_ID}&#39;s velog.<br>I&#39;m ${NICK_NAME}.</pre><ul><li>터미널에서 환경변수 지정</li></ul><pre>export USER_ID=modolee<br>export NICK_NAME=ironman</pre><ul><li>envsub 실행 (무설치)</li></ul><pre>npx envsub intro.template.txt intro.txt</pre><ul><li>결과 확인 intro.txt</li></ul><pre>This is modolee&#39;s velog.<br>I&#39;m ironman.</pre><h3>응용 방법</h3><ul><li>이것을 이용하면 Bitbucket Pipelines에서 Google App Engine으로 배포 할 때, 환경변수를 외부에 노출시키지 않고 Bitbucket에 저장해서 사용할 수 있습니다.</li><li>템플릿 파일 app.template.yaml</li></ul><pre>runtime: custom<br>env: flex<br>service: auth<br><br>resources:<br>  cpu: 1<br>  memory_gb: 0.5<br>  disk_size_gb: 10<br><br>beta_settings:<br>  cloud_sql_instances: ${DB_CONNECTION_NAME}=tcp:${POSTGRES_PORT}<br><br>env_variables:<br>  POSTGRES_HOST: ${POSTGRES_HOST}<br>  POSTGRES_PORT: ${POSTGRES_PORT}<br>  POSTGRES_DB: ${POSTGRES_DB}<br>  POSTGRES_USER: ${POSTGRES_USER}<br>  POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}</pre><ul><li>Bitbucket Pipeline 정의 파일 bitbucket-pipelines.yml</li></ul><pre>...<br><br>deploy: &amp;deploy<br>  step:<br>    name: Deploy to Google App Engine<br>    deployment: gcp<br>    script:<br>      - npx envsub app.template.yaml app.yaml<br>      - cat ./app.yaml<br>      - pipe: atlassian/google-app-engine-deploy:0.7.3<br>        variables:<br>          KEY_FILE: $KEY_FILE<br>          PROJECT: $PROJECT<br><br>...</pre><ul><li>위 처럼 npx envsub app.template.yaml app.yaml 명령을 배포 전에 추가하여 환경변수 값으로 대체 된 값을 가지고 있는 app.yaml 파일을 유동적으로 만들 수 있습니다.</li><li>이렇게 되면 env_variables 뿐만 아니라 cloud_sql_instances와 같이 노출되면 꺼림칙 한 정보들을 숨길 수 있습니다.</li></ul><h3>참고</h3><ul><li><a href="https://www.npmjs.com/package/envsub">envsub — npm</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b855f4f04f90" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crocusenergy/envsub-environment-variables-substitution-library-b855f4f04f90">파일의 환경 변수를 실제 값으로 교체해 주는 라이브러리 envsub</a> was originally published in <a href="https://medium.com/crocusenergy">CrocusEnergy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I started to use Lodash in the Front end (React JS)]]></title>
            <link>https://medium.com/crocusenergy/how-i-started-to-use-lodash-in-the-front-end-react-js-e465caaa45eb?source=rss----35f311588f8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/e465caaa45eb</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[lodash]]></category>
            <dc:creator><![CDATA[Jieun Jeon]]></dc:creator>
            <pubDate>Thu, 22 Oct 2020 08:01:38 GMT</pubDate>
            <atom:updated>2020-11-09T06:28:20.280Z</atom:updated>
            <content:encoded><![CDATA[<p>Today I want to share how I use Lodash JS library in my Front end code. After I start to use the Loadsh library, I found many advantages to using it. In this post, I want to introduce the below 4 things.</p><ul><li>What is Lodash</li><li>Why you should use Lodash</li><li>How to install</li><li>How I use Lodash</li></ul><h3>What is Lodash</h3><p>Lodash is<strong><em> “A modern JavaScript utility library delivering modularity, performance &amp; extras” (from Loadsh.com)</em></strong> Lodash can cover common manipulation programming for arrays, objects, string, and collections using functional programming paradigm.</p><h3>Why you should use Lodash</h3><p>I found Lodash is very useful when I handle nested array or objects. By using functions supported by Lodash, you can chain the Lodash functions so you can perform complicated array or objects manipulations easily. This can lead your code to have more modularity with less code when you need to deal with a complex data structure.</p><h3>How to install</h3><p>If you want to use Lodash with frameworks (React, Vue, Angular, NodeJs), you can install Lodash via npm by running the following command:</p><pre>npm install — save lodash</pre><p>You can use Loadash by simply importing functions that you want to use:</p><pre>import { get, isEmpty, find, filter, has, debounce } from ‘loadash’;</pre><h3>How I use Lodash</h3><h4>Test if an object or an array is empty or not</h4><pre>isEmpty(obj);</pre><p>isEmpty() accepts only one parameter, an object or an array, and returns true if ‘obj’ is empty and false if not.</p><h4>Test if an array has an item that satisfies a custom condition</h4><pre>find(testArray, function(item number) {<br>   Return item &gt; 0;<br>}, 0);</pre><p>find() accepts three parameters, 1. an array to find, 2. a function to be called until a condition meets, 3. index of the array to start a search. It returns one matching item from the array.</p><h4>Test if an array has multiple items that satisfies a custom condition</h4><pre>filter(testArray, function(item number) {<br>   return number &gt; 0;<br>}</pre><p>filter() accepts two parameters, 1. an array to find,</p><h4>Test Get</h4><pre>const testObj = {‘a’: ‘b’: ‘val’};<br>get(testObj, a.b, ‘default_val’)</pre><p>Get() accepts three parameters, 1. object to get, 2. path to get, 3. default value if nothing found. I found this function useful to define the default value if nothing found from a nested object or array in this simple 1 line code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e465caaa45eb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crocusenergy/how-i-started-to-use-lodash-in-the-front-end-react-js-e465caaa45eb">How I started to use Lodash in the Front end (React JS)</a> was originally published in <a href="https://medium.com/crocusenergy">CrocusEnergy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bitbucket Pipelines로 Google App Engine에 자동 배포 시 안전하게 환경변수 추가하기]]></title>
            <link>https://medium.com/crocusenergy/bitbucket-pipelines%EB%A1%9C-google-app-engine%EC%97%90-%EC%9E%90%EB%8F%99-%EB%B0%B0%ED%8F%AC-%EC%8B%9C-%EC%95%88%EC%A0%84%ED%95%98%EA%B2%8C-%ED%99%98%EA%B2%BD%EB%B3%80%EC%88%98-%EC%B6%94%EA%B0%80%ED%95%98%EA%B8%B0-46bb6316fe1d?source=rss----35f311588f8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/46bb6316fe1d</guid>
            <category><![CDATA[google-app-engine]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[environment-variables]]></category>
            <category><![CDATA[bitbucket-pipelines]]></category>
            <category><![CDATA[dotenv]]></category>
            <dc:creator><![CDATA[modolee]]></dc:creator>
            <pubDate>Tue, 20 Oct 2020 01:02:11 GMT</pubDate>
            <atom:updated>2020-10-24T07:39:27.062Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rij3Q09SNw3L5A3v7UAd0A.png" /></figure><p>Bitbucket Pipelines로 Google App Engine에 자동 배포 시 안전하게 환경변수를 추가하는 방법을 소개합니다.</p><h3>개발/배포 환경</h3><ul><li>서버 : Google App Engine<br>- runtime : custom<br>- env: flex</li><li>소스 관리 : Bitbucket</li><li>CI/CD 툴 : Bitbucket Pipelines</li></ul><h3>문제점</h3><ul><li>일반적으로 Google App Engine 설정 파일 (app.yaml)에 환경 변수를 추가하는 방법은 env_varibles 항목에 key:value 형태로 평문 그대로 저장하는 방식입니다.</li><li>app.yaml 파일에 API Key, Auth Token 등의 노출되면 안되는 정보들이 그대로 노출됩니다.</li><li>app.yaml 파일에 직접 저장하는 방식이 아니라, 배포 시에 동적으로 추가해 주는 방식이 필요합니다.</li><li>Bitbucket 또는 GCP에 환경변수를 저장하고 사용하는 방식 중 한가지를 선택해야 합니다.</li></ul><h3>해결 방법 탐색</h3><ul><li>구글링을 통해서 다양하게 찾아 봤지만, 딱 알맞게 적용할 수 있는 방법은 찾지 못했습니다.</li><li>Google Datastore에 저장하고 소스에서 직접 API를 호출해서 가져오는 방법은 GCP에 너무 종속적인 코드가 되는 것 같아서 제외 했습니다.</li><li>배포 시에 .env 파일을 만드는 방법은 App Engine이 standard 환경 일 때는 동작하지만 flex 환경일 때는 동작하지 않습니다.</li><li>App Engine 배포 전 bitbucket pipelines 스크립트 실행 부분에서 수동으로 환경변수를 app.yaml 파일에 추가해 주는 방법이 그나마 괜찮은 방법 같았습니다.</li></ul><h3>해결 방법</h3><ol><li>Bitbucket에 환경변수를 저장</li><li>저장 된 환경변수 이름을 관리하는 파일을 프로젝트에 추가</li><li>저장 된 환경변수 이름을 불러와서 app.yaml 파일에 추가하는 스크립트 생성</li><li>Bitbucket pipelines를 통해서 Google App Engine으로 배포하기 직전에 해당 스크립트 실행</li></ol><h4>Bitbucket에 환경변수 저장</h4><ul><li>기존에 app.yaml 에 평문으로 저장되어 있던 환경변수를 모두 Bitbucket에 저장합니다.</li><li>Bitbucket의 Repository settings &gt; PIPELINES &gt; Deployments 페이지로 이동하여 환경변수를 추가합니다.</li><li>Secured 옵션을 선택하고 저장 한 값은 다시 확인이 불가능하니 반드시 별도로 저장하시기 바랍니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*H6Ptsh2yO_e1LKqF.png" /></figure><h4>환경변수 목록 파일 추가</h4><ul><li>프로젝트 루트에 .env.array 파일을 생성합니다.</li><li>생성 된 파일에 배포 시 자동으로 추가 할 환경변수 이름을 한 줄에 하나씩 추가합니다.</li></ul><pre>TEST_ENV1<br>TEST_ENV2<br>TEST_ENV3</pre><h4>환경변수 추가 스크립트 추가</h4><ul><li>프로젝트 루트에 add-env-to-gae-conf.sh 파일을 생성합니다.</li><li>아래 스크립트 코드를 복사해 붙여 넣습니다.</li></ul><pre>#!/bin/bash</pre><pre># Set default file input/output name<br>FILE_INPUT_NAME=.env.array<br>FILE_OUTPUT_NAME=app.yaml</pre><pre># Set file input/output name, when user add options<br>while getopts &quot;i:o:&quot; opt; do<br>  case $opt in<br>    i)<br>      FILE_INPUT_NAME=$OPTARG ;;<br>    o)<br>      FILE_OUTPUT_NAME=$OPTARG ;;<br>    *) echo &quot;usage: $0 [-i] [-o]&quot; &gt;&amp;2<br>       exit 1 ;;<br>  esac<br>done</pre><pre># Read all environment variables that have to be copied from input file<br>declare env_array=()</pre><pre>while IFS= read -r line || [[ &quot;$line&quot; ]]; do<br>  env_array+=(&quot;$line&quot;)<br>done &lt; &quot;${FILE_INPUT_NAME}&quot;</pre><pre># Print all environment variables to output file<br>if [ &quot;${#env_array[@]}&quot; -eq 0 ]; then<br>  echo &quot;There is no environment variables&quot;;<br>else<br>  { printf &quot;\n\n&quot;; printf &quot;env_variables:&quot;; printf &quot;\n&quot;; } &gt;&gt; &quot;${FILE_OUTPUT_NAME}&quot;;</pre><pre>for i in &quot;${env_array[@]}&quot;;<br>  do<br>    printf &quot;  %s\n&quot; &quot;${i}: ${!i}&quot; &gt;&gt; &quot;${FILE_OUTPUT_NAME}&quot;;<br>  done<br>fi;</pre><ul><li><a href="https://github.com/modolee/add-env-to-gae-conf">스크립트 저장소 바로가기</a></li><li>기본 입력 파일 (.env.array), 기본 출력 파일 (app.yaml) 이 설정되어 있고, -i, -o 옵션을 통해서 변경 가능합니다.</li><li>입력 파일을 읽어서 해당 파일에 저장 된 환경변수 목록을 읽어 환경변수 이름: 값 형태로 출력 파일 가장 하단에 추가합니다.</li><li>env_variables 항목을 통째로 추가하는 것이기 때문에 기존에 env_variables 항목이 정의되어 있다면 삭제해야 정상적으로 동작합니다.</li><li>실행되는 머신에 저장 된 환경변수를 app.yaml 파일에 유동적으로 추가해 줍니다.</li><li>app.yaml 파일 하단에 아래와 같이 추가 됩니다.</li></ul><pre>env_variables:<br>  TEST_ENV1: test string 1<br>  TEST_ENV2: test string 2<br>  TEST_ENV3: test string 3</pre><h4>환경변수 추가 스크립트 확인</h4><ul><li>로컬 머신에서 아래 명령을 실행하면 app.yaml 파일에 환경변수가 추가 되는 것을 확인할 수 있습니다.</li></ul><pre>export TEST_ENV1=&#39;test string 1&#39;<br>export TEST_ENV2=&#39;test string 2&#39;<br>export TEST_ENV3=&#39;test string 3&#39;</pre><pre>bash add-env-to-gae-conf.sh</pre><h4>Bitbucket Pipelines 배포 설정에 환경변수 추가 스크립트 실행 추가</h4><ul><li>bitbucket-pipelines.yml 파일 중 Google App Engine 배포 단계의 스크립트에 환경변수 추가 스크립트를 실행합니다.</li><li>node:alpine 이미지를 기본으로 사용하여 bash를 별도로 설치해 줍니다.</li><li>스크립트의 실행 권한을 주고, 스크립트를 실행한 후 정상적으로 추가 됐는지 확인하기 위해 출력합니다.</li></ul><pre>image: node:alpine</pre><pre>run-test: &amp;run-test<br>  step:<br>    name: Run jest unit test<br>    caches:<br>      - node<br>    script:<br>      - yarn<br>      - yarn test</pre><pre>deploy-dev: &amp;deploy-dev<br>  step:<br>    name: Deploy Develop Branch to App Engine<br>    deployment: gcp-dev<br>    script:<br>      - apk add bash<br>      - chmod +x ./add-env-to-gae-conf.sh<br>      - bash ./add-env-to-gae-conf.sh<br>      - cat ./app.yaml<br>      - pipe: atlassian/google-app-engine-deploy:0.7.3<br>        variables:<br>          KEY_FILE: $KEY_FILE<br>          PROJECT: $PROJECT<br>          STOP_PREVIOUS_VERSION: &#39;true&#39;<br>          DEBUG: &#39;true&#39;</pre><pre>pipelines:<br>  branches:<br>    master:<br>      - &lt;&lt;: *run-test<br>    develop:<br>      - &lt;&lt;: *run-test<br>      - &lt;&lt;: *deploy-dev</pre><h3>코드에서 확인</h3><ul><li>코드에서 확인하기 위해 process.env.TEST_ENV1, process.env.TEST_ENV2, process.env.TEST_ENV3 를 console.log에 찍거나 JSON 형태로 반환해 봅니다.</li><li>Bitbucket에 저장 한 값이 나온다면 정상적으로 동작하는 것입니다.</li></ul><h3>보완이 필요한 점</h3><ul><li>위에서도 언급했지만, app.yaml 파일에 env_variables 항목이 이미 있는 경우에는 정상적으로 동작하지 않습니다.</li><li>이미 존재하는 환경변수도 함께 사용할 수 있는 방식으로 보완하면 더 좋을 것 같습니다.</li></ul><h3>참고</h3><ul><li><a href="https://community.atlassian.com/t5/Bitbucket-Pipelines-questions/Setting-app-engine-app-yaml-env-variables/qaq-p/1248306">Setting app engine app.yaml env variables</a></li><li><a href="https://medium.com/@jorn.verhaegen/environment-variables-with-google-app-engine-and-ci-cd-pipelines-e28b2c038a95">Environment variables with Google App Engine and CI/CD</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46bb6316fe1d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crocusenergy/bitbucket-pipelines%EB%A1%9C-google-app-engine%EC%97%90-%EC%9E%90%EB%8F%99-%EB%B0%B0%ED%8F%AC-%EC%8B%9C-%EC%95%88%EC%A0%84%ED%95%98%EA%B2%8C-%ED%99%98%EA%B2%BD%EB%B3%80%EC%88%98-%EC%B6%94%EA%B0%80%ED%95%98%EA%B8%B0-46bb6316fe1d">Bitbucket Pipelines로 Google App Engine에 자동 배포 시 안전하게 환경변수 추가하기</a> was originally published in <a href="https://medium.com/crocusenergy">CrocusEnergy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bitbucket Pipelines로 Google App Engine에 자동 배포하기]]></title>
            <link>https://medium.com/crocusenergy/deploy-to-gae-using-bitbucket-pipelines-70395422bc4e?source=rss----35f311588f8a---4</link>
            <guid isPermaLink="false">https://medium.com/p/70395422bc4e</guid>
            <category><![CDATA[google-app-engine]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[bitbucket-pipelines]]></category>
            <category><![CDATA[bitbucket]]></category>
            <dc:creator><![CDATA[modolee]]></dc:creator>
            <pubDate>Mon, 19 Oct 2020 03:31:16 GMT</pubDate>
            <atom:updated>2020-10-19T14:34:44.966Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-kahYlyY9d2hiLlxmNWpA.png" /></figure><p>새롭게 시작하는 프로젝트에 적용 한 CI/CD 구축 과정을 소개해 보려고 합니다.</p><h3>개발/배포 환경</h3><ul><li>서버 : Google App Engine</li><li>소스 관리 : Bitbucket</li><li>CI/CD 툴 : Bitbucket Pipelines</li></ul><h3>사전 준비</h3><ul><li>GCP에서 프로젝트를 위한 App Engine 생성</li><li>프로젝트에 App Engine 배포를 위한 기본 설정 파일(app.yaml) 생성</li><li>Bitbucket에 프로젝트 소스 저장</li></ul><h3>GCP IAM 서비스 계정 생성</h3><ul><li>GCP 콘솔에서 IAM 및 관리자 &gt; 서비스 계정 페이지로 이동</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/255/1*XbkbvLdOyYZgroMEbYtmCg.png" /></figure><h4>서비스 계정 만들기</h4><ul><li><strong>서비스 계정 세부 정보</strong><br><strong>- </strong>서비스 계정 이름 : 지정하고자 하는 계정 이름 (한글 허용 안함)<br>- 서비스 계정 ID : 기본으로 지정 됨 (변경 가능)<br>- 서비스 계정 설명 : 계정에 대한 설명 (한글 허용)</li><li><strong>서비스 계정 권한</strong> : 아래의 3가지 권한을 추가해줘야 서비스 계정으로 자동 배포 가능<br>- App Engine &gt; 배포자<br>- 프로젝트 &gt; 편집자<br>- Cloud Storage &gt; 저장소 개체 생성자</li><li><strong>사용자에게 이 서비스 계정에 대한 액세스 권한 부여</strong> : SKIP</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/558/1*B9UdweoZulE9-arZu3lbAg.png" /></figure><h4>Keyfile 다운로드</h4><ul><li>위에서 생성 한 계정을 서비스 계정 목록에서 확인</li><li>해당 계정의 가장 오른쪽에 있는 작업에 있는 더보기를 눌러 키 만들기 선택</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/128/1*WNRpajvvHT9-JL-JTdZSAw.png" /></figure><ul><li>키 유형 : JSON</li><li>만들기를 누르면 JSON 파일이 다운로드 됨</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*cWSOs5w5tbU98ZLKRr91yA.png" /></figure><h3>Bitbucket 설정</h3><h4>Bitbucket Pipelines 활성화</h4><ul><li>Bitbucket에서 해당 프로젝트 &gt; Repository settings &gt; PIPELINES &gt; Settings 페이지로 이동</li><li>Enable Pipelines 를 활성화</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*B5vWUvFxWKmv3h97MLtQFQ.png" /></figure><h4>Keyfile base64 인코딩</h4><ul><li>위에서 다운로드 받은 JSON 파일을 통째로 base64로 인코딩</li></ul><pre>base64 keyfile_name.json</pre><ul><li>인코딩 된 문자열이 출력되면 해당 문자열 전체를 복사</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xylPeKsykdURLycfMzH9NQ.png" /></figure><h4>Bitbucket Repository variables 설정</h4><ul><li>Bitbucket에서 해당 프로젝트 &gt; Repository settings &gt; PIPELINES &gt; Repository variables 페이지 로 이동</li><li>Name / Value 쌍으로 입력<br>- KEY_FILE / 위에서 base64 로 인코딩 한 문자열<br>- PROJECT / App Engine이 설정 된 GCP 프로젝트 ID (프로젝트 이름과 ID는 다를 수 있음)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*qEHLzURoILXx-HgZAtHleQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/625/1*DrDrpGHf_mAi68HvMY5dUw.png" /></figure><ul><li>설정 된 Variables 는 pipelines 설정 파일에서 사용 가능 (예: $KEY_FILE, $PROJECT)</li></ul><h4>Deployments 환경 별 variables 설정 (선택)</h4><ul><li>Repository settings &gt; PIPELINES &gt; Deployments 페이지로 이동</li><li>Test environments, Staging environments, Production environments 가 기본적으로 설정되어 있음</li><li>environment는 추가/수정 가능하며, environment 마다 variables 설정이 가능</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*aZ7jkWyV1V5vwQE53-VYYQ.png" /></figure><h3>Bitbucket Pipelines 파일 작성</h3><ul><li>프로젝트 루트에 bitbucket-pipelines.yml파일 생성</li></ul><pre># develop 브랜치에 PUSH하면 Unit Test를 실행하고 App Engine에 배포 되는 설정</pre><pre>image: node:alpine<br><br>run-test: &amp;run-test<br>  step:<br>    name: Run jest unit test<br>    caches:<br>      - node<br>    script:<br>      - yarn<br>      - yarn test<br><br>deploy-dev: &amp;deploy-dev<br>  step:<br>    name: Deploy Develop Branch to App Engine<br>    deployment: gcp-dev<br>    script:<br>      - pipe: atlassian/google-app-engine-deploy:0.7.3<br>        variables:<br>          KEY_FILE: $KEY_FILE<br>          PROJECT: $PROJECT<br>          STOP_PREVIOUS_VERSION: &#39;true&#39;<br>          DEBUG: &#39;true&#39;<br><br>pipelines:<br>  branches:<br>    master:<br>      - &lt;&lt;: *run-test<br>    develop:<br>      - &lt;&lt;: *run-test<br>      - &lt;&lt;: *deploy-dev</pre><h4>파일 검증</h4><ul><li>아래 URL에서 bitbucket-pipelines.yml 파일에 작성한 내용이 문법적으로 이상이 없는지 확인 가능</li><li><a href="https://bitbucket-pipelines.prod.public.atl-paas.net/validator">https://bitbucket-pipelines.prod.public.atl-paas.net/validator</a></li></ul><h3>자동 배포</h3><h4>소스 PUSH</h4><ul><li>위의 과정을 모두 따라 했다면, 수정 및 추가 된 파일을 모두 COMMIT 한 후 원격의 develop 브랜치에 PUSH 합니다.</li></ul><h4>자동 배포 확인</h4><ul><li>해당 프로젝트 &gt; Pipelines 페이지 로 이동하면 develop 브랜치에서 배포가 진행되는 것을 확인할 수 있습니다.</li><li>각 단계를 클릭하면 상세 실행 명령을 확인할 수 있습니다.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xl3HXp8gw53WudHzy_0jJQ.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70395422bc4e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/crocusenergy/deploy-to-gae-using-bitbucket-pipelines-70395422bc4e">Bitbucket Pipelines로 Google App Engine에 자동 배포하기</a> was originally published in <a href="https://medium.com/crocusenergy">CrocusEnergy</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>