<?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[Stories by Danny Kim on Medium]]></title>
        <description><![CDATA[Stories by Danny Kim on Medium]]></description>
        <link>https://medium.com/@0916dhkim?source=rss-3c26c3f84101------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Stories by Danny Kim on Medium</title>
            <link>https://medium.com/@0916dhkim?source=rss-3c26c3f84101------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 00:59:36 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@0916dhkim/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[프리즈마 스키마에서 CMS를 생성할 수 있을까?]]></title>
            <link>https://medium.com/prisma-korea/%ED%94%84%EB%A6%AC%EC%A6%88%EB%A7%88-%EC%8A%A4%ED%82%A4%EB%A7%88%EC%97%90%EC%84%9C-cms%EB%A5%BC-%EC%83%9D%EC%84%B1%ED%95%A0-%EC%88%98-%EC%9E%88%EC%9D%84%EA%B9%8C-c111c7b30599?source=rss-3c26c3f84101------2</link>
            <guid isPermaLink="false">https://medium.com/p/c111c7b30599</guid>
            <category><![CDATA[cms]]></category>
            <category><![CDATA[prisma]]></category>
            <dc:creator><![CDATA[Danny Kim]]></dc:creator>
            <pubDate>Thu, 17 Feb 2022 04:23:51 GMT</pubDate>
            <atom:updated>2022-03-03T04:10:35.424Z</atom:updated>
            <content:encoded><![CDATA[<p>스키마에 꼭 맞는 타입스크립트 클라이언트를 생성해 주는 것은 프리즈마가 다른 ORM보다 돋보이게 해주는 장점입니다. 그래서 프리즈마가 제공하는 인터페이스를 사용할 때는 복잡한 쿼리를 작성해도 타입을 걱정하는 일이 거의 없죠. 놀랍게도 프리즈마의 코드 제너레이터 로직은 확장 가능하게 설계되어서, 프리즈마 클라이언트 이외의 코드도 생성하게 만드는게 가능합니다.</p><p>이런 생각의 연장선으로 프리즈마가 CMS를 생성하게 해보자는 시도를 해보았습니다. 아직 프로젝트는 개념 증명 단계지만, 성공한다면 백오피스나 사내 어드민 페이지로 활용하는게 가능할 것으로 기대됩니다.</p><h3>참고한 프로젝트</h3><p>이미 시중에 프리즈마를 활용한 CMS들이 존재하기 때문에, 그 중 눈에 띄는 프로젝트들부터 분석해 보았습니다.</p><h4>KeystoneJS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Plgi1yJ35JtSKRgXJlZQmg.png" /></figure><p>KeystoneJS는 ORM이 내장된 headless CMS입니다. Keystone schema API로 데이터베이스를 디자인하면 GraphQL 서버와 Admin UI를 전부 생성해주는 굉장한 개발편의성을 자랑합니다. 2021년에는 프리즈마를 데이터베이스 어댑터로 사용하는걸 지원하면서 다른 headless CMS 경쟁자들과는 차원이 다르다는걸 보여줬습니다. Keystone은 이렇게 우수한 프레임워크지만 데이터베이스를 직접 관리하는 이상, 기존에 있던 db에 붙여서 사용하는건 힘들다는 한계가 있었습니다.</p><h4>PalJS</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yGvlcGldVzdZSWaJ6-zLAg.png" /></figure><p>개인 개발자가 시작한 GraphQL API + Admin UI 생성도구입니다. 풀스택을 한번에 해결해버린다는 점에서 Keystone과 유사하지만, PalJS는 프리즈마 제너레이터라는 점에서 차별점이 있습니다. 프리즈마 스키마만 있다면 어떤 프로젝트에든 붙여서 쓸 수 있고, prisma instrospection과 조합하면 매우 유연하게 적용할 수 있습니다. 하지만 UI코드가 컴포넌트 단위로 생성되기 때문에 커스텀한 UI를 만드는데에 한계가 있었습니다.</p><h3>prisma-generator-proto</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W217F-gDKSBtF1TWkB51vQ.png" /></figure><p>기존 프리즈마 기반 CMS들의 한계점을 극복하기 위해서는 어떻게 설계하는게 좋을지 고민한 결과 prisma-generator-proto 라는 프로토타입 프로젝트를 만들게 되었습니다.</p><h4>프리즈마 제너레이터 사용</h4><p>CMS는 그 자체로 하나의 서비스가 되는 경우도 있지만, 다른 서비스의 데이터를 관리하기 위한 목적으로 사용하는 경우가 많습니다. 그렇다면 이미 존재하는 서비스에 쉽게 붙일 수 있게 설계된 CMS가 범용성에서 우위를 차지할 수 있다고 볼 수 있습니다. Keystone처럼 스스로 데이터베이스 스키마와 migration까지 전부 관리하는 도구는 기존 프로젝트에 붙이기 힘들죠. prisma generate 커맨드에서 생성되는 CMS라면 훨씬 도입하는데 부담이 적을것이라고 판단했습니다.</p><h4>UI는 리액트 훅으로 제공</h4><p>PalJS와 같이 단번에 admin UI 전체가 생성되는건 확실히 편리하지만, 제품이 성장함에 따라 UI를 커스텀 해야할 필요가 생기는 시점이 옵니다. Material UI 같은 컴포넌트 라이브러리에서 제공하는 UI를 커스텀 해보려고 시도해보신 분들은 공감하시겠지만 패키지로 제공되는 컴포넌트를 입맛대로 수정하는건 꽤나 번거로운 일입니다. 그래서 prisma-generator-proto 는 UI를 만드는데 필요한 데이터와 기능만 리액트 훅으로 제공해서 admin UI 제작이 쉽지만 충분히 유연하도록 만들었습니다.</p><h3>작동원리</h3><p>prisma-generator-proto 를 포함한 프리즈마 제너레이터들은 모두 비슷한 방식으로 작동합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Isp4WTRgx5r0fcvi1trfAQ.png" /></figure><h4>프리즈마 스키마</h4><p>시작은 프리즈마의 핵심이라고 할 수 있는 schema.prisma 파일부터입니다.</p><pre>datasource db {<br>  url      = env(&quot;DATABASE_URL&quot;)<br>  provider = &quot;postgresql&quot;<br>}</pre><pre>generator client {<br>  provider = &quot;prisma-client-js&quot;<br>}</pre><pre>model User {<br>  id        Int      <a href="http://twitter.com/id">@id</a> <a href="http://twitter.com/default">@default</a>(autoincrement())<br>  email     String   <a href="http://twitter.com/unique">@unique</a><br>  name      String?<br>  posts     Post[]<br>}</pre><pre>model Post {<br>  id        Int      <a href="http://twitter.com/id">@id</a> <a href="http://twitter.com/default">@default</a>(autoincrement())<br>  title     String   <a href="http://twitter.com/db">@db</a>.VarChar(255)<br>  author    User?    <a href="http://twitter.com/relation">@relation</a>(fields: [authorId], references: [id])<br>  authorId  Int?<br>}</pre><p>위의 예시에서 볼 수 있듯이 schema.prisma 파일은 세 부분으로 나누어져 있습니다.</p><ul><li>datasource: 데이터베이스 연결 설정입니다.</li><li>model: 데이터 모델 정의입니다.</li><li>generator: 이 스키마를 활용하는 제너레이터를 설정합니다. 기본적으로 prisma-client-js 라는 제너레이터를 사용해서 프리즈마 클라이언트를 생성하게 되는데, 추가적으로 다른 제너레이터를 실행하도록 설정할 수 있습니다.</li></ul><p>프리즈마 사용자는 스키마를 직접 작성할 수도 있고, prisma introspection을 사용해서 기존 db에서 스키마를 뽑아내는 것도 가능합니다.</p><h4>prisma generate</h4><p>prisma generate 커맨드는 schema.prisma 파일에서 설정해준 제너레이터들을 차례로 실행합니다. 스키마를 파싱하는 작업은 프리즈마가 담당하며, 파싱된 결과물인 DMMF가 각 제너레이터에 전달됩니다. DMMF에는 다음과 같은 자료가 JS 객체 형태로 들어있습니다:</p><ul><li>모든 모델 리스트</li><li>각 모델 안에 들어있는 필드 리스트</li><li>각 필드의 타입, 초기값, nullable 유무</li><li>모델 사이의 association</li></ul><p>또한, 프리즈마는 output 디렉토리가 어디로 설정되어있는지도 제너레이터에 전달해주기 때문에 제너레이터를 작성하는 개발자는 DMMF를 이용해서 output 디렉토리에 원하는 파일을 쓰기만 하면 됩니다!</p><h3>진행상황</h3><p>prisma-generator-proto 가 현재 생성할 수 있는 코드는 다음과 같습니다.</p><h4>서버 코드 생성</h4><p>CRUD용 route handler들을 생성해서 Express 라우터 형태로 제공하며, 서버 자체는 생성해주지 않습니다.</p><p>사용 예시:</p><pre>import express from &quot;express&quot;;<br>import { router } from &quot;../__generated__&quot;;</pre><pre>const app = express();</pre><pre>app.use(express.json());</pre><pre>// 제너레이터가 생성한 route handler을 사용.<br>app.use(&quot;/api&quot;, router);</pre><pre>app.listen(3001, () =&gt; {<br>  console.log(&quot;Listening...&quot;);<br>});</pre><h4>클라이언트 코드 생성</h4><p>생성된 API handler를 활용하는 리액트 훅을 제공합니다. 서버와 마찬가지로 프론트 엔드 프로젝트 자체를 생성해주지는 않습니다.</p><p>사용 예시 (모델 이름이 Country 인 경우):</p><pre>import Form from &quot;../components/Form&quot;;<br>import React from &quot;react&quot;;<br>import Table from &quot;../components/Table&quot;;<br>import styles from &quot;../styles/DataScreen.module.css&quot;;<br>import { useCountry } from &quot;../__generated__/hooks&quot;;</pre><pre>const Countries = () =&gt; {<br>  // 생성된 훅을 사용해서 CRUD 가능.<br>  const [countries, addHandler, formState, setFormState] = useCountry();</pre><pre>return (<br>    &lt;div className={styles.screen}&gt;<br>      &lt;Form<br>        name=&quot;Country&quot;<br>        keys={[&quot;name&quot;, &quot;population&quot;, &quot;continentId&quot;, &quot;isUnMember&quot;]}<br>        onSubmit={addHandler}<br>        state={formState}<br>        setState={setFormState}<br>      /&gt;</pre><pre>      &lt;Table<br>        name=&quot;Country&quot;<br>        list={countries}<br>        keys={[&quot;id&quot;, &quot;name&quot;, &quot;population&quot;, &quot;continentId&quot;, &quot;isUnMember&quot;]}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>};</pre><pre>export default Countries;</pre><h4>NPM 패키지</h4><p><a href="https://www.npmjs.com/package/@prisma-korea/prisma-generator-proto">prisma-generator-proto</a> 는 NPM에서 다운받으실 수 있습니다.</p><p>소스코드는 <a href="https://github.com/prisma-korea/prisma-generator-proto">GitHub 리포</a> 에 공개되어 있습니다.</p><h3>다른 아이디어</h3><p>저는 CMS를 만들었지만, 다른 사람들이 만든 신기한 제너레이터들도 구경해보고 싶으시다면 이 <a href="https://www.prisma.io/docs/concepts/components/prisma-schema/generators#community-generators">리스트도</a> 살펴보세요!</p><p>프리즈마 코리아 커뮤니티에서도 다양한 시도를 하고 있으니 직접 참여해보고 싶으시다면 카카오톡 오픈채팅에서 문의해주세요.</p><p><em>Originally published at </em><a href="https://0916dhkim.github.io/posts/ckzqfz7v648780ak1368tem43"><em>https://0916dhkim.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c111c7b30599" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prisma-korea/%ED%94%84%EB%A6%AC%EC%A6%88%EB%A7%88-%EC%8A%A4%ED%82%A4%EB%A7%88%EC%97%90%EC%84%9C-cms%EB%A5%BC-%EC%83%9D%EC%84%B1%ED%95%A0-%EC%88%98-%EC%9E%88%EC%9D%84%EA%B9%8C-c111c7b30599">프리즈마 스키마에서 CMS를 생성할 수 있을까?</a> was originally published in <a href="https://medium.com/prisma-korea">Prisma Korea</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[모노리포에서 Prisma 사용하기]]></title>
            <link>https://0916dhkim.medium.com/%EB%AA%A8%EB%85%B8%EB%A6%AC%ED%8F%AC%EC%97%90%EC%84%9C-prisma-%EC%82%AC%EC%9A%A9%ED%95%98%EA%B8%B0-fb811c189997?source=rss-3c26c3f84101------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb811c189997</guid>
            <category><![CDATA[monorepo]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[prisma]]></category>
            <dc:creator><![CDATA[Danny Kim]]></dc:creator>
            <pubDate>Tue, 18 Jan 2022 04:14:43 GMT</pubDate>
            <atom:updated>2022-01-18T04:14:43.869Z</atom:updated>
            <content:encoded><![CDATA[<p>프리즈마는 차원이 다른 개발자 경험을 제공하는 타입스크립트 ORM입니다. 대부분의 경우 프리즈마는 설정이 필요 없지만, 모노리포에 프리즈마를 추가하는 작업은 직관적이지 않을 수 있습니다. 이 포스트에서는 프리즈마를 모노리포 환경에서 사용하는 법을 다룹니다.</p><h3>간단한 프리즈마 소개</h3><p>프리즈마에는 크게 두가지 중요한 개념이 있습니다. <a href="https://www.prisma.io/docs/concepts/components/prisma-schema">스키마</a> 그리고 <a href="https://www.prisma.io/docs/concepts/components/prisma-client">클라이언트</a> 인데요:</p><ul><li>프리즈마 스키마는 데이터 모델과 데이터베이스 설정을 정의하는 텍스트 파일이며, 이렇게 생겼습니다:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f8cf7921bfb8b659eca4b76848ae944/href">https://medium.com/media/3f8cf7921bfb8b659eca4b76848ae944/href</a></iframe><ul><li>이 스키마를 이용해서 프리즈마는 @prisma/client 라는 패키지를 생성하는데, 이 패키지가 ORM의 타입지원과 기능을 제공합니다:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/208716925538604eb33d2c88a3c3e747/href">https://medium.com/media/208716925538604eb33d2c88a3c3e747/href</a></iframe><h3>그렇다면 여러 패키지에서 하나의 @prisma/client를 돌려 쓰려면 어떻게 해야 하나요?</h3><p>모노리포 워크스페이스 구조가 이런 식으로 생겼다고 해봅시다:</p><pre>- Project Root<br>  - apps<br>    - dashboard<br>  - libs<br>    - core</pre><p>생성된 프리즈마 클라이언트를 공유하려면 일단 프리즈마 스키마를 별도의 패키지에 이렇게 집어넣습니다:</p><pre>- Project Root<br>  - apps<br>    - dashboard<br>  - libs<br>    - core<br>    - shared-prisma<br>      - prisma<br>        - schema.prisma<br>      - src<br>        - index.ts</pre><p>이제 prisma generate 커맨드를 사용해서 @prisma/client를 생성하고, 그 생성된 클라이언트를 libs/shared-prisma/src/index.ts 모듈에서 re-export 해주면 됩니다:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9b2563b50d45e69bc908dcf58c0cc11/href">https://medium.com/media/a9b2563b50d45e69bc908dcf58c0cc11/href</a></iframe><p>이렇게 설정해두면 다른 패키지에서 공유된 프리즈마 클라이언트를 import 할 수 있습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f114b495fa64e3ff7344eadb2ac8c2b1/href">https://medium.com/media/f114b495fa64e3ff7344eadb2ac8c2b1/href</a></iframe><h3>Nx 사용시 주의사항</h3><p><a href="https://nx.dev/structure/buildable-and-publishable-libraries">buildable 혹은 publishable</a> 라이브러리를 사용하지 않는다면, 모든 의존성이 워크스페이스에 설치됩니다. 상황에 따라 이게 편할 수도 있지만 정말 불편할 수도 있습니다.</p><ul><li>좋은 경우: @prisma/client가 워크스페이스에 설치되기 때문에 별도로 shared-prisma에서 re-export를 할 필요가 없습니다. 모든 패키지에서 이미 @prisma/client에 접근 가능합니다.</li><li>안좋은 경우: 모노리포 안에 서로 다른 프리즈마 스키마를 (따라서 다른 프리즈마 클라이언트를) 사용하는 앱이 여러개 있는 경우, Nx의 이러한 구조가 골치아픕니다. 각각의 프리즈마 스키마에서 @prisma/client를 생성할 때마다 전부 워크스페이스의 @prisma/client를 덮어쓰기 때문입니다. 이 문제를 해결하기 위해서는shared-prisma를 독립적인 package.json과 node_modules를 가진 buildable Nx 라이브러리로 만들어줘야합니다.</li></ul><p><em>Originally published at </em><a href="https://0916dhkim.github.io/posts/ckyjl0ypl723309larum2rj0o"><em>https://0916dhkim.github.io</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb811c189997" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[리액트 서버 컴포넌트와 프리즈마]]></title>
            <link>https://medium.com/prisma-korea/%EB%A6%AC%EC%95%A1%ED%8A%B8-%EC%84%9C%EB%B2%84-%EC%BB%B4%ED%8F%AC%EB%84%8C%ED%8A%B8%EC%99%80-%ED%94%84%EB%A6%AC%EC%A6%88%EB%A7%88-c1652a997927?source=rss-3c26c3f84101------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1652a997927</guid>
            <category><![CDATA[react-server-component]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[prisma]]></category>
            <dc:creator><![CDATA[Danny Kim]]></dc:creator>
            <pubDate>Wed, 29 Dec 2021 03:11:47 GMT</pubDate>
            <atom:updated>2021-12-29T15:22:06.446Z</atom:updated>
            <content:encoded><![CDATA[<p>리액트 18버전에서 가장 관심을 많이 받고있는 기능은 단연 서버 컴포넌트입니다 (RSC). 이전까지는 페이지 전체를 서버에서 렌더하는 server-side rendering (SSR)이 주목받았었지만 서버 컴포넌트를 사용하게 되면 페이지의 일부만 서버에서 렌더한 후 페이지에 주입하는게 가능합니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wP58fIKdK8hsF3yY.png" /><figcaption>Source: <a href="https://www.freecodecamp.org/news/react-server-components/">https://www.freecodecamp.org/news/react-server-components/</a></figcaption></figure><p>일반적인 웹앱의 경우 API를 통해 데이터베이스의 정보를 받아오는데요, 서버 컴포넌트를 사용하면 REST API (혹은 GraphQL API)를 통하지 않고도 필요한 정보를 렌더할 수 있다는 장점이 있습니다. 이건 기존 SSR에서도 충분히 가능한 부분이지만, SSR로는 첫 페이지 렌더만 서버에서 이뤄지는 반면에 서버 컴포넌트는 페이지를 받아오고 난 이후에도 비동기적으로 개별 컴포넌트를 서버에서 받아올 수 있다는게 차이점입니다.</p><h3>프리즈마 현황</h3><p>리액트의 이러한 변화에 맞춰 프리즈마 팀에서도 RSC에 대한 지원을 준비중입니다.</p><ul><li>Npm에 <a href="https://www.npmjs.com/package/react-prisma">react-prisma</a> 패키지 공개.</li><li>프리즈마 + RSC 데모 <a href="https://youtu.be/ATBdP-Yfaec?t=1482">영상과</a> <a href="https://www.prisma.io/blog/database-access-in-react-server-components-r2xgk9aztgdf">포스트</a> 공개.</li></ul><h3>데모 소스코드 뜯어보기</h3><p>이제 프리즈마 팀과 리액트 팀이 만든 데모의 소스코드를 뜯어보며 서버 컴포넌트는 어떤식으로 구현되는지 알아봅시다!</p><h4>구조</h4><p>데모용으로 만들어진 노트 정리 앱의 백엔드는 Express 그리고 프론트엔드는 (당연히) 리액트로 만들어져 있습니다. 데이터베이스는 프리즈마와 Sqlite3를 사용했네요. 프로젝트 구조는 다음과 같습니다:</p><ul><li>server<br>- api.server.js</li><li>src<br>- index.client.js<br>- LocationContext.client.js<br>- Cache.client.js<br>- Root.client.js<br>- db.server.js<br>- App.server.js<br>- 기타 컴포넌트 모듈들.</li></ul><h4>server/api.server.js</h4><p>모든 서버 로직은 이 모듈 안에 들어있습니다. HTML을 반환하는 경로는 / 하나 뿐이며, 따라서 실질적으로 이 앱은 single page application (SPA) 입니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*nogp_TWSTKpUWjj3bEYMIA.png" /></figure><p>특이한건 /react 경로입니다. GET /react는 흥미롭게도 JSON이나 HTML이 아닌 serialize 된 RSC를 반환합니다. SSR의 경우 HTML과 JS를 반환하고 REST API의 경우 JSON을 반환하는 점과 대비됩니다. 이렇게 클라이언트로 전달된 RSC는 react-server-dom-webpack 이라는 패키지를 사용해서 deserialize 됩니다.</p><h4>src/LocationContext.client.js</h4><p>이 앱은 전역 상태로 location이라는 상태를 가지고 있습니다 (window.location과는 별개). {selectedId, isEditing, searchText} 의 형태인데, 사견으로는 location 보다 appState 정도의 이름이 더 정확하지 않았을까 싶습니다. 해당 상태는 LocationContext에 저장되며, Provider은 Root.client.js에서 사용됩니다.</p><p>주목할 점으로, 클라이언트가 서버에 /react 요청을 보낼 때 location을 X-Location이라는 헤더에 담아서 보냅니다. 이렇게 전달된 location object는 &lt;App&gt; 컴포넌트를 렌더할 때 props로 사용됩니다.</p><h4>src/Cache.client.js</h4><p>리액트 18에 추가될 가능성이 있는 또 다른 기능으로 <a href="https://github.com/reactwg/react-18/discussions/25">suspense cache</a>가 있고, 이 데모 앱에서 사용되었습니다. 이 모듈에 정의된 useServerResponse 훅은 /react 응답 값을 react-server-dom-webpack 패키지를 사용해 deserialize 한 후 suspense cache에 넣습니다. 이후 같은 location으로 /react에 요청을 보낼 일이 있다면 캐싱된 컴포넌트를 재사용합니다. 새로운 노트를 추가하거나 기존 노트를 지우는 등 cache invalidation이 필요한 경우 이 모듈에 정의된 useRefresh 훅을 통해서 캐시를 refresh 할 수 있습니다.</p><h4>src/Root.client.js</h4><p>이 리액트 앱의 최상위 컴포넌트입니다. index.client.js 모듈에서 createRoot 함수를 사용해 DOM에 추가됩니다. 특기할 점으로, error boundary가 Root 컴포넌트에 들어가 있습니다. 자식 함수 컴포넌트에서 throw Error을 할 경우 해당 error boundary에서 처리됩니다.</p><p>주석: 리액트 concurrent mode는 ReactDOM.render이 아닌 createRoot을 사용해야 합니다.</p><h4>src/db.server.js</h4><p>react-prisma의 PrismaClient 인스턴스가 이 모듈 안에 들어있습니다. 모듈 이름에서 알 수 있듯이 서버 컴포넌트에서만 import 가능합니다.</p><h4>src/App.server.js</h4><p>이 SPA의 알맹이입니다. location을 props로 받는 서버 컴포넌트이며, 클라이언트에 전달된 이후 Root의 child로 렌더됩니다. App의 자식들은 클라이언트 컴포넌트와 서버 컴포넌트가 섞여있음을 볼 수 있습니다.</p><h4>한계점</h4><p>전체적인 구현을 알고 나니 이 데모 앱의 한계점을 알 수 있었습니다.</p><ol><li><strong>페이지가 하나뿐임. </strong><strong>X-Location 헤더를 사용한 props 전달.</strong><br>만들고자 하는 앱이 SPA가 아닌 경우 이 데모 앱의 아키텍처를 그대로 사용할 수는 없을 것으로 보입니다. 그리고 HTTP 헤더로 props를 전달하는 구조라서 JSON.stringify 할 수 없는 객체들은 props로 쓸 수 없습니다 (예: 함수, 날짜).</li><li><strong>Mutation 결과가 페이지 (리액트 컴포넌트)임.<br></strong>리액트 팀은 mutation 결과로 컴포넌트를 반환함으로써 클라이언트의 캐시 관리를 보다 수월하게 해줄 수 있다고 언급했지만, 데모 앱에서는 페이지 하나를 통채로 반환하기 때문에 RSC가 특별히 더 효율적으로 보이진 않았습니다. 그리고 채팅 앱 같이 여러 스크린이 존재하는 경우, 업데이트 되어야 하는 스크린들을 일일히 확인해서 서버가 보내주는건 기존 cache invalidation보다 더 쉬운 방법이라고 말하긴 어려울 것 같습니다.</li></ol><p>데모 앱의 한계점과는 별개로 React 18이 아직 실제 프로젝트에 사용하기 어려운 이유도 있습니다.</p><ol><li><strong>타입스크립트 지원 미비. 인터페이스가 아직 확정되지 않음.<br></strong>지금 실험 단계에 있는 기능들은 전부 unstable_ 접두사를 붙여야 사용할 수 있으며, 아직 인터페이스가 확정되지 않은것으로 보입니다 (예: unstable_useTransition). 이에 따른 당연한 결과로 타입스크립트 지원이 없으며, 프리즈마의 중요한 장점인 타입을 활용하기 힘듭니다.</li><li><strong>주요 리액트 프레임워크들의 지원 미비.<br></strong>리액트 팀은 현재 NextJS와 <a href="https://nextjs.org/docs/advanced-features/react-18">파트너쉽을</a> 맺고 concurrent mode와 RSC지원을 추가하는 중입니다. 하지만 NextJS 문서에 따르면 클라이언트 컴포넌트에서 서버 컴포넌트를 import하지 못하는 등의 치명적인 한계가 아직 남아있습니다. 널리 사용되고 있는 Create React App (CRA)의 경우에는 아직 리액트 18 지원에 대한 언급이 없습니다. 클라이언트 전용이었던 리액트가 서버쪽 기능을 추가하는 것이기 때문에 여러모로 어려움이 있을것으로 예상됩니다.<br>주석: next와 react-prisma 패키지가 서로 다른 react 버전을 peer dependency로 지정했기 때문에 정확히 어떤 버전의 react를 설치해야 할 지 확인하기 어려웠습니다.</li></ol><h3>데모 소스코드 개선해보기</h3><p>데모 앱에서 부족한 부분들을 확인했으니, 개선 가능한 부분들을 보완해 보았습니다. 여기에서 제가 작업한 결과물을 확인하실 수 있습니다: <a href="https://github.com/prisma-korea/prisma-server-component-example">https://github.com/prisma-korea/prisma-server-component-example</a></p><h4>React Router 적용</h4><p>데모 앱은 SPA라서 React Router를 사용한 앱들에도 RSC를 적용할 수 있을지 먼저 확인해 보았습니다.</p><p>일단 각 스크린별로 다른 컴포넌트를 렌더해주어야 하므로, 백엔드의 renderReactTree가 App 말고도 다른 컴포넌트를 렌더할 수 있게 범용성을 개선했습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfb5116d5a815b4333fc93dea5538855/href">https://medium.com/media/dfb5116d5a815b4333fc93dea5538855/href</a></iframe><p>그리고 각 스크린별로 서버 컴포넌트를 요청할 수 있는 경로를 지정해주었습니다. (app.use(&#39;/react&#39;, router) 이므로 /react/가 Home 컴포넌트에 대응됩니다.)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10e0452f3a42175bdf294d3c55a762f5/href">https://medium.com/media/10e0452f3a42175bdf294d3c55a762f5/href</a></iframe><p>이에 대응되게 useServerResponse가 pathname에 따라 다른 서버 컴포넌트를 요청하도록 수정했습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd65c09930fe4b055a6bfcbc71a30e93/href">https://medium.com/media/bd65c09930fe4b055a6bfcbc71a30e93/href</a></iframe><p>마지막으로 Root 컴포넌트에 BrowserRouter를 추가하고, suspense 캐싱은 pathname을 키로 사용하도록 했습니다.</p><p>이렇게 수정하고 나니 스크린을 전환할 때 마다 /react/* 경로에서 컴포넌트를 받아오고, 이미 방문한 스크린은 캐싱된 컴포넌트를 재사용하는걸 확인할 수 있었습니다. 결과적으로 SPA가 아니라도 RSC는 무리없이 사용 가능합니다!</p><h4>Cache Invalidation</h4><p>데모 앱은 mutation 응답으로 컴포넌트를 받아와서 클라이언트에 렌더하는걸 보여주는데, SPA에서는 가능한 방법이라도 라우터가 있는 상황에서는 서버가 캐시를 관리하는게 간단하지 않아보였습니다. 따라서 클라이언트에서 캐시를 관리하는 일반적인 구조로 수정했습니다.</p><p>일단 CRUD API가 컴포넌트가 아닌 JSON을 반환하도록 수정하고,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d106a9030db33635607e5bd071e0aaf7/href">https://medium.com/media/d106a9030db33635607e5bd071e0aaf7/href</a></iframe><p>Suspense cache를 invalidate하는 훅을 작성했습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64accf55b7cf51a2b67be4d1ddecfd85/href">https://medium.com/media/64accf55b7cf51a2b67be4d1ddecfd85/href</a></iframe><p>마지막으로 handleSubmit에서 mutation이 끝난 후에 cache invalidate을 하게 해주었습니다.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/98d2a50c3942df29de6febc1a5c476eb/href">https://medium.com/media/98d2a50c3942df29de6febc1a5c476eb/href</a></iframe><p>역시 cache invalidation은 RSC를 쓰든 쓰지 않든 피해갈 수 없는 난제인 것 같습니다…</p><h3>기대되는 점</h3><p>아직 리액트 18은 베타 단계라 불안정한 면이 있고, 관련 라이브러리들도 적응하는 기간이 꽤 필요할 것으로 보입니다. 하지만 앞서 제가 데모 앱에서 확인한 한계점들도 지금 약간의 노력으로 해결 가능하거나 출시 이후 시간이 지나면 저절로 해결될 부분들이라서 걱정이 되진 않습니다. 오히려 제 예상으로 RSC는 SSR의 상위호환격 기능으로써 18버전 출시 이후 많은 기업들에서 채택할 것 같습니다. 뻔히 예상되는 기술적 어려움이 있음에도 불구하고 장기적인 안목으로 리액트를 만들어 나가는 리액트 팀을 응원합니다.</p><blockquote><em>Priska Korea 오픈 채팅방: </em><a href="https://open.kakao.com/o/g4oQTEqd"><em>https://open.kakao.com/o/g4oQTEqd</em></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1652a997927" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prisma-korea/%EB%A6%AC%EC%95%A1%ED%8A%B8-%EC%84%9C%EB%B2%84-%EC%BB%B4%ED%8F%AC%EB%84%8C%ED%8A%B8%EC%99%80-%ED%94%84%EB%A6%AC%EC%A6%88%EB%A7%88-c1652a997927">리액트 서버 컴포넌트와 프리즈마</a> was originally published in <a href="https://medium.com/prisma-korea">Prisma Korea</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 Update Relay Cache]]></title>
            <link>https://medium.com/hyodotdev/how-to-update-relay-cache-d04ee074eb98?source=rss-3c26c3f84101------2</link>
            <guid isPermaLink="false">https://medium.com/p/d04ee074eb98</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[relayjs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Danny Kim]]></dc:creator>
            <pubDate>Sun, 31 Jan 2021 22:32:58 GMT</pubDate>
            <atom:updated>2021-02-07T20:46:05.422Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*R7W2uXa4tMUvJrqS" /><figcaption>Photo by <a href="https://unsplash.com/@alinnnaaaa?utm_source=medium&amp;utm_medium=referral">Alina Grubnyak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article covers how to manipulate records inside Relay cache (a.k.a. Relay store). Although Relay can take care of great amount of state management by itself, sometimes developers have to tell Relay what to do. In order to do that efficiently, we need to know how Relay manages its cache and how we can interact with the cache.</p><h3>What Relay Cache Looks Like</h3><p>Relay stores its cache as a graph of records. Each record is identified by its unique ID, and a record can have scalar fields and “links” to other records.</p><p>For example, look at this GraphQL schema:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4507a3980a0232bfc204ab80c7c898af/href">https://medium.com/media/4507a3980a0232bfc204ab80c7c898af/href</a></iframe><p>A User record has an id field and an email field which are scalars. Also, it has a list of Post records, and we call these “linked records”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/327/1*nyaQf9c8LS2ZMpKmgp0_9A.jpeg" /></figure><p>So for example, if we want to access an Post record inside Relay cache, we have two options:</p><ol><li>Access it directly by its ID.<br> store.get(&#39;xyzpq9999&#39;)</li><li>Access the user which is linked to the Post record of our interest, then follow the link.<br>store.get(‘abcde5656’).getLinkedRecord(‘posts’)[1]</li></ol><p>We can freely modify scalar values or links as long as we can access the cached records. I will discuss the API specifics later in this article.</p><h3>How to Update Relay Cache</h3><p>There are two ways to update Relay cache.</p><ol><li>Fetch the updated record from server.</li><li>Use Relay updater function.</li></ol><h4>Approach 1: Fetch the Updated Record</h4><p>The first approach is easier and cleaner. If server can response with the updated record after mutation, Relay can automatically update the cache accordingly. Look at this GraphQL mutation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7fb1749d572bb4892fb01bce622cb0e/href">https://medium.com/media/c7fb1749d572bb4892fb01bce622cb0e/href</a></iframe><p>It is a simple mutation that updates the title of a Post. When successful, server will return the updated version of Post. Relay will use this response to update its cache, so there is no extra effort required for us.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2efe063ec9df0a004e06ca1c77c90c0a/href">https://medium.com/media/2efe063ec9df0a004e06ca1c77c90c0a/href</a></iframe><p>Just make sure to request id and title field so that Relay can process the response and update cache.</p><h4>Approach 2: Updater Function</h4><p>Receiving the updated value immediately as a response is nice, but sometimes we cannot change APIs to suit our needs. This is where we need to manually modify Relay cache using <strong>updater</strong> function. I will cover the basics in this article, but you might want to check out <a href="https://relay.dev/docs/en/mutations">Relay’s official documentation</a> on this topic.</p><p>Consider this mutation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbdca699d4a62204483dd1e7f2545f9f/href">https://medium.com/media/cbdca699d4a62204483dd1e7f2545f9f/href</a></iframe><p>deletePostContent mutation does not respond with the updated Post record; therefore, Relay will not update its cache automatically. Although we do not have the updated record, we know that the content field will be null after successful deletePostContent. Here’s how you update cache manually using updater function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b3ea96db8fa5130876f6cd30bab6709/href">https://medium.com/media/7b3ea96db8fa5130876f6cd30bab6709/href</a></iframe><p>In this case, finding the Post record was easy because we knew its ID. store.get method returns a proxy to the record if it exists. Proxy is how we mainly interact with Relay cache, so it is a good idea to get familiar with its API (<a href="https://relay.dev/docs/en/experimental/relay-store">Relay Store API</a>). Here are a few useful methods of RecordProxy :</p><ul><li>getValue : Gets the value of a scalar field.</li><li>setValue : Sets the value of a scalar field.</li><li>getLinkedRecord : If a field is linked to another record, get RecordProxy of the linked record.</li><li>setLinkedRecord : Link the given field to the given record. If there is an existing linked record, the original linked record is unlinked.</li><li>getLinkedRecords : gets a list of linked records (e.g. User.posts ).</li></ul><h3>Alternatives to Cache Update</h3><p>Maybe your issue can be resolved without updating Relay cache. Consider these alternatives before writing your updater function.</p><h4>Cache Invalidation</h4><p>We can invalidate individual records using RecordProxy.invalidateRecord method. Calling this method will mark the Record as “stale” and force Relay not to re-use this cached record. Note that invalidation does not trigger any refetch unless specified inside useSubscribeToInvalidationState hook.</p><h4>Imperative Refetch</h4><p>Relay provides for fetchQuery and useQueryLoader for imperative usage. We can trigger imperative re-fetch on mutation completion.</p><h3>Conclusion</h3><p>If server can respond to mutation with the updated record, let Relay use server response to update its cache. When server response is insufficient, we can read &amp; write pretty much any value inside Relay cache using updater function as long as we know how to locate the records of our interest.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d04ee074eb98" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hyodotdev/how-to-update-relay-cache-d04ee074eb98">How to Update Relay Cache</a> was originally published in <a href="https://medium.com/hyodotdev">Hyo Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>