<?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 Pasindu Dilshan Gunathilake on Medium]]></title>
        <description><![CDATA[Stories by Pasindu Dilshan Gunathilake on Medium]]></description>
        <link>https://medium.com/@pasindu-dilshan?source=rss-af9fb87e6fdf------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9CBO-8xUbBkg7WxVrVUD3g.jpeg</url>
            <title>Stories by Pasindu Dilshan Gunathilake on Medium</title>
            <link>https://medium.com/@pasindu-dilshan?source=rss-af9fb87e6fdf------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 10:26:31 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pasindu-dilshan/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[Building a Serverless GraphQL API with Prisma, Apollo & PlanetScale - Part Ⅱ]]></title>
            <link>https://engineering.99x.io/building-a-serverless-graphql-api-with-prisma-apollo-planetscale-part-%E2%85%B1-b154156e6fd5?source=rss-af9fb87e6fdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/b154156e6fd5</guid>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[pothos]]></category>
            <dc:creator><![CDATA[Pasindu Dilshan Gunathilake]]></dc:creator>
            <pubDate>Tue, 27 Sep 2022 06:20:26 GMT</pubDate>
            <atom:updated>2022-09-27T06:23:48.803Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzQVDZ6QSJCqPxa6Kx2R_Q.png" /></figure><p>This is the second &amp; final part of the series written on building a serverless GraphQL API with <a href="https://www.prisma.io/">Prisma</a>, <a href="https://www.apollographql.com/">Apollo</a> &amp; <a href="https://planetscale.com/">Planetscale</a>.</p><p>If you missed the first part head over to the following article.</p><p><a href="https://engineering.99x.io/building-a-serverless-graphql-api-with-prisma-apollo-planetscale-part-%E2%85%B0-9974cd0cbd35">Building a Serverless GraphQL API with Prisma, Apollo &amp; PlanetScale -  Part Ⅰ</a></p><p>We are going to do the following items in order to accomplish our end goal.</p><ol><li>Configure apollo server</li><li>Building our GraphQL schema. (We’ll see how we can plug-in Prisma on writing our resolvers &amp; mutations)</li><li>Testing our GraphQL API</li><li>Deploying the Lambda</li></ol><h3>Installing dependencies for Apollo server</h3><p>We need to install the <a href="https://github.com/apollographql/apollo-server">apollo-server-lambda</a> &amp; <a href="https://github.com/graphql/graphql-js">graphql</a> packages in our serverless application developed so far.</p><pre>npm install apollo-server-lambda graphql</pre><p>Next we’ll take a look at how we are going to define our GraphQL schema.</p><h3>Defining GraphQL Schema</h3><p>There are two approaches to creating our GraphQL service.</p><ul><li>Schema-first approach : Priority is given in the process of designing the schema</li><li>Code-first approach (Resolver-first) : Prioritize code over schema; We start by coding the resolvers. Eventually schema is programmatically generated.</li></ul><p>One of the aims that we set from first article was to make the API type-safe as much as possible. For this code-first approach is ideal. So let’s follow it.</p><h4>File Directory structure</h4><p>We will split our API code in the following file structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/917/1*79lVEMc3eJnuKp6mYzfPWA.png" /><figcaption>File structure of our serverless project by the end of this article. Note that some files from boilerplate code has been cleaned up.</figcaption></figure><ul><li>api/db.ts :- Where we define a reusable PrismaClient</li><li>api/context.ts :- Where we define the context to be passed to GraphQL server.</li><li>api/schema :- This is the directory where we define our GraphQL Schema. <br>- api/schema/builder.ts :- Where we define our builder (More on this later)<br>- api/schema/index.ts :- Where we write our code-first graphql schema.</li><li>api/handler.ts :- Where we create our apollo server and define our Lambda handler.</li><li>api/index.ts :- Where we will wrap our handler as a function to be imported in serverless.ts</li><li>api/context.ts :- Where we define the context to be passed to each of our GraphQL resolver.</li></ul><h4>Using Pothos for strongly typed code-first approach</h4><p>To make our development easier &amp; faster with code-first approach we are going to use a library called <a href="https://github.com/hayes/pothos">Pothos</a>. The main reason why we choose Pothos is that it has a <a href="https://pothos-graphql.dev/docs/plugins/prisma">plugin for Prisma</a>.</p><p>There are several other libraries apart from Pothos which will be helpful for similar case. Some of these are <a href="https://typegraphql.com/">TypeGraphQL</a>, <a href="https://nexusjs.org/">GraphQL Nexus</a> &amp; <a href="https://www.graphql-code-generator.com/">GraphQL Code Generator</a>.</p><p>We’ll need to install related dependencies as below.</p><pre>npm install @pothos/core @pothos/plugin-prisma @prisma/client</pre><blockquote><strong><em>Note</em></strong>: <a href="https://pothos-graphql.dev/docs/guide/troubleshooting#type-isues">Pothos encourages</a> you to enable <a href="https://www.typescriptlang.org/tsconfig#strict">strict mode in typescript</a></blockquote><p>Next we will add the pothos generator to our prisma schema file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cf2510a29747e4d6b4a7eb3c7acf02f/href">https://medium.com/media/9cf2510a29747e4d6b4a7eb3c7acf02f/href</a></iframe><p>This ensures whenever we modify our database schema via Prisma it automatically updates the type definitions required for GraphQL API development. We can run the following command to re-generate client &amp; create the new types.</p><pre>npx prisma generate</pre><h4>Creating a reusable PrismaClient</h4><p>We can instantiate a new PrismaClient that’s reusable in api/db.ts</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/256375c72c79b9928a6fd380fb644d85/href">https://medium.com/media/256375c72c79b9928a6fd380fb644d85/href</a></iframe><h4>Creating a context for GraphQL resolvers</h4><p>We can pass the PrismaClient that was built earlier to be accessible to the resolvers via <a href="https://www.apollographql.com/docs/apollo-server/data/resolvers/#the-context-argument">context argument</a>. Let’s define this in api/context.ts</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59612c5e76fc54d24d1ee33f66cbb4bf/href">https://medium.com/media/59612c5e76fc54d24d1ee33f66cbb4bf/href</a></iframe><h4>Setting up the Pothos builder</h4><p>Using the generated types along with the context we can create our builder in api/schema/builder.ts as follow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39d56b579cb764d1d0af6389de5dd361/href">https://medium.com/media/39d56b579cb764d1d0af6389de5dd361/href</a></iframe><h4>Writing our code-first schema</h4><p>Developing our code-first schema is the most time consuming part out of all the steps we follow.</p><p>In order to grasp exactly how our code was written, you need to dig-deep into Pothos guide section.</p><p><a href="https://pothos-graphql.dev/docs/guide">Getting started guide for Pothos GraphQL</a></p><p>Since this article is not entirely about Pothos we are going to skip that explanation and go ahead finalizing our schema in api/schema/index.ts as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50496d43a37da62d03d34c39509db114/href">https://medium.com/media/50496d43a37da62d03d34c39509db114/href</a></iframe><p>In above schema we have defined,</p><ul><li><a href="https://www.apollographql.com/docs/apollo-server/schema/schema/#the-query-type">GraphQL queries</a> for a single User, Profile &amp; Post that can be fetched by passing their relevant Id</li><li><a href="https://www.apollographql.com/docs/apollo-server/schema/schema/#the-mutation-type">GraphQL mutations</a> to create a User &amp; Post</li></ul><p>We have accessed Prisma client via the context we’re expecting to pass earlier in the next step.</p><p>Next we will use this schema to create our apollo server as the handler.</p><h3>Creating Apollo Server Handler</h3><p>We can plug the schema we built earlier, along with the context to the ApolloServer instance. Then we can expose this as a Lambda function handler as follow.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c878a0fe760df62c2d5dd3b0d7dbe8ea/href">https://medium.com/media/c878a0fe760df62c2d5dd3b0d7dbe8ea/href</a></iframe><h3>Passing Handler to serverless</h3><p>To simply pass our handler to functions property in serverless.ts we are going to wrap our handler in api/index.ts as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a12e8830f1720c0403a0259822ba7982/href">https://medium.com/media/a12e8830f1720c0403a0259822ba7982/href</a></iframe><p>Then we can import this from our serverless.ts file. Finally it will look as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13b9d86e3e521e2ad9b95b104471e2b8/href">https://medium.com/media/13b9d86e3e521e2ad9b95b104471e2b8/href</a></iframe><p>Now we should be able to spin up our GraphQL server.</p><h3>Testing the GraphQL API locally</h3><p>In the first part of this series we’ve created a script to run locally. We can utilize it as follow.</p><pre>npm run dev</pre><p>Then you can head to <a href="http://localhost:3000/dev/graphql">http://localhost:3000/dev/graphql</a> to explore the graph we’ve built.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zWAbS6sXep2b1g8loHPW8w.gif" /><figcaption>Time to explore the graph we’ve built</figcaption></figure><p>You can hit <strong><em>Query you server</em></strong> button to head over to <a href="https://www.apollographql.com/docs/studio/">Apollo studio</a> (You’ll be prompted with the sandbox mode if you aren’t logged in to Apollo)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6NKitD31h0hG82Hqu-ahug.gif" /><figcaption>Much like any other GraphQL playgrounds you can use Apollo studio to explore the graph built.</figcaption></figure><h3>Deploying the Lambda</h3><p>In the previous article we’ve added a serverless script to deploy. By invoking,</p><pre>npm run deploy</pre><p>you can deploy the Lambda.</p><p>There are a few things we can do such as creating lambda layers where it will result in further reducing the size of Lambda. You can read more about it via:</p><p><a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-layers.html">Creating and sharing Lambda layers</a></p><p>Once deployment is done, console will output the endpoints where you can explore the Apollo GraphQL server as before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yWThzgOgSrqt_FuXCQ5tJA.png" /></figure><p>Or you can browse through <a href="https://aws.amazon.com/api-gateway/">AWS API Gateway</a> and find this endpoint as well.</p><p>With that we’re going to wrap up this series.</p><p>All the code for this guide is available in the following repository.</p><p><a href="https://github.com/Pasi-D/serverless-graphql-api">GitHub - Pasi-D/serverless-graphql-api: Serverless GraphQL API with Apollo, Prisma &amp; Pothos</a></p><p>Hope this guide will help you in writing your next GraphQL API in a productive manner.</p><p>Happy coding !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b154156e6fd5" width="1" height="1" alt=""><hr><p><a href="https://engineering.99x.io/building-a-serverless-graphql-api-with-prisma-apollo-planetscale-part-%E2%85%B1-b154156e6fd5">Building a Serverless GraphQL API with Prisma, Apollo &amp; PlanetScale - Part Ⅱ</a> was originally published in <a href="https://engineering.99x.io/">Engineering at 99x</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Serverless GraphQL API with Prisma, Apollo & PlanetScale -  Part Ⅰ]]></title>
            <link>https://engineering.99x.io/building-a-serverless-graphql-api-with-prisma-apollo-planetscale-part-%E2%85%B0-9974cd0cbd35?source=rss-af9fb87e6fdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/9974cd0cbd35</guid>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[planet-scale]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Pasindu Dilshan Gunathilake]]></dc:creator>
            <pubDate>Mon, 22 Aug 2022 09:27:44 GMT</pubDate>
            <atom:updated>2022-08-22T09:27:44.079Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Serverless GraphQL API with Prisma, Apollo &amp; PlanetScale - Part Ⅰ</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o7fnhmJIL86KBKYVf_PW0g.jpeg" /></figure><p>In this two part series, I’ll be showing you step by step how to utilize <a href="https://www.serverless.com/"><em>Serverless Framework</em></a> to build a simple<em> </em><a href="https://graphql.org/"><em>GraphQL</em></a><em> API</em>.</p><p>For data persistence we will be using <a href="https://planetscale.com/"><em>PlanetScale</em></a> which is a MySQL-compatible, serverless database platform powered by <a href="https://vitess.io/">Vitess</a>.</p><p>We will be using <a href="https://www.prisma.io/"><em>Prisma</em></a> which is a next generation ORM to communicate with the database. Finally to build the GraphQL API we will be using <a href="https://www.apollographql.com/docs/apollo-server/"><em>Apollo server</em></a>.</p><p>In this article we are going to take a look at each of the tech stacks that we are utilizing to build our serverless API; Then we’ll configure the basic infrastructure that we are going to be needing later onwards.</p><h3>Pre-Requisites</h3><ul><li>Some basic understanding about <a href="https://graphql.org/">GraphQL</a>.</li><li>A <a href="https://planetscale.com/">PlanetScale</a> account. (They offer a <a href="https://planetscale.com/pricing">limited free tier</a> which is useful for testing things out.)</li><li>A basic understanding about <a href="https://prisma.io/">Prisma</a>.</li><li>NodeJS (Preferably 14.x LTS) along with <a href="https://www.serverless.com/framework/docs/getting-started">serverless CLI installed</a>.</li></ul><h3>Why PlanetScale ?</h3><blockquote>PlanetScale provides a workflow that allows users to update database schemas without locking the database or causing downtime.</blockquote><p>It’s much like version controlling your database schema. <br>PlanetScale allows you to branch database schemas the same way you branch your code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TEiH4V0ud0vi_Dc9_xU6Gg.png" /><figcaption><a href="https://docs.planetscale.com/concepts/branching">PlanetScale Branching Flow</a></figcaption></figure><p>You can create a development or staging environment(s) for your database through branches.</p><p>Eventually you can keep a single production ready database branch as well.</p><h3>Why Apollo for GraphQL development ?</h3><p><a href="https://www.apollographql.com/">Apollo</a> is a team &amp; a community built around GraphQL, which provides numerous productive tools that will help to elevate your project.</p><p>Using <a href="https://www.apollographql.com/docs/apollo-server/">Apollo Server</a> is one of the best ways to build a production-ready type-safe GraphQL server that can connect to any API, database or microservice.</p><p>It has compatibility with majority of trending JS frameworks &amp; its deployable in serverless environments.</p><h3>Why Prisma ?</h3><p>Prisma is a next-generation object–relational mapper (ORM) which makes it easier for developers to write clean &amp; type-safe database queries. This makes development faster, write self-documented code and makes it less error prone in production.</p><p>Productivity &amp; developer experience are taken into consideration at the core of Prisma. Prisma guarantees to give you a significant productivity boost for majority of common workflows surrounding database(s).</p><p>Let’s get started with setting up our serverless project.</p><h3>Setting up the serverless project</h3><p>We’ll use the aws-nodejs-typescript serverless template to initialize the project. <br>Let’s use Typescript with the sole aim to making this API type-safe as much as possible.</p><pre>serverless create --template aws-nodejs-typescript --path serverless-graphql-api</pre><blockquote><strong><em>Note</em></strong> : With <em>serverless 3.x.y</em> version above template is bundled with <a href="https://esbuild.github.io/"><em>esbuild</em></a><em>,</em> While in serverless 2.x.y its <a href="https://webpack.js.org/">webpack</a>. In order to avoid running into any bundling issues its better to use webpack.</blockquote><blockquote>If you’re having trouble, you can start using a boilerplate template I’ve created with serverless create-template-url <a href="https://github.com/Pasi-D/aws-nodejs-typescript.git">https://github.com/Pasi-D/aws-nodejs-typescript.git</a> --path serverless-graphql-api</blockquote><p>Afterwards navigate to the project directory &amp; install the boilerplate dependencies with a npm install.</p><p>This template comes with a single lambda function triggered by an HTTP request. We won’t be needing this.</p><h3>Adding required devDependencies</h3><p>The boilerplate code structure looks much like below. I’ve went ahead and added couple of developer productivity tweaks such as <a href="https://eslint.org/">ESLint</a> &amp; <a href="https://prettier.io/">prettier</a>. But these two are completely optional unless you’re hyped in keeping the codebase clean 😉</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*thKZ5D6MYTu-SQxdx-93Bg.png" /><figcaption>Initial project structure</figcaption></figure><p>We will need to install <a href="https://github.com/neverendingqs/serverless-dotenv-plugin">serverless-dotenv-plugin</a> ,<a href="https://github.com/dherault/serverless-offline">serverless-offline</a> &amp; serverless-webpack-prisma plugins as they will be needed soon afterwards. <br>Adding them is pretty straightforward; First do a</p><pre>npm install serverless-dotenv-plugin serverless-offline serverless-webpack-prisma --save-dev</pre><p>Then update the serverless plugin list in serverless.ts file.</p><pre>…<br>plugins: [<br>  &quot;serverless-webpack&quot;, <br>  &quot;serverless-webpack-prisma&quot;,<br>  &quot;serverless-offline&quot;,<br>  &quot;serverless-dotenv-plugin&quot;<br>]<br>…</pre><p>You can set useChildProcesses property to true under custom in serverless.ts to run the handlers in a child process.</p><pre>...<br>custom: {<br>  ...,<br>  &quot;serverless-offline&quot;: {<br>     useChildProcesses: true<br>  }<br>}<br>...</pre><p>serverless-offline is added in order to emulate the Lambda API locally. Let’s go ahead and add a following scripts in package.json to develop locally &amp; for deployment.</p><pre>...<br>&quot;scripts&quot;: {<br>   &quot;dev&quot;: &quot;serverless offline&quot;, <br>   &quot;deploy&quot;: &quot;serverless deploy --verbose&quot;,<br>   &quot;remove&quot;: &quot;serverless remove --verbose&quot;<br>},<br>...</pre><h3>Adding Prisma to the Project</h3><p>We need to add Prisma CLI as a development dependency.</p><pre>npm install prisma --save-dev</pre><p>Next we need to initialize Prisma in our project directory. We can do this with following command.</p><pre>npx prisma init</pre><p>This will,</p><ul><li>Create a prisma directory with a <strong>schema.prisma</strong> file. This is where we will define our data model.</li><li>Create a .env file which we will use to define environment variables such as database connection string. We will keep a .env.dist committed to the repository.</li></ul><p>Now before we move into creating connection with our database let’s see what’s so significant about PlanetScale is.</p><h3>Setting up the PlanetScale database</h3><p>You can setup a Planetscale database via their <a href="https://planetscale.com/features/cli">CLI</a> or straightly through the web console. Let’s pick the latter after signing into their platform.</p><p>Process of creating a new PlanetScale database via web console is straightforward. <br>Following is a <em>.gif</em> illustration how you can simply do this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HYkRG48l45MLh1v8F1zjYQ.gif" /><figcaption>It only takes couple of minutes to create a database in PlanetScale</figcaption></figure><p>When selecting the <a href="https://docs.planetscale.com/concepts/regions">Planetscale database region</a> make sure to select the same deployment region of Lambda.</p><p>Default branch of this newly created database is main. This will be a development branch.</p><p>Using the connect button get your connection variables for this main branch. Select Prisma from the dropdown to get the database connection URL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXptP9YMmmON0VGb1kNBzw.jpeg" /><figcaption>From the drop down highlighted you can select Prisma and get the database connection url string</figcaption></figure><h3>Update database connection variables</h3><p>For ease of maintenance we will split our connection variables in following manner.</p><p>Update your .env variables with the Database connection settings obtained from PlanetScale.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54b41927729c406b7f1276a8bdbe4d03/href">https://medium.com/media/54b41927729c406b7f1276a8bdbe4d03/href</a></iframe><h3>Making Prisma client compatible with AWS Lambda</h3><p>In order to make Prisma client work with AWS Lambda we need to make it compatible to the Lambda runtime. This can be done by altering <a href="https://www.prisma.io/docs/concepts/components/prisma-schema/generators#binary-targets">binaryTarget property</a> in <a href="https://www.prisma.io/docs/concepts/components/prisma-schema/generators#prisma-client-prisma-client-js">Prisma Client generator block</a> as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a1b5c2eeaa984f6005013b0a0a2c51d/href">https://medium.com/media/7a1b5c2eeaa984f6005013b0a0a2c51d/href</a></iframe><blockquote>“native” in above is to run compatible with the local development machine. “rhel-openssl-1.0.x” is for compatibility with <a href="https://aws.amazon.com/blogs/compute/migrating-aws-lambda-functions-to-al2/">AWS Lambda which uses an OS called Amazon Linux 2</a> that use RHEL OpenSSL binary.</blockquote><p>Next we need to update our serverless.ts in a manner to upload only the Prisma Engine binaries relevant for Lambda runtime.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/17c43a0b1ef8b95dd238da96963fcedc/href">https://medium.com/media/17c43a0b1ef8b95dd238da96963fcedc/href</a></iframe><p>This ensures the packaged archive is as small as possible.</p><p>There are several other options you can adopt in case if your setup is different to what we are using here. You can refer to this via following AWS Lambda deployment guide by Prisma.</p><p><a href="https://www.prisma.io/docs/guides/deployment/deployment-guides/deploying-to-aws-lambda">Deploying to AWS Lambda</a></p><h3>Defining our Data Model</h3><h4>Referential Integrity in PlanetScale &amp; approach with Prisma</h4><blockquote>To support scaling across multiple database servers, PlanetScale <a href="https://docs.planetscale.com/learn/operating-without-foreign-key-constraints">does not allow the use of foreign key constraints</a> which is normally available in a relational database.</blockquote><p>So this needs to be handled manually in application level.</p><p>Luckily with Prisma, you can maintain these relationships in your data and allow the use of <a href="https://www.prisma.io/docs/concepts/components/prisma-schema/relations/referential-actions">referential actions</a> by using Prisma’s ability to <a href="https://www.prisma.io/docs/concepts/components/prisma-schema/relations/referential-integrity#handling-the-referential-integrity-in-prisma">emulate referential integrity in the Prisma client</a>.</p><p>Referential Integrity is currently available as a preview feature. So in schema.prisma file we need to add it to the previewFeatures list in the generator block &amp; set the referentialIntegrity type to &quot;prisma&quot; in the datasource block.</p><h4>Data modeling</h4><p>Soon after above step we can move on to the data modeling part.</p><p>We will take a simple blogging app scenario into our consideration where there are 3 entities : User, Profile &amp; Post.</p><p>Following is an ERD depiction of these.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_bPcrZjdRx1Bz1C6DunXSA.jpeg" /></figure><p>We’ll represent above ERD in schema.prisma with syntaxes in <a href="https://www.prisma.io/docs/concepts/components/prisma-schema">Prisma schema language</a>.</p><p>Putting all of these together we can update our schema.prisma file in following manner.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c588bec146c92a173348dad07f92123a/href">https://medium.com/media/c588bec146c92a173348dad07f92123a/href</a></iframe><h3>Sync the database schema</h3><p>Prisma recommends not using prisma migrate (which generates its own history of migration files) command when making schema changes with PlanetScale. Instead the <a href="https://www.prisma.io/docs/guides/database/using-prisma-with-planetscale#differences-to-consider">recommended approach</a> is to use following command.</p><pre>npx prisma db push</pre><p>This will,</p><ul><li>Synchronize the Prisma schema with database schema.</li><li>Triggers <a href="https://www.prisma.io/docs/concepts/components/prisma-schema/generators">generators</a>; In our case <a href="https://www.prisma.io/docs/concepts/components/prisma-client">Prisma client</a> will be generated.</li></ul><h3>Creating a highly available production branch</h3><p>A production branch in PlanetScale is intended for high availability. Schema changes can’t be directly pushed to it. It also includes automated daily backups.</p><p>You can decide which PlanetScale database branch (i.e a development branch) you need to promote to production.</p><p>Since we made our schema changes to main branch, I will create a new branch called production from main branch and promote it as the Production branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c-OIlGth05ot2x9DsAeljg.png" /></figure><p>Similar to the earlier step obtain the connection variables for this production branch. Then update your .env as we will be utilizing it to persist our data when API is completed.</p><p>If you are further interested in the development approach when making schema changes to Planetscale with Prisma, I recommend reading following guide.</p><p><a href="https://docs.planetscale.com/tutorials/automatic-prisma-migrations">https://docs.planetscale.com/tutorials/automatic-prisma-migrations</a></p><p>That’s all what we’re going to cover in this part. In the next part we will start working on building the GraphQL API.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9974cd0cbd35" width="1" height="1" alt=""><hr><p><a href="https://engineering.99x.io/building-a-serverless-graphql-api-with-prisma-apollo-planetscale-part-%E2%85%B0-9974cd0cbd35">Building a Serverless GraphQL API with Prisma, Apollo &amp; PlanetScale -  Part Ⅰ</a> was originally published in <a href="https://engineering.99x.io/">Engineering at 99x</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Working with Geo Coordinates in MySQL]]></title>
            <link>https://pasindu-dilshan.medium.com/working-with-geo-coordinates-in-mysql-5451e54cddec?source=rss-af9fb87e6fdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/5451e54cddec</guid>
            <category><![CDATA[geolocation]]></category>
            <category><![CDATA[spatial-data-analysis]]></category>
            <category><![CDATA[maps]]></category>
            <category><![CDATA[coordinates]]></category>
            <category><![CDATA[mysql]]></category>
            <dc:creator><![CDATA[Pasindu Dilshan Gunathilake]]></dc:creator>
            <pubDate>Sun, 03 Oct 2021 11:10:24 GMT</pubDate>
            <atom:updated>2021-10-04T08:30:05.329Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to Use Geo Coordinates in MySQL</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ED__KdeF4XsmUjPcyFBshA.jpeg" /></figure><p>Several months ago, I worked on a task that required finding certain entities around a small radius of an end user’s mobile device location. Latitude &amp; Longitude location data relevant to these entities were stored in a SQL database.</p><p>One of the choices to tackle this problem was to use <a href="https://developer.android.com/training/location/geofencing">Geofencing</a>, which turned out to be tedious in terms of implementation. Another approach to resolve this problem was using an SQL query against the database, which had all these location data.</p><p>This article is a walkthrough related to the findings that I was able to figure out while working on the latter solution. First, we will consider ways to store latitude &amp; longitude data in SQL databases. Then we’ll be looking at how we can query our database to find locations around a given location’s perimeter.</p><h3>Ways to persist location data within MySQL</h3><h4>Storing Latitude &amp; Longitude data as Floats or Decimal</h4><p>This is one of the most fundamental ways of storing geocoordinate data.</p><p>Latitude &amp; longitude values can be represented &amp; stored in a SQL database using decimal points (Decimal degrees) rather than degrees (or <strong>D</strong>egrees <strong>M</strong>inutes <strong>S</strong>econds).</p><p>For example, Colombo’s geo-location can be represented as,</p><p>(DMS Latitude) 6° 55&#39; 57&#39;’ N = 6.932500 (Decimal Degree Latitude)</p><p>(DMS Longitude) 79° 51&#39; 27.4392&#39;’ E = 79.857622 (Decimal Degree Longitude)</p><p>Depending on the accuracy you may require, you can decide how many decimal points you need to keep latitude &amp; longitude values. This decision may lead to the choice of using either float or decimal in the SQL database.</p><p>For example, storing up to 5 decimal places is good enough to differentiate between two trees at a location apart. So, a datatype such as <a href="https://dev.mysql.com/doc/refman/8.0/en/fixed-point-types.html">DECIMAL</a>(6,5) in MySQL is sufficient in this case.</p><p><em>Note: Be careful when you’re using floats data type as it can round the value.</em></p><h4>Spatial Data Types</h4><p>Spatial types are data types that store geometry data. Every aspect around us has some sort of a spatial component. Where we are living, how we are traveling etc. Maps are just one way to utilize spatial data.</p><p>Most of the databases, including MySQL, automatically come with spatial data types. However, others such as Postgres require some configuration or an installation to use a spatial data type.</p><p>Let’s take MySQL into our consideration first,</p><p>Following <a href="https://www.ogc.org/">OGC</a> (<strong>O</strong>pen <strong>G</strong>eospatial <strong>C</strong>onsortium) specifications, MySQL implements spatial extensions as a subset of the SQL with Geometry Types environment. As a result, there are drastic changes in these spatial data types between MySQL 5.6 &amp; 8.0. To get an understanding of what these are, first, you need to know what <a href="https://en.wikipedia.org/wiki/Spatial_reference_system"><strong>SRID</strong></a> is.</p><h4>SRID (Spatial Reference Identifier)</h4><p>There can be numerous coordinate systems depending on the plane or shape. For example, a cartesian plane is defined as flat space. A geographical plane is from an ellipsoid. So a point on the surface can have different meanings based on which coordinate system it lies upon.</p><p><strong>SRID,</strong> which stands for <strong>S</strong>patial <strong>R</strong>eference <strong>Id</strong>entifier, describes the coordinate space in which the geometry object is defined. For MySQL, SRID is a unique integer associated with a coordinate system that OGC proposed.</p><p>By default, MySQL uses SRID 0, which represents an infinite flat cartesian plane with no units assigned to its axes. In 5.7 and earlier versions, SRID was ignored &amp; all computations are cartesian.</p><p>MySQL 8.0, on the other hand, supports multiple spatial reference systems &amp; geographic computations. This means that SRIDs of geometries have meaning &amp; affect computations. Apart from this, there are a couple of notable improvements compared to the 5.6 version, which is beneficial for distance calculation.</p><ul><li>It introduces ellipsoid computation instead of flat plane cartesian.</li><li>Introduced multiple spatial reference systems identifiers (SRIDs). Out of them following are notably beneficial for our use case.<br>◾ <strong>4326 </strong>— Represents spatial data using longitude and latitude coordinates on the earth’s surface as defined in the <a href="https://en.wikipedia.org/wiki/World_Geodetic_System">WGS84 standard</a>, which is also used for the Global Positioning System (GPS)<br>◾ <strong>3857 </strong>— Used by certain Web mapping and visualization applications (Google Maps, Bing). Uses spherical development of ellipsoidal coordinates.</li></ul><h3>Finding location points near a given coordinate</h3><p>We’ll be taking a look at one of the mathematical formulas used in spherical trigonometry as well as in navigation first.</p><h4>Haversine Formulae</h4><p>Haversine formula determines the circle distance between two points on a sphere given their latitudes &amp; longitudes. The mathematical representation is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*9WVwBx50rGIaTiqJHNe3Hg.png" /><figcaption>source: <a href="https://en.wikipedia.org/wiki/Haversine_formula">https://en.wikipedia.org/wiki/Haversine_formula</a></figcaption></figure><p>It also can be written as follows.</p><pre>a = sin²(φB - φA/2) + cos φA * cos φB * sin²(λB - λA/2)</pre><pre>c = 2 * atan2( √a, √(1−a) )</pre><pre>d = R * c</pre><p>Where φ is latitude, λ is longitude, r is the radius of the sphere.</p><p>By substituting φ with a location’s latitude, λ with longitude &amp; R with the earth’s mean radius (6367 km or 3956 mi), you can obtain the distance between two location points.</p><p>Since we have taken the assumption that earth is a sphere (which is an oblate spheroid and not perfectly spherical) the result will not be 100% accurate. But it is good enough for most of the applications.</p><p>For scenarios where you need to calculate distance between two countries, errors in huge margins will be. But for scenarios like calculating the distance between two nearby coffee shops, the result will be around 97%-99% accurate.</p><p>Using the haversine formula is ideal when you’ve stored latitude &amp; longitude data as either float or decimal values. Let’s consider applying this on MySQL. First, we’ll build a database schema to persist geo-locations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/de287882190c5cf69cf8b69d88778d05/href">https://medium.com/media/de287882190c5cf69cf8b69d88778d05/href</a></iframe><p>Let’s keep constant value for a specific user’s location and try to query Geo Locations around him/her with a distance less than 100m.</p><p>Applying the above formula for this via SQL functions we get,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d84608ac96b9a2ec64d9ec1212099b9c/href">https://medium.com/media/d84608ac96b9a2ec64d9ec1212099b9c/href</a></iframe><h4>Taking advantage of spatial data functions</h4><p>Earlier, we saw certain differences between MySQL version 5.6 &amp; 8.0 when it comes to spatial data. So, let’s build a new database schema on top of MySQL 8.0 to persist geo-locations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a29530fd85fcbfa9024ab89b7a31f1db/href">https://medium.com/media/a29530fd85fcbfa9024ab89b7a31f1db/href</a></iframe><p>In this schema, we’ve used Point spatial type, which represents a single location in coordinate space. SRID 4326 is used as it closely resembles the earth’s surface coordinates. Apart from that, a<a href="https://dev.mysql.com/doc/refman/8.0/en/optimizing-spatial-analysis.html"> spatial index</a> is added to improve query performance.</p><p>Now we’ll use the <a href="https://dev.mysql.com/doc/refman/8.0/en/spatial-convenience-functions.html#function_st-distance-sphere">ST_Distance_Sphere</a> spatial data function to capture the geo-locations around 100m radius from a given user’s location.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2589947591462b230f64f7a11efa49b/href">https://medium.com/media/a2589947591462b230f64f7a11efa49b/href</a></iframe><p>For this simple query, spatial indexing will not provide a huge improvement.</p><p>Let’s consider some additional scenarios that come across depending on the tech stack we use.</p><h4>Bonus Content 1: Spatial Data types in Postgres</h4><p>Postgres doesn’t default with spatial data types. Instead, it has a database extender called <a href="https://postgis.net/">PostGIS</a>, which has the same functionalities as MySQL 8.0’s spatial data types, spatial data functions &amp; even more. For example, with the <a href="https://postgis.net/">PostGIS</a> extension in place, using <a href="https://postgis.net/docs/ST_DWithin.html"><strong>ST_DWithin</strong></a><strong> </strong>function, you can check whether two geometries are within the specified distance of one another.</p><h4>Bonus Content 2: Approach to work with Prisma</h4><p>If you’re using Prisma in your tech stack, this part will benefit you.</p><p>As per the current <a href="https://github.com/prisma/prisma/releases/tag/3.1.1">latest release of Prisma</a>, there is no native support for spatial data types. However, in the <a href="https://www.notion.so/Prisma-Roadmap-50766227b779464ab98899accb98295f">Prisma roadmap</a>, there is a plan to support PostGIS. So hopefully, there will be support for all spatial data types in the future as well. You can find additional information via this ongoing <a href="https://github.com/prisma/prisma/issues/1798">Github issue</a>.</p><p>To reflect the same schema we used to store geo-locations as decimals, we can add the following model in the Prisma schema.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f9eb9dd6a76546354909a13703f00a6/href">https://medium.com/media/1f9eb9dd6a76546354909a13703f00a6/href</a></iframe><p>On the other hand, to use Point spatial data type in our schema,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a01959995e3ca9c77396613b609807d/href">https://medium.com/media/5a01959995e3ca9c77396613b609807d/href</a></iframe><p>Spatial index can’t be added via Prisma schema file. Instead, it needs to be added manually.</p><pre>ALTER TABLE GeoLocation ADD SPATIAL INDEX(position);</pre><p>In both scenarios, we’ll need to use $queryRaw to fetch our data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16a0c650abec1e5c3669b9d210cd6e6f/href">https://medium.com/media/16a0c650abec1e5c3669b9d210cd6e6f/href</a></iframe><h3>Summary</h3><p>Hope this article has helped you navigate through the hurdles you face on using geo locations and SQL databases.</p><p>Thank you for reading!</p><h3>Learn More</h3><ul><li><a href="https://enlear.academy/how-to-implement-a-customized-google-map-with-flutter-d6fb40534cda">How To Implement a Customized Google Map with Flutter</a></li><li><a href="https://enlear.academy/integrating-google-map-with-react-js-dc58b02110e0">How to Integrate Google Maps with React</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5451e54cddec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Enforce Referential Integrity with Prisma]]></title>
            <link>https://javascript.plainenglish.io/how-to-enforce-referential-integrity-with-prisma-1d921b8ff296?source=rss-af9fb87e6fdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d921b8ff296</guid>
            <category><![CDATA[database]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Pasindu Dilshan Gunathilake]]></dc:creator>
            <pubDate>Mon, 20 Sep 2021 11:33:20 GMT</pubDate>
            <atom:updated>2021-09-20T11:33:20.916Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the fourth part of an introductory series of articles on Prisma. If you haven’t checked out previous articles you can find them below.</p><ul><li><a href="https://javascript.plainenglish.io/simplifying-backend-development-with-prisma-564200f31943">Simplify Backend Development with Prisma</a></li><li><a href="https://javascript.plainenglish.io/diving-into-prisma-schema-b278e92dff8b">A Deep Dive into Prisma Schema</a></li><li><a href="https://javascript.plainenglish.io/data-modeling-with-prisma-5c4c37f31d8c">Data Modeling with Prisma</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dz0dbyDCDUHlHfKUK6gflA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@flyd2069?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">FLY:D</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In the previous segments, although we created relationships between tables and records, we didn’t bother about the behaviors amongst these relationships. We didn’t consider the <a href="https://en.wikipedia.org/wiki/Referential_integrity">referential integrity</a>. We need to make sure how the database engine will react when one of these related parent records gets updated or deleted.</p><p>In this article, we will take a look at how this is done via the Prisma schema.</p><h3>Let’s dive in 🤿</h3><p>Now imagine what needs to happen if a user record gets deleted from the User table. Or what needs to happen if a tag applied to a post record gets updated. SQL systems have mechanisms to handle these kinds of scenarios gracefully.</p><p>In MySQL, these can be enforced with either of the referential actions, ON UPDATE or ON DELETE.</p><h4><strong>ON DELETE CASCADE </strong>&amp;<strong> ON UPDATE CASCADE</strong></h4><p>On deleting the parent table record, if set to <strong>ON DELETE CASCADE</strong> will automatically delete the matching row in the child table.</p><p>Likewise, for<strong> ON UPDATE CASCADE</strong> tells the database that when an update occurs in the parent table matching records in the child table must be mapped with the new value.</p><h4><strong>ON DELETE SET NULL &amp; ON UPDATE SET NULL</strong></h4><p>Like <strong>CASCADE</strong>, we can use <strong>SET NULL</strong> on delete and update operations. The foreign key column from the child table (books) will be set to <strong>NULL </strong>when the parent record gets updated or deleted.</p><h4><strong>RESTRICT &amp; NO ACTION</strong></h4><p>Setting <strong>RESTRICT </strong>applies the same effect as omitting <strong>ON DELETE</strong> or <strong>ON UPDATE</strong> clauses. It rejects applying delete or update operations if the parent entity has associated child records.</p><p><strong>NO ACTION</strong> has certain differences in different SQL database engines. But in MySQL, it&#39;s almost equivalent to <strong>RESTRICT</strong>. <strong>NO ACTION</strong> rejects the delete or update operation for the parent table if there is a related foreign key value in the child table.</p><p>So how do we set these with the Prisma schema?</p><p>This is where <a href="https://www.prisma.io/docs/concepts/components/prisma-schema/relations/referential-actions">referential actions in Prisma</a> schema comes into play.</p><p>Before we move in, first we need to update our Prisma version. Because referential actions were defined from Prisma v.2.26.0 onwards.</p><p>I’ll be updating this to the latest release (3.0.2) where referential actions are in General Availability. You can do this by either manually bumping the version in <strong><em>package.json</em></strong> or just hit,</p><pre>npm install prisma@latest --save-dev</pre><p>This will update the Prisma CLI version to the latest version.</p><p>Similarly, you’ll need to update the Prisma client version as well.</p><pre>npm install @prisma/client@latest</pre><blockquote>If you run into error(s) in updating the Prisma version you can clear out node_modules directory and/or npm_cache and retry again.</blockquote><p>Now referential actions can be defined in the <a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#relation">@relation</a> attribute.</p><p>But wait… how did post record(s) got deleted in a cascading manner in the first few articles? 🤔</p><p>Prior to Prisma 2.25.0 following the default referential actions were taking place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*932fyDcLGdRD75wE3G5Elw.png" /><figcaption>Resource: <a href="https://www.prisma.io/docs/guides/upgrade-guides/upgrading-versions/upgrading-to-prisma-3/referential-actions#prisma-2x-default-referential-actions">Default referential actions prior to v.2.25.0</a></figcaption></figure><p>With the latest Prisma version we have following defaults instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*thbPYTPoWSB4sxZPM2Ffag.png" /><figcaption>Resource: <a href="https://www.prisma.io/docs/concepts/components/prisma-schema/relations/referential-actions/#referential-action-defaults">Default referential actions after v.2.26.0</a></figcaption></figure><p>In order for these defaults to reflect in our database, we need to run a migration or do a <a href="https://www.prisma.io/docs/concepts/components/prisma-migrate/db-push">prisma db push</a>.</p><p>Let’s do a migration to track the database schema changes.</p><pre>npx prisma migrate dev --name referential_default_update</pre><p>Now if you try to delete a User an error will be thrown. Let’s do this via Prisma Studio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4oNRwxedSDzfWYNV3Tnwcw.gif" /><figcaption>This ensures that ON DELETE RESTRICT has taken effect between User &amp; Post tables</figcaption></figure><p>Now in order to keep our old behavior of deleting or updating the Post record in a cascading manner once associated User record is deleted, we need to update Post model as follows.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31d9088aedcb5703f1d481149e8aac42/href">https://medium.com/media/31d9088aedcb5703f1d481149e8aac42/href</a></iframe><p>Similar to enforcing referential integrity in 1-m relationship, we can apply this to our previously built explicit m-n relationship as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ffc17f24779a448e1dbd26c38fec8d4/href">https://medium.com/media/8ffc17f24779a448e1dbd26c38fec8d4/href</a></iframe><p>With these changes,</p><ul><li>If you delete a User who created Post(s), relevant Post record(s) will be deleted</li><li>If you delete either a tag or post the relevant tag assignment, the record in TagsOnPosts table will get deleted.</li></ul><blockquote><em>If we have used an implicit m-n relationship between tags &amp; posts we will be unable to use referential actions. Because referential actions in a m-n relationship has to be applied to the join table.</em></blockquote><p>Other referential actions available are,</p><ul><li><a href="https://www.prisma.io/docs/concepts/components/prisma-schema/relations/referential-actions#restrict">Restrict</a> : If applied onDelete prevents deletion. If applied onUpdate referenced field cannot be updated.</li><li><a href="https://www.prisma.io/docs/concepts/components/prisma-schema/relations/referential-actions#noaction">NoAction</a> : Similar to <a href="https://www.prisma.io/docs/concepts/components/prisma-schema/relations/referential-actions#restrict">Restrict</a>. However, differences are there depending on the database on which it is used upon.</li><li><a href="https://www.prisma.io/docs/concepts/components/prisma-schema/relations/referential-actions#setnull">SetNull</a> : Referenced scalar field will be set to null if applied onDelete or onUpdate.</li><li><a href="https://www.prisma.io/docs/concepts/components/prisma-schema/relations/referential-actions#setdefault">SetDefault</a> : Referenced scalar field will be set to default if applied onDelete or onUpdate.</li></ul><p>Depending on the use case of your application domain, you will need to use either one or a few of these referential actions to improve the consistency &amp; reliability of the data stored.</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d921b8ff296" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/how-to-enforce-referential-integrity-with-prisma-1d921b8ff296">How to Enforce Referential Integrity with Prisma</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Modeling with Prisma]]></title>
            <link>https://javascript.plainenglish.io/data-modeling-with-prisma-5c4c37f31d8c?source=rss-af9fb87e6fdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c4c37f31d8c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Pasindu Dilshan Gunathilake]]></dc:creator>
            <pubDate>Sun, 29 Aug 2021 06:57:07 GMT</pubDate>
            <atom:updated>2021-08-29T08:46:41.431Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lFPXzXFdnJTretkN0kVSUA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@charlesdeluvio?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Charles Deluvio</a> on <a href="https://unsplash.com/s/photos/data?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>This is the third part of an introductory series of articles on Prisma. If you haven’t checked out previous articles you can find them below.</p><ul><li><a href="https://javascript.plainenglish.io/simplifying-backend-development-with-prisma-564200f31943">Simplify backend development with Prisma</a></li><li><a href="https://javascript.plainenglish.io/diving-into-prisma-schema-b278e92dff8b">A deep dive into Prisma Schema</a></li></ul><p>We’ve been considering the database logic of a simple blogging scenario where there are two database entities. User &amp; Post.</p><p>In this article we’ll be taking a practical approach in moderating these entities. We will focus on different types of database entity mappings that can take place &amp; how Prisma schema helps you to lift off the heavy load in such scenarios.</p><p>Since the ground that we cover in this article is huge we’ll not be considering how to create CRUD operations depending on the changes we carry out. But you can find the code relevant in divided branches in the <a href="https://github.com/Pasi-D/Prisma-Starter">previous repository we used</a>.</p><p>Divided branches at the end of this article looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VLOcZLCTfZ1JErkIqjEqdA.jpeg" /><figcaption><strong>If you’re seeing these branch names in comments of code segments used in this article that means you’ve reached up-to that point in the same git repository branch.</strong></figcaption></figure><p>Depending on the <a href="https://en.wikipedia.org/wiki/Cardinality_(data_modeling)">cardinality</a> there can be 3 types of relations</p><ol><li>One-to-one (1-1)</li><li>One-to-many (1-m)</li><li>Many-to-many (m-n)</li></ol><p>We’ll take each of these relation types into account &amp; add relevant modifications.</p><h3>One-to-one (1-1) relationships</h3><p>In the modification we will be doing User &amp; Profile entities follow one-to-one mapping. Along the way we’ll be altering few properties in User entity as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AhQW_PV0tu5jhw5H9NcLzw.jpeg" /><figcaption>user-profile one to one mapping introduced to current ERD</figcaption></figure><p>A User record can have zero to one Profile record. A profile record must have a User otherwise it can’t be created.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/249519de346ce2639f56548a44e9266b/href">https://medium.com/media/249519de346ce2639f56548a44e9266b/href</a></iframe><p>Optionally you can name the added foreign key constraint via @relation attribute. In this case both models need to be updated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bb5d3e84699cc014fb7771c1964938b/href">https://medium.com/media/3bb5d3e84699cc014fb7771c1964938b/href</a></iframe><p>Let’s run the migration &amp; see how the SQL query is generated.</p><pre>npx prisma migrate dev --name “UserToProfile”</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rCNomxlzmLIMoH99ihcsZg.jpeg" /><figcaption>SQL queries generated for the user-profile migration</figcaption></figure><p>Depending on the requirement, a Profile can be made mandatory in order to create a User.</p><p>If we try to remove optional type modifier, it will be invalid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RwNGk28p9AX2My4oyp8X8g.png" /><figcaption>Removing optional modifier does not make the relationship mandatory</figcaption></figure><p>To do so from database level we need to keep a foreign key field like <strong><em>profileId</em></strong> in User table.</p><p>So, we’ll add a scalar field <strong><em>profileId</em></strong><em> </em>in User model that can be referenced in the <strong><em>profile</em></strong> relation field &amp; previously added scalar field in Profile should be removed making the User mapping optional.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59cd6ca2d101fee59047b4849a81a88a/href">https://medium.com/media/59cd6ca2d101fee59047b4849a81a88a/href</a></iframe><p>On attempting to make this migration, you will be prompted with a warning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aOtAUrkDYdb6wJ41wmkZ3g.jpeg" /><figcaption>On attempting to run a migration, a warning is prompted to safeguard existing data</figcaption></figure><p>In case if we need to omit either of above conditions. i.e to create either User or Profile records independently &amp; keeping the relationships optional.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5b15dcd4c7a1d89f988af48e86970ab/href">https://medium.com/media/c5b15dcd4c7a1d89f988af48e86970ab/href</a></iframe><blockquote>Decision on choosing the entity to store the foreign key scalar field in a one-to-one mapping is up to you.</blockquote><h4>One-to-one self relations</h4><p>Let’s say in these pandemic times you decide to roll out a nominee feature for the blogging platform. You can nominate a User; In case you get deceased he/she can take over.</p><p>In such a scenario,</p><ul><li>A user can have one or zero nominator(s).</li><li>A user can have one or zero nominee.</li></ul><p>In this situation we have to add a relation field to User model that refers itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53b7510284d3c6679ae18d7fd1b73e19/href">https://medium.com/media/53b7510284d3c6679ae18d7fd1b73e19/href</a></iframe><p>Generated migration file looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fJhYJfATVazsnPQjJcLkug.jpeg" /><figcaption>User-to-User one to one self relation migration SQL</figcaption></figure><h3>One-to-many (1-m) relationships</h3><p>User-Post relation we built so far is having one-to-many relationship. Accordingly, we can</p><ul><li>Create a User with zero or more posts</li><li>Create a Post that’s always related to a User</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3800ee7484ee801a318f4f5b9d26a74d/href">https://medium.com/media/3800ee7484ee801a318f4f5b9d26a74d/href</a></iframe><p>Similar to the previous one to one mapping we can make the Post to User mapping optional. i.e a Post can be made to have zero to one User</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6653f66c7950bff9f034572aae73cd21/href">https://medium.com/media/6653f66c7950bff9f034572aae73cd21/href</a></iframe><p>What happens if I used composite primary key in User table instead of the current id field? How do I need to reflect this in the Prisma schema?</p><p>For such a case following modifications need to be made.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff258ab5b6a73f133ec3932529e6a6ab/href">https://medium.com/media/ff258ab5b6a73f133ec3932529e6a6ab/href</a></iframe><p>If we take a look at the migration changes relevant to this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O10jsc4bX9F8ktg4SPXdFA.jpeg" /><figcaption>Migration SQL generated after adding a composite PK for User</figcaption></figure><h4><em>One-to-many self relations</em></h4><p>Now if you decide to incorporate a blog manager position how would you modify your User entity?</p><p>One way is to add several fields to User model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/baee39ff4b18a832ab3d99401491b6bf/href">https://medium.com/media/baee39ff4b18a832ab3d99401491b6bf/href</a></iframe><p>In this way,</p><ul><li>A User (or a blog member user) can have zero or one Manager</li><li>A Manager can have zero to many Members</li></ul><p>Generated migration file looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1F6VObF5-6jiJljgl0cgeQ.jpeg" /><figcaption>Migration SQL generated for User manage User one to many relationship</figcaption></figure><h3>Many-to-Many (m-n) Relationships</h3><p>In m-n type relationships for relational databases we create an intermediate table called <em>relation table</em> (Also other terms such as <em>Associate table</em>, <em>composition table</em>, <em>join table</em> or <em>pivot table</em> implies the same thing.)</p><p>To get a grip of understanding on this, let’s add Tags to our Post model. A single Post can have zero to many Tag(s) &amp; vice versa.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*53akcEgr0mbGgVmdfLE-0g.jpeg" /><figcaption>Tags to Post is a m-n relationship ERD. TagsOnPosts entity is the relation table</figcaption></figure><p>There’s two ways to define the many-to-many relationship in Prisma Schema depending on the relation table.</p><ol><li>Explicit many-to-many relations</li><li>Implicit many-to-many relations</li></ol><h4><em>Explicit m-n relations</em></h4><p>In an Explicit m-n relation intermediate relation table is represented as a model in the Prisma schema.</p><p>Unlike in implicit m-n relation you will be managing the relation table. So, you can follow a convention that suits best.</p><p>You can include additional meta data such as the date tag was created (<strong><em>assignedAt</em></strong>), assigned person (<strong><em>assignedBy</em></strong>) in the relation table.</p><p>Since every model must have at least one unique criterion that has only required fields, we’ll add a multi field ID with <a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#id-1">@@id</a> attribute. (i.e a composite primary key) If you think this in terms of data the same post can’t have the same tag more than once.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f9ab1a57ff348ac8a61e5865a70f87a/href">https://medium.com/media/2f9ab1a57ff348ac8a61e5865a70f87a/href</a></iframe><p>On running migrations for this change, we get the following SQL query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2SGQXsXUB2Vcwod8H_douA.jpeg" /><figcaption>Tag to Post many to many explicit relation migration</figcaption></figure><h4><em>Implicit m-n relations</em></h4><p>In an Implicit m-n relation, relation fields are defined as lists on the two models. Although the relation table exists in the underlying database, its managed by Prisma &amp; is not manifested within the Prisma schema.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19feb6b805322068c2bc32c635289d56/href">https://medium.com/media/19feb6b805322068c2bc32c635289d56/href</a></iframe><p>The migration SQL query generated is as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XqZ3YFQu0yI1YIHbVd4voQ.jpeg" /><figcaption>Tag to Post implicit m-n relation migration SQL query</figcaption></figure><p>Autogenerated relation table in an implicit m-n relation follows a specific convention.</p><p>In order to follow an implicit m-n relation both the models should have a single field ID (<a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#id">@id</a>)</p><h4>Many-to-many self relations</h4><p>A m-n self-relation is always implicit. A simple example for this is adding followers to User model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d193acb28309b1e4b7db3ba03c56ff0/href">https://medium.com/media/8d193acb28309b1e4b7db3ba03c56ff0/href</a></iframe><p>Migration gives the generated SQL as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aje8qmZAVPFpRUiHrmWUSg.jpeg" /><figcaption>SQL migration generated in User follow User m-n self relation</figcaption></figure><p>Apart from inability to add additional meta data, you can’t moderate <a href="https://www.prisma.io/docs/concepts/components/prisma-schema/relations/referential-actions">referential actions</a> in an implicit m-n relation.</p><h3>Conclusion</h3><p>We have covered majority of relationship types that can take place via our simple blog scenario.</p><p>Hope this article helps you in understanding how to work with Prisma in managing different entity mappings in a relational database.</p><p>In the next article we’ll take a look at one important missing piece in entity mapping that works in Prisma: <a href="https://en.wikipedia.org/wiki/Foreign_key#Referential_actions">Referential Actions</a></p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c4c37f31d8c" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/data-modeling-with-prisma-5c4c37f31d8c">Data Modeling with Prisma</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diving into Prisma Schema]]></title>
            <link>https://javascript.plainenglish.io/diving-into-prisma-schema-b278e92dff8b?source=rss-af9fb87e6fdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/b278e92dff8b</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[relational-databases]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Pasindu Dilshan Gunathilake]]></dc:creator>
            <pubDate>Sat, 28 Aug 2021 16:39:08 GMT</pubDate>
            <atom:updated>2021-08-28T22:31:51.207Z</atom:updated>
            <content:encoded><![CDATA[<h3>A Deep Dive into Prisma Schema</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z6Heqd2AK1yxuY83wb2jIA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@kellysikkema?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kelly Sikkema</a> on <a href="https://unsplash.com/s/photos/plan?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>In a previous article I outlined the benefits on utilizing Prisma for backend development. If you haven’t checked it out yet, read it over here.</p><p><a href="https://javascript.plainenglish.io/simplifying-backend-development-with-prisma-564200f31943">Simplify Backend Development with Prisma</a></p><p>Even though we straightforwardly jumped into writing a simple application logic with Prisma, we didn’t closely looked at most of the aspects involved with it.</p><p>In this article I will take a short walkthrough in explaining about the main configuration file in your Prisma setup : <strong>The Prisma Schema</strong>.</p><p>Similar to the previous article, we will be focusing on how everything works along with a MySQL database.</p><p>All the code that we previously used can be found in the following repository.</p><p><a href="https://github.com/Pasi-D/Prisma-Starter/">GitHub - Pasi-D/Prisma-Starter: A simple project demonstrating simplicity of using Prisma ◭</a></p><h3>Let’s Dive In 🤿</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/743/1*6rYQGXpnAZ8nNHvKQVB2fw.png" /><figcaption>Prisma schema we developed so far</figcaption></figure><p>There are 3 main parts in a Prisma schema.</p><ol><li>Data Sources</li><li>Generators</li><li>Data Model Definition(s)</li></ol><p>Let’s take a look at each of them.</p><h4><a href="https://www.prisma.io/docs/concepts/components/prisma-schema/data-sources">Data Sources</a></h4><blockquote>How Prisma connects to the database is determined in <a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference/#datasource"><strong><em>datasource</em></strong></a><strong><em> </em></strong>block in Prisma schema.</blockquote><p><strong>⚠ You can only specify one </strong><a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference/#datasource"><strong>datasource</strong></a><strong> block within the Prisma schema.</strong></p><figure><img alt="datasource block can have three attributes under it. Provider, url &amp; shadowDatabaseUrl." src="https://cdn-images-1.medium.com/max/1024/1*nyvBzlVSISzdqEMe3OgZWQ.jpeg" /><figcaption>datasource block in a nutshell</figcaption></figure><p>Apart from <strong><em>provider</em></strong> &amp; <strong><em>url</em></strong> fields there is another called <strong><em>shadowDatabaseUrl</em></strong> which comes <a href="https://www.prisma.io/docs/concepts/components/prisma-migrate/shadow-database">handy in managing migrations</a>. We will discuss about this in a future article.</p><p>As of the time of writing this article, Prisma has deprecated support in working with multiple database providers.</p><h4><a href="https://www.prisma.io/docs/concepts/components/prisma-schema/generators">Generators</a></h4><blockquote>The assets that will be created when you run npx prisma generate (or prisma generate if you installed Prisma globally) is determined by how this block is configured.</blockquote><p>A Prisma schema can have one or more generator block(s).</p><p>Following fields can be altered within this block.</p><ul><li><strong>provider</strong> : A mandatory field which defines which Prisma client is created. At the moment only prisma-client-js (i.e Prisma’s JavaScript client) is the only provider made available by Prisma. <br>However, you can specify any other file or <a href="https://www.npmjs.com/">npm</a> package that follows Prisma’s generator specification here. You can check out a list of community build generators from <a href="https://www.prisma.io/docs/concepts/components/prisma-schema/generators#community-generators">here.</a></li><li><strong>output </strong>: An optional field which determines the location for the generated client. By default, this location path is node_modules/.prisma/client</li></ul><p>When you have specified Provider as prisma-client-js following two fields can be parsed within generator block.</p><ul><li><a href="https://www.prisma.io/docs/concepts/components/prisma-schema/generators#binary-targets"><strong>binaryTargets</strong></a> : prisma-client-js uses several engine binaries which are in the form of executable binary files. So, it is important to utilize the correct binary file when you’re deploying the application to a specific platform.<br>By default, this field value is <strong><em>native</em></strong>. For native binary target Prisma detects the current OS &amp; automatically specifies the correct binary target for the client.<br>You can check the list of binaryTargets options from <a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#binarytargets-options">Prisma schema API reference</a>.</li><li><a href="https://www.prisma.io/docs/concepts/components/preview-features/"><strong>previewFeatures</strong></a> : Prisma release certain features that are only in Preview. They are not completely production ready, but you can start adopting them. The complete list of feature flags for Prisma client &amp; Prisma schema can be found <a href="https://www.prisma.io/docs/concepts/components/preview-features/client-preview-features/">here</a>.<br>⚠ If you’re expecting to use a <strong><em>previewFeature</em></strong>(s) cross check with the available Prisma version first.</li></ul><h4><a href="https://www.prisma.io/docs/concepts/components/prisma-schema/data-model">Data Model Definition(s)</a></h4><p>Let’s take a look at the last data model we finished in the previous article.</p><pre>model User {<br>  id        Int     @id @default(autoincrement()) <br>  username  String  @unique <br>  email     String  @unique <br>  posts     Post[] <br>}</pre><pre>model Post { <br>  id        Int     @id @default(autoincrement()) <br>  title     String <br>  content   String? <br>  authorId  Int <br>  author    User?   @relation(fields: [authorId], references: [id]) <br>}</pre><blockquote>As you may have realized by now <strong><em>model </em></strong>block is responsible for an entity in your application domain. They get mapped in to either tables (in case of relational databases) or collections (for no-sql databases).</blockquote><figure><img alt="model name you defined is mapped to underlying database entity by default. Each model consists of fields which maps to attributes of underlying database entity." src="https://cdn-images-1.medium.com/max/891/1*AqjmQ87O9uUjzKwHY1Ns2Q.jpeg" /><figcaption>model block.</figcaption></figure><p>How you name your Prisma model is quite important. By default, it gets mapped with the same name to the relevant database entity.</p><p>With <a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference/#map-1">@@map</a> attribute you can rename the underlying database entity.</p><pre>model User { <br>  id        Int @id @default(autoincrement())  <br>  username  String @unique   <br>  email     String @unique   <br>  posts     Post[]</pre><pre>  @@map(&quot;user&quot;)<br>}</pre><p>Prisma doesn’t follow a specific convention when updating Prisma models via Introspection. It will use the same entity name. In this case to keep the same convention in your models @@map attribute can be utilized.</p><figure><img alt="Let’s say from Introspection you get a different case model. Then you can use @@map attribute to keep the consistency in your application models." src="https://cdn-images-1.medium.com/max/909/1*ePFDhwew8xbmZs2DMO3J3w.jpeg" /><figcaption>Its essential to keep a consistency in how you write your application models</figcaption></figure><p>We’ll stick with the <a href="https://techterms.com/definition/pascalcase">pascal case convention</a> for both model name &amp; database entity names.</p><p>Fields are nested inside the model block. They represent the properties of our database entities.<br>Similar to <a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference/#map-1">@@map</a> used with model names, we can use <a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference/#map">@map</a> attribute to rename the mapped property name in the database entity.</p><p>When it comes to fields there are two types</p><ul><li>Scalar fields</li><li>Relation fields</li></ul><p><strong><em>Scalar Fields</em></strong></p><p>General data types we have used in our models such as <em>Int</em>, <em>String</em> falls into this.</p><p>The data source connector we used earlier determines how each Prisma scalar type get mapped to the underlying native database type.</p><p>Since we are using MySQL, following is how each of these scalar fields get mapped. These fields include certain attributes which helps to moderate the shape of underlying database entity.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fairtable.com%2Fembed%2FshrT2CpylUN01CWIL&amp;display_name=Airtable&amp;url=https%3A%2F%2Fairtable.com%2FshrT2CpylUN01CWIL&amp;image=https%3A%2F%2Fstatic.airtable.com%2Fimages%2Foembed%2Fairtable.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=airtable" width="800" height="533" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cd16c192c73e3b4a54f1d7bb9b928e5/href">https://medium.com/media/3cd16c192c73e3b4a54f1d7bb9b928e5/href</a></iframe><p><strong><em>Relation fields</em></strong></p><p>Some fields on a Prisma model do not have a scalar type. Instead, their type is another model. These fields are relation fields.</p><p>In the data model we build there is a one-to-many relation where a User can have multiple Post record(s) &amp; a Post record has a single User.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*aJUfI4AKHK7DHxHd8n3AHA.png" /><figcaption>author relation field in Post model</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/171/1*hSVEQLqHtnnUinIWLi4MDQ.png" /><figcaption>posts relation field in User model</figcaption></figure><p>These relation fields do not map in the underlying database entity. They are used in generating the Prisma client.</p><p>@relation attribute can only be applied to a relation field. Usually this comes into play when you need to add a foreign key constraint to a scalar field within the model.</p><h3>Attributes</h3><p>So far, we have seen attributes such as <a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference/#map-1">@@map,</a> @relation, @unique etc. These alter the behavior of fields or model block. There are two types of attributes that you can add to your data model.</p><ol><li>Field attributes — Prefixed with @ (Ex: <a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#id">@id</a>)</li><li>Block attributes — Prefixed with @@ (Ex: <a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#map-1">@@map</a>)</li></ol><p>We’ll take a look at few of those attributes that works alongside a relational database.</p><p><a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#id"><strong>@id</strong></a></p><p>This attribute helps to mark the field as the uniquely identifier of the database entity. It maps to the PRIMARY KEY in underlying relational database.</p><p><a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#id-1"><strong>@@id</strong></a></p><p>In order to create a compound primary key in a relational database this can be utilized.</p><p>we can create a composite primary key in User model with username &amp; email to replace the id field.</p><pre>model User { <br>  username  String<br>  email     String<br>  posts     Post[]</pre><pre>  @@id([username, email])<br>}</pre><p>In the same way a composite unique key can be generated with <a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#unique"><strong>@@unique</strong></a></p><pre>model User {  <br>  id         Int      @id @default(autoincrement()) <br>  username   String   <br>  email      String   <br>  posts      Post[]  <br> <br>  @@unique([username, email]) <br>}</pre><p>There are several other attributes in addition to these which you can read in full details in the <a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#attributes">Prisma schema reference</a> documentation.</p><p>Apart from this there are attribute functions as well.</p><p><a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#autoincrement"><strong>autoincrement()</strong></a></p><p>In a relational database such as MySQL this map to AUTO_INCREMENT where database will increment the numerical ID value.</p><p><a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#uuid"><strong>uuid()</strong></a></p><p>This will generate a UUID string.</p><p><a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#now"><strong>now()</strong></a></p><p>This will set the current timestamp. Maps to CURRENT_TIMESTAMP() in MySQL &amp; is compatible with DateTime Prisma scalar type.</p><p>Full list of attribute functions can be referred in <a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference#attribute-functions">Prisma schema reference</a> as well.</p><h4>Conclusion</h4><p>We’ll wrap this article from here. In the next article we’ll take a practical approach in modeling our data considering our simple blogging scenario.</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b278e92dff8b" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/diving-into-prisma-schema-b278e92dff8b">Diving into Prisma Schema</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplify Backend Development with Prisma]]></title>
            <link>https://javascript.plainenglish.io/simplifying-backend-development-with-prisma-564200f31943?source=rss-af9fb87e6fdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/564200f31943</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[prisma]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Pasindu Dilshan Gunathilake]]></dc:creator>
            <pubDate>Sat, 26 Jun 2021 16:27:18 GMT</pubDate>
            <atom:updated>2021-06-27T20:01:23.667Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yv-YXzGZ3AzR3re7fe9KgA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@pepegombos?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Peter Gombos</a> on <a href="https://unsplash.com/@pepegombos?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>If you are a backend or a full-stack developer working in Node.js ecosystem, you probably have worked with different database access tools.</p><p>If you are working with SQL databases like MySQL you might be familiar with <a href="https://en.wikipedia.org/wiki/Object%E2%80%93relational_mapping"><em>ORM</em> (Object Relational Mapper)</a> libraries like <a href="https://sequelize.org/">Sequelize</a>, <a href="https://typeorm.io/">Typeorm</a>, <em>Query builders</em> like <a href="http://knexjs.org/">Knex</a> or native database drivers like <a href="https://github.com/mysqljs/mysql">mysql</a> that will help to <em>write raw SQL queries</em>.</p><p>Each of these tools or methods have their own pros and cons.</p><p>I found out that among these tools <a href="https://www.prisma.io/?utm_source=Prisma%20Ambassador&amp;utm_medium=Blog%20post&amp;utm_campaign=Prisma%20AP%20Pasindu%20Dilshan">Prisma</a> is way more developer friendly.</p><p>In this article I will give a beginner walkthrough to Prisma and make you see how we can develop flexible &amp; scalable backends.</p><h3>What is Prisma?</h3><blockquote><strong>Prisma is an open source next-generation ORM that allows you to easily manage &amp; interact with your database.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h7H7_ifastIBuFUny8PnZA.png" /><figcaption>Visit <a href="https://www.prisma.io/?utm_source=Prisma%20Ambassador&amp;utm_medium=Blog%20post&amp;utm_campaign=Prisma%20AP%20Pasindu%20Dilshan">Prisma.io</a></figcaption></figure><p>Current Prisma release is comprised with 3 main parts</p><ol><li>Prisma Migrate: An imperative database schema migration tool.</li><li>Prisma Client: An auto-generated and type-safe query builder.</li><li>Prisma Studio: A visual editor for the data in your database.</li></ol><p>Without further explaining let’s start building something, so the ideas behind Prisma will be much visible.</p><h3>Let’s dive in</h3><p>We will take a very basic blog post scenario into account, where a User creates a blog post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uPrKJZgdgmjmbimimyvZ5A.png" /><figcaption>Entity Relationship Diagram (ERD)</figcaption></figure><ul><li>For the sake of simplicity there are only 2 entities: User &amp; Post.</li><li>All data will be stored in a MySQL database.</li><li>Features such as authentication are also discarded for simplicity.</li></ul><p>A minimal TypeScript script for database querying will be built at the end.</p><p>If you need a guide on setting up MySQL on your development environment check out this in <a href="https://www.prisma.io/dataguide/">Prisma’s Data Guide</a>.</p><p><a href="https://www.prisma.io/dataguide/mysql/5-ways-to-host-mysql">5 ways to host MySQL databases | Prisma&#39;s Data Guide</a></p><p>All the code that you find over here can be found in the following repository. Its divided into separate branches for each topic covered in this article.</p><p><a href="https://github.com/Pasi-D/Prisma-Starter">Pasi-D/Prisma-Starter</a></p><p>We will start off with a simple Typescript script &amp; install Prisma first. You can find the starting code in <a href="https://github.com/Pasi-D/Prisma-Starter/tree/0-Initial-Script"><strong><em>0-Initial-Script</em></strong></a> branch.</p><h3>1. Setting up Prisma</h3><p>First, we need to install Prisma as a development dependency so we can use Prisma CLI commands within the project.</p><pre>$ npm install prisma --save-dev</pre><p>You can now invoke Prisma CLI within the directory by prefixing it with <a href="https://docs.npmjs.com/cli/v7/commands/npx"><em>npx</em></a>. Let’s initialize Prisma schema file with following command.</p><pre>$ npx prisma init</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*xIv4gyYw2-TrE1E7T-qwsQ.png" /></figure><p>This will create a Prisma directory with a <strong><em>schema.prisma</em></strong> file and an <em>.env</em> file.</p><p>You can move this <em>.env </em>file to root i.e the same level as <em>package.json</em>.</p><h4><em>Wait what’s Prisma Schema?</em></h4><blockquote><strong>Prisma schema is the main configuration file in your Prisma setup. It serves as the source of truth for your database schema and the models in the application.</strong></blockquote><p>You can use Prisma schema to,</p><ul><li>Generate correct data source client code (Prisma Client). This acts as the query builder for your data.</li><li>Generate migrations to update the database schema.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*CzqDRuQbyvo9jGOppQSzLA.png" /><figcaption>How our Prisma.schema will look like in the end</figcaption></figure><p>Prisma schema consist of following parts</p><ol><li>Data source : Defines the connection to data source.</li><li>Generators : Defines what clients need to generated based on data model.</li><li>Data model definition(s) : Your application model(s)</li></ol><p><em>Default schema generated uses PostgreSQL as the </em><strong><em>provider</em></strong><em>. So, the first thing to do is to switch this to ```mysql```.</em></p><pre>datasource db {<br>  provider = &quot;mysql&quot;<br>  url      = env(&quot;DATABASE_URL&quot;)<br>}</pre><p>In order to connect to our database, <strong><em>url</em></strong> field needs to be changed. Instead of hardcoding this you can <a href="https://www.prisma.io/docs/concepts/more/environment-variables">set it as an environment variable</a>.</p><p>This needs to be specified in the following general format.</p><pre>DATABASE_URL=mysql://USER:PASSWORD@HOST:PORT/DATABASE</pre><h3>2. Creating database schema with migrations</h3><blockquote><strong>With </strong><a href="https://www.prisma.io/docs/concepts/components/prisma-migrate/"><strong>Prisma Migrate</strong></a><strong> you can keep your Prisma schema in sync with your database schema. It can also aid you to maintain existing data in your database.</strong></blockquote><p>Let’s jump into changing Prisma schema suitable to our scenario. We can start writing our data model.</p><pre>model User {<br>  id        Int     @id @default(autoincrement()) <br>  username  String  @unique <br>  email     String  @unique <br>  posts     Post[] <br>}</pre><pre>model Post { <br>  id        Int     @id @default(autoincrement()) <br>  title     String <br>  content   String? <br>  authorId  Int <br>  author    User?   @relation(fields: [authorId], references: [id]) <br>}</pre><p>If this model seems a bit tedious &amp; difficult to grasp the idea of how it will map into our database schema following visual representation will help you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/990/1*FwXtbO8b5qthfWmDM-2OTw.png" /><figcaption>Mapping between Prisma Schema &amp; Database Entities(Tables)</figcaption></figure><p>Our Prisma schema has several attributes that represent how table fields should be.</p><ul><li>@id — Primary keys</li><li>@unique — Unique Keys</li><li>@default — Default values</li><li>@relation — Relationship between two tables</li></ul><p>You can find more in detailed at <a href="https://www.prisma.io/docs/reference/api-reference/prisma-schema-reference/#attributes">attributes section of Prisma schema reference.</a></p><p>In order to generate migrations,</p><pre>$ npx prisma migrate dev --name init</pre><p>This will,</p><ol><li>Generate SQL migration file for this migration.</li><li>Runs generated migration file against database.</li><li>Generate Prisma client and update it in the <em>package.json</em> dependency list if not available.</li></ol><p>If you need to make changes to your database schema all you have to do is make relevant changes to Prisma schema then run Prisma migration command.</p><p>If you have used <a href="https://typeorm.io/">TypeORM </a>this process might be familiar. TypeORM can also automatically generate migration files with schema changes you make. <br>But the difference is, in TypeORM you need to manage separate Model files which maps with the migration files. With Prisma you only need to modify model(s) in Prisma Schema file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Wm9ZauRcCMTORlXZcomGAg.gif" /><figcaption>Comparison between Prisma &amp; Other ORMs in terms of Migration</figcaption></figure><p>We’ll dig deeper into database migrations with Prisma in a future article.</p><p>There are several more game changers in Prisma 🚀</p><h3>3. Database Introspection</h3><blockquote><strong>Prisma is capable of generating data model in Prisma schema for an existing database schema. This is done with </strong><a href="https://www.prisma.io/docs/concepts/components/introspection"><strong>Introspection</strong></a><strong>.</strong></blockquote><p>Say you don’t want to use Prisma migration &amp; you’re doing migration with plain SQL or any other migration tool. With Prisma you can re-introspect your database &amp; re-generate Prisma schema then reflect these changes in your Prisma client (Which we’ll see ahead).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*8XAp2fpbwZ9LcNbeXm9tFw.png" /><figcaption><a href="https://www.prisma.io/docs/concepts/overview/what-is-prisma#sql-migrations-and-introspection">If for some reasons, you can not or do not want to use Prisma Migrate, you can still use introspection to update your Prisma schema from your database schema.</a></figcaption></figure><blockquote>In this way you can gradually adopt Prisma to an existing application without making huge compromises.</blockquote><h3>4. Prisma Client</h3><blockquote><a href="https://www.prisma.io/docs/concepts/components/prisma-client"><strong>Prisma client</strong></a><strong> plays the key part in writing your application logics. It’s an auto-generated type-safe query builder.</strong></blockquote><p>In case if Prisma client is not there in your package.json dependency list, its better to install <em>@prisma/client</em> package as a dependency.</p><pre>npm install @prisma/client</pre><p>Whenever Prisma schema is modified, you need to invoke <strong><em>prisma generate</em></strong> to reflect those changes in your Prisma client.</p><p>Let’s make the changes in the <strong><em>app.ts</em></strong> for querying data.</p><p><em>(P.S: In your console </em><strong><em>npm run serve</em></strong><em> will run the script)</em></p><p>First you need to import Generated Prisma client and create a Prisma object.</p><pre>import { PrismaClient } from &quot;@prisma/client&quot;;</pre><pre>const prisma = new PrismaClient();</pre><p>To create a user record</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6b44e0f28050df1bddf6f4035debd66/href">https://medium.com/media/b6b44e0f28050df1bddf6f4035debd66/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kp8W-BGMsvHvgrSYuiapng.gif" /><figcaption>All types are auto-generated based on the shape of model(s).</figcaption></figure><p>To create multiple posts</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8efce20521b36329be39a656d4fe40e2/href">https://medium.com/media/8efce20521b36329be39a656d4fe40e2/href</a></iframe><p>To create a User with post(s)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfa868a0050569fba3e405891384c6ed/href">https://medium.com/media/dfa868a0050569fba3e405891384c6ed/href</a></iframe><p>To query all users.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8d0a440f5a4e0efedaa706928d84bc11/href">https://medium.com/media/8d0a440f5a4e0efedaa706928d84bc11/href</a></iframe><p>To find a user by email, but need only username &amp; post titles.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64191638816631cbcc639b08429f3ed0/href">https://medium.com/media/64191638816631cbcc639b08429f3ed0/href</a></iframe><blockquote>Since the types are auto-generated based on the data model we defined in Prisma schema, every aspect from writing application logic to managing codebase is a lot easier. We don’t need to write any boilerplate code at all.</blockquote><h3>5. Seed Data</h3><p>In some cases, as soon as we create our database schema, we need to update some database table(s) with records to work with. To do this we can seed our database. <br>Prisma has an integrated seeding functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KoUKP9twY3U38vwAv1ELkw.png" /><figcaption>Prisma db seed is still in preview</figcaption></figure><p><a href="https://github.com/prisma/prisma/releases/tag/2.25.0">Currently</a>, this is still a preview feature &amp; not recommended to use in production environment.</p><p>This will be fully available in upcoming Prisma releases.</p><p>To make this work for now, first we’ll need <a href="https://www.npmjs.com/package/ts-node"><em>ts-node</em></a> &amp; <a href="https://www.npmjs.com/package/@types/node">node types</a> as dev dependencies.</p><pre>npm install ts-node @types/node --save-dev</pre><p>We need to modify package.json script as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/172f007e1304ea011173119597fba413/href">https://medium.com/media/172f007e1304ea011173119597fba413/href</a></iframe><p>Seed file needs to be in same location as Prisma schema file. An example is given below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f9f850526e76a613a979be298cf50bc/href">https://medium.com/media/7f9f850526e76a613a979be298cf50bc/href</a></iframe><p>To seed this data,</p><pre>$ npx prisma db seed — preview-feature</pre><h3>6. Prisma Studio</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*urulXYiPyxCaHVjkGiGsgQ.png" /><figcaption>Data stored can be visualized with Prisma Studio</figcaption></figure><p>Prisma studio is a visual studio for the data in your database.</p><p>You can run it with,</p><pre>$ npx prisma studio</pre><p>In this way you will not probably need to integrate a database administration tool such as <a href="https://www.phpmyadmin.net/">phpMyAdmin</a> just to visualize your data.</p><h3>Conclusion</h3><p><a href="https://www.prisma.io/?utm_source=Prisma%20Ambassador&amp;utm_medium=Blog%20post&amp;utm_campaign=Prisma%20AP%20Pasindu%20Dilshan">Prisma</a> has lots of features for an ORM &amp; certainly makes the developers life easier.</p><p>Apart from the ones we’ve discussed there are many more powerful features that will be added in future ahead. Support for MongoDB &amp; SQL Server, schema visualization are just few of them. You can view the plan ahead at <a href="https://www.notion.so/prismaio/Prisma-Roadmap-50766227b779464ab98899accb98295f">Prisma Roadmap</a>. Prisma also has a thriving developer community from all around the globe.</p><p>Hope this article has helped you in understanding the basic flows of Prisma &amp; why it’s such a powerful tool for backend development. If you have any questions or feedback, comment down below.</p><p>Thanks for reading!</p><p><em>More content at </em><a href="http://plainenglish.io/"><strong><em>plainenglish.io</em></strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=564200f31943" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/simplifying-backend-development-with-prisma-564200f31943">Simplify Backend Development with Prisma</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</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 Version React Native Applications]]></title>
            <link>https://pasindu-dilshan.medium.com/managing-configurable-versioning-in-react-native-876ef4b31c23?source=rss-af9fb87e6fdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/876ef4b31c23</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[versioning]]></category>
            <dc:creator><![CDATA[Pasindu Dilshan Gunathilake]]></dc:creator>
            <pubDate>Sun, 23 May 2021 18:33:10 GMT</pubDate>
            <atom:updated>2021-10-26T10:57:08.779Z</atom:updated>
            <content:encoded><![CDATA[<h4>Managing Configurable Versioning in a React Native App</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1T_xNJrleBzxJGlfKC77sg.jpeg" /></figure><p>Versioning is a critical component of your app upgrade &amp; maintenance strategy.</p><p>If you’re a developer with a certain level of experience you know that it’s not a good idea to keep constants like API endpoints, Secret keys hardcoded around the codebase.</p><p>To address this what we normally do is to keep an <em>.env</em> file with configurations as key-value pairs &amp; access them universally at any point in the codebase.</p><p>What if we can do the same thing for versioning a react native application?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*6VtUVthkAmw07d9YPmk19g.gif" /></figure><p>In this article, we’re going to take a look at how we can configure versioning in react native applications to make the development flow smoother.</p><p><strong><em>As a bonus at the end of the article, we’ll see how we need to alter an app automation platform such as a </em></strong><a href="https://appcenter.ms/"><strong><em>visual studio app centre</em></strong></a><strong><em> with these changes.</em></strong></p><h3>Let’s get started 🏁</h3><p>We’ll start with a fresh react native project. I prefer to use <a href="https://github.com/react-native-community/react-native-template-typescript">react native community-built typescript template</a>.</p><pre>npx react-native init RNVersioner --template react-native-template-typescript</pre><p>In order to access custom constants in react native we need to install <a href="https://github.com/luggit/react-native-config"><strong>react-native-config</strong></a>.</p><pre>yarn add react-native-config</pre><p>(<a href="https://github.com/luggit/react-native-config#setup"><em>Setup guidelines</em></a><em> can be different depending on the react-native version you’re using. Adjust them accordingly.</em>)</p><p>This library exposes config variables to your JS/TS code in React Native, supporting iOS, Android and Windows. It advocates for <a href="https://12factor.net/config">twelve-factor configuration</a> which summed up, is:</p><blockquote>Apps sometimes store config as constants in the code. This is a violation of twelve-factor, which requires strict separation of config from code. Config varies substantially across deploys, code does not.</blockquote><p>Next, we’ll create a <em>.env.dist</em> file and include versioning values there. Most of the applications use <a href="https://semver.org/"><strong><em>semantic versioning</em></strong> (<strong><em>semver</em></strong>)</a>. Also, there can be release flavours (alpha, beta, etc.). Considering that,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/24480eb3efdbad8708d6172fb6040222/href">https://medium.com/media/24480eb3efdbad8708d6172fb6040222/href</a></iframe><p>Next, we’ll change platform-specific codes that need to be changed in order to make this work. We’ll be focusing on Android &amp; iOS in this article for the sake of simplicity.</p><h3>Changing Android version name and version number</h3><p>Android has two settings available to define version information.</p><ol><li><strong><em>VersionCode</em> : </strong>This is a positive integer used as an internal version number. This number is used only to determine whether one version is more recent than another, with higher numbers indicating more recent versions. This is not the version number shown to users. The Android system use <em>versionCode</em> value to protect against downgrades by preventing users from installing an APK with a lower <em>versionCode</em> than the version currently installed on their device. <br>(⚠️ <em>Warning: The greatest value Google Play allows for versionCode is 2100000000.</em>)</li><li><strong>VersionName : </strong>This is the string used as the version number shown to users.</li></ol><p>For more information on android versioning, read the <a href="https://developer.android.com/studio/publish/versioning"><strong>android developer guide on publishing versions</strong></a>.</p><p>We can define these two values either on the Android Manifest file or in <em>app/build.gradle. </em>But we need to follow<em> </em>a versioning schema to generate <em>versionCode</em> &amp; <em>versionName</em>. So, we’ll include this in the gradle configurations.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c54055053318719ea046cb56679a9e9e/href">https://medium.com/media/c54055053318719ea046cb56679a9e9e/href</a></iframe><p><em>Above is a gradle recipe I discovered after referring to many articles. You can customize according to your own choice.</em></p><h3>iOS Version Number &amp; Build Number</h3><p>Unlike in Android, for iOS version and the build numbers work together to uniquely identify a particular App Store submission for an app. These two values reside in <em>Info.plist</em> file as follows.</p><ul><li><strong>The version number</strong> is saved with the key <strong><em>CFBundleShortVersionString</em></strong></li><li><strong>The build number</strong> is associated with the key <strong><em>CFBundleVersion</em></strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*XwMk5Ytc8MrTIAjvv4HFnQ.png" /><figcaption>In xcode right-click (or click while holding the control key) in the display you can select “Show Raw Keys/Values” from the popup menu to see the machine-readable versions of these keys</figcaption></figure><p>For additional information &amp; a guide on version numbers &amp; build numbers refer to this <a href="https://developer.apple.com/library/archive/technotes/tn2420/_index.html">archived technote</a>.</p><p>To expose environment variables to <em>info.plist</em> there are some extra steps that need to be followed. You can refer them over <a href="https://github.com/luggit/react-native-config#availability-in-build-settings-and-infoplist">here at react-native-config setup guide.</a></p><p>Once that’s done you can modify <em>info.plist</em> similar to below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e844372731ae7b0a63d52848b8e4f45/href">https://medium.com/media/7e844372731ae7b0a63d52848b8e4f45/href</a></iframe><p>That’s pretty much it.</p><p>Now in order to run the application in debug mode or to generate a release <em>.apk</em> or <em>.ipa</em> a copy of <em>.env.dist</em> needs to be made with required adjustments.</p><pre>cp .env.dist .env</pre><p>Make sure to include <em>.env</em> in your <em>.gitignore</em> to avoid unnecessary changes.</p><h3>Displaying version name in the application</h3><p>This is straightforward. However, as a good case practice, I keep an environment variable accessor with a caching mechanism.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6f8415863b8fd5d93cc2f2acbd3377d/href">https://medium.com/media/b6f8415863b8fd5d93cc2f2acbd3377d/href</a></iframe><p>You can invoke this <strong><em>getAppVersionName</em></strong> utility function in any of your components in order to display the version name.</p><h3>Bonus: Connecting to an automation platform</h3><p>So how do you work with this implementation with app automation platforms like <a href="https://appcenter.ms/"><strong>App Center</strong></a> or even tools like <a href="https://fastlane.tools/"><strong>Fast Lane</strong></a>?</p><p>Let’s take a look at how we can work with App Center to change our application builds.</p><p>I’m assuming that you have prior experience in connecting the app centre to a repository and setting up the build pipeline for a react native project. <br>So we’ll be skipping a few steps ahead from setting up an app centre project &amp; running your first build ⏭️</p><p>App centre provides build scripts to customize your builds. In order to make our application work now, we need to make a copy of <em>.env.dist</em> and update the environment variables. We can use <a href="https://docs.microsoft.com/en-us/appcenter/build/custom/scripts/#post-clone">Post-clone</a> or <a href="https://docs.microsoft.com/en-us/appcenter/build/custom/scripts/#pre-build">Pre-build</a> scripts for this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42765ddcafc280b0616b474377237381/href">https://medium.com/media/42765ddcafc280b0616b474377237381/href</a></iframe><p>Now, all we need is to update app centre build configurations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*LKGaEx22JpLNsHaBl2-a9g.png" /><figcaption>Update the environment variables in app centre</figcaption></figure><p>That’s it.</p><p>Now you are in charge of managing versions of your builds via the App centre.</p><h3>Learn More</h3><ul><li><a href="https://enlear.academy/upload-images-to-aws-s3-in-react-native-0-60-f20c547a963c">Upload Images to AWS S3 in React Native 0.60+</a></li><li><a href="https://enlear.academy/a-simple-method-to-extract-touch-gesture-data-from-a-react-native-app-9d0cbade9a7f">React-Native: Did you know that We Can Extract Touch Gestures?</a></li><li><a href="https://enlear.academy/how-to-build-serverless-mobile-application-using-aws-amplify-react-native-for-android-26eef1d12757">Serverless Mobile App with AWS Amplify and React Native</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=876ef4b31c23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Improvising styling in react native]]></title>
            <link>https://pasindu-dilshan.medium.com/improvising-styling-in-react-native-d9a1787df129?source=rss-af9fb87e6fdf------2</link>
            <guid isPermaLink="false">https://medium.com/p/d9a1787df129</guid>
            <category><![CDATA[style-guides]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[ui]]></category>
            <dc:creator><![CDATA[Pasindu Dilshan Gunathilake]]></dc:creator>
            <pubDate>Sat, 01 May 2021 10:48:45 GMT</pubDate>
            <atom:updated>2021-05-02T14:19:10.764Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*18oc57etqP8kIWQemuoFEg.jpeg" /></figure><p>In this article we’ll be discussing on building a robust stylesheet guideline for react native. This guideline is built with the aid of <a href="https://reactnativeelements.com/docs/customization#theming"><em>theming provided by react native elements</em></a> along with <a href="https://reactnative.dev/docs/stylesheet"><em>Stylesheet API in react native</em></a>. However at the end of this article you will see that its not just limited to react native elements at all. Along with this we’ll see how some blockers such as code separation, module resolution issues in compilation, type safety… etc. were resolved as well.</p><h3>Why even bother with theming ? 🤔</h3><p>Features like theming or even internationalization are common to be found in majority of the applications found in the market. (Ex: Reddit, Facebook, Messenger) Perhaps your application may not need it at this point. But if you’re planning to build a scalable application, then it will be pretty hard to integrate these features when the codebase matures with time. So, it’s convenient to plan ahead and adopt them at an early stage.</p><h3>Let’s get started 🚀</h3><p>We’ll start off with the typescript react native template from react native community.</p><pre>npx react-native init StyleProApp --template react-native-template-typescript</pre><h3>Structuring your Application Matters 🧱</h3><p>How you structure your codebase is opiniated &amp; it may differ depending on the context of your application. But the general norm or a good case practice in terms of maintaining your UI is to break down your components as much as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/782/1*CEuDyNymjKgqX3nrL9AyJw.png" /><figcaption>How you structure your project is up to you.</figcaption></figure><p>Recently I came across <a href="https://atomicdesign.bradfrost.com/">atomic design</a>. Which is good to adopt because it provides flexibility, maintainability &amp; testability in the long run.</p><h3>Skipping ahead for the stylesheet ⏭️</h3><p>Since we’ll be utilizing React Native Elements,</p><pre>yarn add react-native-elements</pre><p>Next steps are to create a theming file and pass it down as a prop into the theming provider which wraps the entire application. <br>But since we’re working with typescript, first will need to extend our theme type from react native element’s theme. Instead of adopting Typescript’s declaration merging method <a href="https://reactnativeelements.com/docs/customization/#typescript-definitions-extending-the-default-theme">as mentioned in the official documentation’s guideline</a> I’ve created a separate set of types.</p><blockquote>p.s Current version of react native elements (3.4.1) doesn’t export some of its types such as <strong>Colors </strong>from core modules. They need to be imported via the <strong>dist/</strong> directory in node modules.</blockquote><p>Edit: For some weird reason on metro server I couldn’t split my types to a custom declaration file. So I included all the types &amp; interfaces within the theme file.</p><p>Adding custom path alias in <em>tsconfig.json</em></p><pre>....<br>&quot;paths&quot;: {<br>   ....<br>   &quot;themes&quot;: [&quot;./assets/theme&quot;],<br>},<br>...</pre><p>So, our initial theme file looks like this. Note that I have exported a hook for using theme context as well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90c947ed4171b0f5fd9b6f59b3088bb0/href">https://medium.com/media/90c947ed4171b0f5fd9b6f59b3088bb0/href</a></iframe><p>Then we pass this down to the theme prop in the Theme Provider.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed666362af74cae50b42cbe3bf640e08/href">https://medium.com/media/ed666362af74cae50b42cbe3bf640e08/href</a></iframe><h3>Using theme values &amp; separation of styles 🎨</h3><p>For starters let’s just say that I need to style my progressive indicator via this approach. We’ll create a separate style file and build a custom hook like function for styling.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7335d3cd3fd8d5b69fb4138d190842b/href">https://medium.com/media/e7335d3cd3fd8d5b69fb4138d190842b/href</a></iframe><p>Then using this inside your component is a bit simple.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d100aa0e07a24ad69fab23657f83c62/href">https://medium.com/media/3d100aa0e07a24ad69fab23657f83c62/href</a></iframe><h3>Module Resolution ✔️</h3><p>Although you may be able to fix the typescript errors that occur for importing contents from path aliases via tsconfig.json, metro server will still throw errors for unresolved paths. To fix this what you need to do is add a dev dependency.</p><pre>yarn add --dev babel-plugin-module-resolver</pre><p>Then edit your babel.config.js,</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f43b1a176f5cc720af56d0322fc62cf0/href">https://medium.com/media/f43b1a176f5cc720af56d0322fc62cf0/href</a></iframe><p>Although above approach is mainly utilizing <a href="https://github.com/react-native-elements/react-native-elements/blob/6713620e73333829224e1d8195974f252b703de2/src/config/ThemeProvider.tsx">react-native-element’s ThemeProvider</a>, you can build your own ThemeProvider using <a href="https://reactjs.org/docs/context.html">React’s Context API</a> &amp; plug it in the same manner. So its just a matter of spending a little more time on writing your own context provider &amp; context consumer.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FLmNwrBhejkK9EFP504%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FLmNwrBhejkK9EFP504%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExcGZ5Z3lrbjNuMzlodnA3ODdrb25wenp2OWNrZjlrYXpibXhua2hpYyZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2FLmNwrBhejkK9EFP504%2Fgiphy_s.gif&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/91c2efa4198c043f3f400f216214650e/href">https://medium.com/media/91c2efa4198c043f3f400f216214650e/href</a></iframe><h3>Good Case Practices in managing your styles ✍️</h3><p>It’s very important for your application to be responsive across majority of devices. Using flexbox layout at almost all the time and using relative values for certain styling properties (Ex: top: 20%, etc.) are couple of good choices for this. Refer the <a href="https://reactnative.dev/docs/next/style">guideline provided by react native documents for this</a>.</p><p>However, in certain scenarios like defining font sizes or defining fixed margin values you will need to make sure that they are scaled depending on the device pixel ratio. A good library that will help to achieve this is <a href="https://github.com/nirsky/react-native-size-matters">react-native-size-matters</a> which is a peer dependency of react native elements.</p><p>The entire code for above is available in the following <em>work in progress repository</em>.</p><p><a href="https://github.com/Pasi-D/React-Native-Starter-Kit">Pasi-D/React-Native-Starter-Kit</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d9a1787df129" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>