<?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 Liam Martens on Medium]]></title>
        <description><![CDATA[Stories by Liam Martens on Medium]]></description>
        <link>https://medium.com/@liammartens?source=rss-be04e4939010------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*wiL2r_tYNQ5eBkBsO5HYyw.jpeg</url>
            <title>Stories by Liam Martens on Medium</title>
            <link>https://medium.com/@liammartens?source=rss-be04e4939010------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 02:56:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@liammartens/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[Using your local .npmrc inside a VS Code development container]]></title>
            <link>https://liammartens.medium.com/using-your-local-npmrc-inside-a-vs-code-development-container-e31f2b36a335?source=rss-be04e4939010------2</link>
            <guid isPermaLink="false">https://medium.com/p/e31f2b36a335</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[vscode]]></category>
            <category><![CDATA[development-container]]></category>
            <category><![CDATA[devcontainer]]></category>
            <category><![CDATA[npm]]></category>
            <dc:creator><![CDATA[Liam Martens]]></dc:creator>
            <pubDate>Sat, 10 Apr 2021 12:51:52 GMT</pubDate>
            <atom:updated>2021-04-10T12:51:52.447Z</atom:updated>
            <content:encoded><![CDATA[<h3>Using your local .npmrc inside a VS Code development container</h3><p>Often times it is useful to use a system-wide .npmrc file to authenticate to private repositories. However when working with development containers in VS Code you lose this context as the container is, of course, fully isolated.</p><p>However you can actually mount your global .npmrc file inside your container with some clever configuration inside your devcontainer.json file.</p><pre>{<br>    &quot;image&quot;: &quot;node:14&quot;,<br>    &quot;containerUser&quot;: &quot;node&quot;,<br>    &quot;mounts&quot;: [<br>      &quot;source=${localEnv:HOME}${localEnv:USERPROFILE}/.npmrc,target=/home/node/.npmrc,type=bind,consistency=cached&quot;<br>    ]<br>}</pre><p>Using the mounts configuration, it is possible to attach the system-wide .npmrc file to your container as a docker volume. This way your development container will be able to use your previously authenticated npm repositories. Awesome!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e31f2b36a335" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using GraphQL Code Generator (TypeScript) with Apollo]]></title>
            <link>https://liammartens.medium.com/using-graphql-code-generator-typescript-with-apollo-f36d7afe4f7e?source=rss-be04e4939010------2</link>
            <guid isPermaLink="false">https://medium.com/p/f36d7afe4f7e</guid>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[file-upload]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[graphql]]></category>
            <dc:creator><![CDATA[Liam Martens]]></dc:creator>
            <pubDate>Wed, 27 Jan 2021 19:03:59 GMT</pubDate>
            <atom:updated>2021-01-27T20:59:07.297Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*YpaQfRzqmnlCXDjP0QqBDQ.jpeg" /></figure><p>Let’s say you have a GraphQL API and now you want to start accepting file uploads. This is possible using the following the Upload Scalar type from graphql-upload, as detailed here <a href="https://www.apollographql.com/docs/apollo-server/data/file-uploads/">https://www.apollographql.com/docs/apollo-server/data/file-uploads/</a> (keep in mind you will need to use the graphql-multipart-request-spec to actually upload files, as explained here <a href="https://github.com/jaydenseric/graphql-multipart-request-spec">https://github.com/jaydenseric/graphql-multipart-request-spec</a>)</p><p>However, when using GraphQL Code Generator with TypeScript you might run into an issue with the Upload scalar type as this is not a default GraphQL scalar type. To fix this we will need to add 2 things:</p><h4>1. Update the schema to accept the scalar Type</h4><p>First off we need to tell the schema the scalar type actually exists. We can do this by simply adding scalar Upload to the top of the schema file.</p><h4>2. Update the codegen configuration</h4><p>Now we need to update our configuration so it will use the correct typing for the newly defined scalar type. We can do this by using the scalars configuration key. (as can be found here <a href="https://graphql-code-generator.com/docs/plugins/typescript">https://graphql-code-generator.com/docs/plugins/typescript</a>)</p><p>The simplest way to configure this is as follows:</p><pre>config:<br>      scalars:<br>        Upload: import(&#39;graphql-upload&#39;).FileUpload</pre><p>All set! Now the resulting code generation will have something like this:</p><pre>export type Scalars = {<br>  ...<br>  Upload: import(&#39;graphql-upload&#39;).FileUpload;<br>};</pre><p>This will way you can make your custom file upload resolvers completely type safe!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f36d7afe4f7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Fauna + Next.js/TypeScript To-do app]]></title>
            <link>https://liammartens.medium.com/creating-a-fauna-next-js-typescript-to-do-app-5cfe1fa938e4?source=rss-be04e4939010------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cfe1fa938e4</guid>
            <category><![CDATA[apollo-client]]></category>
            <category><![CDATA[faunadb]]></category>
            <category><![CDATA[to-do-list-app]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Liam Martens]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 18:17:05 GMT</pubDate>
            <atom:updated>2021-01-12T18:18:21.903Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*n5cSmen3U_CV6VRBmM0LBA.jpeg" /></figure><p>Recently I have started exploring the NoSQL solution called <a href="https://fauna.com/">Fauna</a> to integrate it with one of my side projects. It took some digging and exploring to get it set-up and well integrated with my intended set-up, but I now have a solid set-up for future Next.js/Fauna projects. So let’s dive into making our little to-do app</p><h3>Step 1: Create FaunaDB database</h3><p>Firstly let’s start by creating a new database from the <a href="https://dashboard.fauna.com/">Fauna dashboard</a>. You can name it anything you want, for the purpose of this guide I will simply call it todo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*LFKL3lusQIIM8nbOQovGBA.png" /><figcaption>Creating new Fauna Database</figcaption></figure><p>After creating the database we will have to create a Admin secret for it so we can manage the instance from our local machine. You do this in the Security tab of the database. After creating the key, copy it somewhere for usage in our Next.js app later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*bqR7F3SpEhddtjx69ZbW9Q.png" /><figcaption>Creating a new Admin type key for managing the Database</figcaption></figure><p>As far as Fauna is concerned this is all for the moment. Let’s continue by setting up our Next.js project.</p><h3>Step 2: Setting up Next.js</h3><p>We’ll go with a basic create-next-app setup for this guide. Find an appropriate spot to create your project and run the following command to bootstrap our Next.js app.</p><pre>npx create-next-app</pre><h3>Step 3: Setting up TypeScript</h3><p>Next.js has splendid and well documented TypeScript support so we will simply be following their basic steps on adding TS to the project, with some minor adjustments.</p><p>First off create a tsconfig.json in our project root. This will be automatically populated by Next.js next time we run our project. To do this quickly you can run</p><pre>touch tsconfig.json</pre><p>Secondly we will need to install typescript and the appropriate typing packages for react and node as follows</p><pre>npm install --save-dev typescript @types/react @types/node</pre><pre># or if you&#39;re using Yarn<br>yarn add -D typescript @types/react @types/nod</pre><p>We are almost ready to support TypeScript in our project, the last step is setting up our tsconfig.json . For an initial setup we can simply run the project to auto-populate it. The output will say something along the lines of We detected TypeScript in your project and created a tsconfig.json file for you.</p><pre>npm run dev</pre><pre># or<br>yarn dev</pre><p>After having run the dev command you can stop the project again and the tsconfig.json should look something like this:</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;target&quot;: &quot;es5&quot;,<br>    &quot;lib&quot;: [<br>      &quot;dom&quot;,<br>      &quot;dom.iterable&quot;,<br>      &quot;esnext&quot;<br>    ],<br>    &quot;allowJs&quot;: true,<br>    &quot;skipLibCheck&quot;: true,<br>    &quot;strict&quot;: false,<br>    &quot;forceConsistentCasingInFileNames&quot;: true,<br>    &quot;noEmit&quot;: true,<br>    &quot;esModuleInterop&quot;: true,<br>    &quot;module&quot;: &quot;esnext&quot;,<br>    &quot;moduleResolution&quot;: &quot;node&quot;,<br>    &quot;resolveJsonModule&quot;: true,<br>    &quot;isolatedModules&quot;: true,<br>    &quot;jsx&quot;: &quot;preserve&quot;<br>  },<br>  &quot;include&quot;: [<br>    &quot;next-env.d.ts&quot;,<br>    &quot;**/*.ts&quot;,<br>    &quot;**/*.tsx&quot;<br>  ],<br>  &quot;exclude&quot;: [<br>    &quot;node_modules&quot;<br>  ]<br>}</pre><p>Personally, I would add 2 more settings to ensure better type safety. (however this is up to you whether to include these or not)</p><pre>{<br>    &quot;noImplicitAny&quot;: true,<br>    &quot;strictNullChecks&quot;: true<br>}</pre><p>At this point you might have noticed we still have .js in our project, such as pages/_app.js and pages/index.js . To finalize our setup we will need to rename these to .tsx .</p><p>You will also see a file called pages/api/hello.js , which is an API route. This one can be renamed to hello.ts as we do not require JSX support in these API routes.</p><p>Now you will see a few errors regarding missing types in both the _app.tsx and hello.ts files. (the latter we will remove later, but let’s keep it for now)</p><p>To fix these errors we need to add typings to both of these as follows</p><pre># for _app.tsx<br>import { AppProps } from &#39;next/app&#39;<br>import &#39;../styles/globals.css&#39;</pre><pre>function MyApp({ Component, pageProps }: AppProps) {<br>  return &lt;Component {...pageProps} /&gt;<br>}</pre><pre>export default MyApp</pre><pre># for hello.ts<br>import { NextApiRequest, NextApiResponse } from &#39;next&#39;<br>export default (req: NextApiRequest, res: NextApiResponse) =&gt; {<br>  res.statusCode = 200<br>  res.json({ name: &#39;John Doe&#39; })<br>}</pre><h3>Step 4: Start building our GraphQL schema</h3><p>Technically Fauna does not require you to use GraphQL per se, however it is required to “easily” achieve type safety between the datastore and our app. (that and GraphQL is snazzy and cool)</p><p>For this guide we will have a very simple schema, but we will also use some custom resolvers so you we can dive deeper into the functionality Fauna provides.</p><p>Let’s start by thinking about what data we need to store. Very simply, we need the todo itself, the date and time it was created and it’s status. We can easily make a GraphQL type out of this and it would look something like this:</p><pre>enum TodoStatus {<br>    NEW,<br>    INPROGRESS,<br>    DONE<br>}</pre><pre>type Todo {<br>    todo: String!<br>    status: TodoStatus!<br>}</pre><p>You may notice it does not contain a datetime (or similar) field. This is because Fauna will keep track of this by default and inject it into our schema with the _ts field.</p><p>To dive more into Fauna specific functionality we will also add 2 queries called todosByStaus and todosByText . The first query will find todos by their status and the latter will do a search by their text. (in reality you would most likely implement this in next.js — however for the purpose of showing what you can do in Fauna we are making a resolver for it)</p><p>Lastly, we will also add a query called allTodos . This one will automatically be handled by Fauna, which means we do not need to build our own resolver for it.</p><p>Our final schema would look something like this:</p><pre>enum TodoStatus {<br>    NEW,<br>    INPROGRESS,<br>    DONE<br>}<br>type Todo {<br>    todo: String!<br>    status: TodoStatus!<br>}<br>type Query {<br>    allTodos(): [Todo!]!<br>    todosByStatus(status: TodoStatus): [Todo!]! <a href="http://twitter.com/resolver">@resolver</a>(paginated: true)<br>    todosByText(text: String): [Todo!]! <a href="http://twitter.com/resolver">@resolver</a>(paginated: true)<br>}</pre><p>Let’s save our schema in our project as graphql/schema.gql before we switch back to Fauna to import our GraphQL schema.</p><h3>Step 5: Importing our schema</h3><p>We can now import our schema into Fauna either using the UI or the import endpoint. For the UI, you can import your schema under the GraphQL tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1wmYZGeXSFRxQ_3fSahpeQ.png" /><figcaption>Import new GQL schema</figcaption></figure><p>To import a schema using the endpoint, you can run below command (dont’t forget to add your previously saved FAUNA_KEY )</p><pre>curl -X POST --data &quot;@./graphql/schema.gql&quot; -H &quot;Authorization: Bearer &lt;FAUNA_KEY&gt;&quot; <a href="https://graphql.fauna.com/import">https://graphql.fauna.com/import</a></pre><p>After importing there are a few things to note.</p><p>First of all when we return to the GraphQL section in the Fauna UI, we can now use the GraphQL Playground. This also allows you to see what our imported schema will look like in it’s final form after being adjusted by Fauna.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdNyrvJtnQXMcU1V2JtqCA.png" /><figcaption>We see some default mutations and a default query called findTodoByID (alongside our manually defined queries)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7eICUeXmgtTSG8qlfy90Bg.png" /><figcaption>We can also see the default Fauna fields called _id and _ts, which are the unique ID and the timestamp respectively. Aside from this we also see a TodoInput type, which is used for the createTodo mutation.</figcaption></figure><p>Secondly, we can explore “Functions” section, which now contains 2 functions. These match our previously defined queries, but they don’t do anything yet.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jnPxf0VWBdGqkdbzLW7giA.png" /><figcaption>Newly created functions by Fauna. At this time they will throw a “Not Implemented” exception.</figcaption></figure><p>Lastly, when we check out the “Collections” section, we can also see Fauna has created a new collection for us called “Todo” . This matches our GraphQL type name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rtaj-LDUYdxPLCxQtUtWVQ.png" /><figcaption>Newly created collection by Fauna matching our GraphQL type.</figcaption></figure><h3>Step 6: Making our custom queries work</h3><p>For our custom queries to work we will need to write the Fauna functions that go along with them. You can do this manually in the UI, but it would be wise to keep these function definitions in a central place such as our Next.js project.</p><p>To do this we will start by making a file named graphql/migrations/{yyymmddhhmm}_IntialCreate.fql . I am calling it a migration, simply because I needed a name for it and the term seemed appropriate. (there is an actual migration tool for Fauna called <a href="https://github.com/fauna/faunadb-migrate">faunadb-migrate</a> , however it is 2 years old and unofficial)</p><p>For our functions to work we will need a few things to be created/updated by our migration. As we will search through our Fauna collection, we will need to make use of indexes (<a href="https://docs.fauna.com/fauna/current/tutorials/indexes/#preparation">Index tutorial from Fauna</a>). We will need 2 of them, the first one will be to retrieve all our todos, the second one will be used to retrieve the todos by their tag. We need the first one to implement our todosByText function. Indexes can only perform exact match searches, which means we need to implement custom filtering logic after fetching all our todos in the first place. Our migration script will also handle updating the previously created functions with appropriate logic for them to actually work.</p><p>Let’s start by making our first index. We will name our first index allTodos and the source of the index will be Todo . The script to create this will look as follows:</p><pre>CreateIndex({<br>    name: &quot;allTodos&quot;,<br>    source: Collection(&quot;Todo&quot;)<br>})</pre><p>To make our migration a little smarter, we will also add some conditional logic to create the index only if it does not exist yet and otherwise update the existing index by the same name. The result would be the below:</p><pre>Let(<br>    {<br>        index_params: {<br>            name: &quot;allTodos&quot;,<br>            source: Collection(&quot;Todo&quot;)<br>        }<br>    },<br>    If(<br>        Exists(Index(&quot;allTodos&quot;)),<br>        Update(Index(&quot;allTodos&quot;), Var(&quot;index_params&quot;)),<br>        CreateIndex(Var(&quot;index_params&quot;))<br>    )<br>)</pre><p>We will apply the same logic and steps for our 2nd index, called todosByStatus, which will handle searching by status. This is possible using an index as it will be an exact search and it would look something like this:</p><pre>Let(<br>    {<br>        index_params: {<br>            name: &quot;todosByStatus&quot;,<br>            source: Collection(&quot;Todo&quot;),<br>            terms: [<br>                { field: [&quot;data&quot;, &quot;status&quot;] }<br>            ]<br>        }<br>    },<br>    If(<br>        Exists(Index(&quot;todosByStatus&quot;)),<br>        Update(Index(&quot;todosByStatus&quot;), Var(&quot;index_params&quot;)),<br>        CreateIndex(Var(&quot;index_params&quot;))<br>    )<br>)</pre><p>The only addition here is the terms field in our parameters. This simply defines which fields can be searched by.</p><p>Next we will make use of our indexes in our functions. Let’s start with the simplest one, which is the todosByStatus function. For this to work we can simply use the built-in Match function from Fauna to use our Index and find the relevant results (or matches). The function body would look like this:</p><pre>Query(<br>    Lambda(<br>        [&quot;status&quot;, &quot;size&quot;, &quot;before&quot;, &quot;after&quot;],<br>        Let(<br>            {<br>                match: Match(Index(&quot;todosByStatus&quot;), Var(&quot;status&quot;)),<br>                page: If(<br>                  Equals(Var(&quot;before&quot;), null),<br>                  If(<br>                    Equals(Var(&quot;after&quot;), null),<br>                    Paginate(Var(&quot;match&quot;), { size: Var(&quot;size&quot;) }),<br>                    Paginate(Var(&quot;match&quot;), { after: Var(&quot;after&quot;), size: Var(&quot;size&quot;) })<br>                  ),<br>                  Paginate(Var(&quot;match&quot;), { before: Var(&quot;before&quot;), size: Var(&quot;size&quot;) })<br>                )<br>            },<br>            Map(Var(&quot;page&quot;), Lambda(&quot;x&quot;, Get(Var(&quot;x&quot;))))<br>        )<br>    )<br>)</pre><p>WOW! Where did all the other stuff come from?<br>Aha that is because, when returning multiple items Fauna expects it to be paginated. This can easily be done by using the Paginate function, however it does require us to accept some additional parameters such as size , before and after . We also need to create some logic to pass the arguments on accordingly. More info on pagination can be found <a href="https://docs.fauna.com/fauna/current/tutorials/indexes/pagination.html">here</a> and the conditional code is explained <a href="https://docs.fauna.com/fauna/current/api/graphql/functions#paginated">here</a>.</p><p>Now for our migration script, we will also apply the same logic as we did previously so we only try to create a new function when it does not exist yet and update it if it does. Our final script for the todosByStatus function will look as follows.</p><pre>Let(<br>    {<br>        function_params: {<br>            name: &quot;todosByStatus&quot;,<br>            body: Query(<br>                Lambda(<br>                    [&quot;status&quot;, &quot;size&quot;, &quot;before&quot;, &quot;after&quot;],<br>                    Let(<br>                        {<br>                            match: Match(Index(&quot;todosByStatus&quot;), Var(&quot;status&quot;)),<br>                            page: If(<br>                            Equals(Var(&quot;before&quot;), null),<br>                            If(<br>                                Equals(Var(&quot;after&quot;), null),<br>                                Paginate(Var(&quot;match&quot;), { size: Var(&quot;size&quot;) }),<br>                                Paginate(Var(&quot;match&quot;), { after: Var(&quot;after&quot;), size: Var(&quot;size&quot;) })<br>                            ),<br>                            Paginate(Var(&quot;match&quot;), { before: Var(&quot;before&quot;), size: Var(&quot;size&quot;) })<br>                            )<br>                        },<br>                        Map(Var(&quot;page&quot;), Lambda(&quot;x&quot;, Get(Var(&quot;x&quot;))))<br>                    )<br>                )<br>            )<br>        }<br>    },<br>  If(<br>    Exists(Function(&quot;todosByStatus&quot;)),<br>    Update(Function(&quot;todosByStatus&quot;), Var(&quot;function_params&quot;)),<br>    CreateFunction(Var(&quot;function_params&quot;))<br>  )<br>)</pre><p>For our loose todosByText function, we will need to manually implement the searching functionality in our UDF or User-Defined function. We can make use of a few built-in functions such as Filter, Lowercase and ContainsStr to make this work. Without all our pagination overhead, this would look something like:</p><pre>Filter(<br>    Match(Index(&quot;allTodos&quot;)),<br>    Lambda(<br>        &quot;x&quot;,<br>        ContainsStr(LowerCase(Select([&quot;data&quot;, &quot;todo&quot;], Get(Var(&quot;x&quot;)))), LowerCase(Var(&quot;text&quot;)))<br>    )<br>)</pre><p>Basically we select all our todos, and filter it, similar to the JS filter method, using a predicatae Lambda function which checks whether our searched text can be found in the todo text. Combining this with our pagination and conditional checks we get the following script:</p><pre>Let(<br>  {<br>    function_params: {<br>      name: &quot;todosByText&quot;,<br>      body: Query(<br>          Lambda(<br>            [&quot;text&quot;, &quot;size&quot;, &quot;before&quot;, &quot;after&quot;],<br>            Let(<br>              {<br>                filter: Filter(<br>                  Match(Index(&quot;allTodos&quot;)),<br>                  Lambda(<br>                    &quot;x&quot;,<br>                    ContainsStr(LowerCase(Select([&quot;data&quot;, &quot;todo&quot;], Get(Var(&quot;x&quot;)))), LowerCase(Var(&quot;text&quot;)))<br>                  )<br>                ),<br>                page: If(<br>                  Equals(Var(&quot;before&quot;), null),<br>                  If(<br>                    Equals(Var(&quot;after&quot;), null),<br>                    Paginate(Var(&quot;filter&quot;), { size: Var(&quot;size&quot;) }),<br>                    Paginate(Var(&quot;filter&quot;), { after: Var(&quot;after&quot;), size: Var(&quot;size&quot;) })<br>                  ),<br>                  Paginate(Var(&quot;filter&quot;), { before: Var(&quot;before&quot;), size: Var(&quot;size&quot;) })<br>                )<br>              },<br>              Map(Var(&quot;page&quot;), Lambda(&quot;x&quot;, Get(Var(&quot;x&quot;))))<br>            )<br>          )<br>        )<br>    }<br>  },<br>  If(<br>    Exists(Function(&quot;todosByText&quot;)),<br>    Update(Function(&quot;todosByText&quot;), Var(&quot;function_params&quot;)),<br>    CreateFunction(Var(&quot;function_params&quot;))<br>  )<br>)</pre><p>This is all we need to make our functions work, so let’s import it into Fauna. To do this we can use the Fauna shell either in the UI (which allows loading from a file) or in your local terminal. For the latter you will need to install and configure it before running following command (more info — <a href="https://github.com/fauna/fauna-shell">fauna-shell</a>)</p><pre>fauna eval --file=./graphql/migrations/202101121515_InitialCreate.fql</pre><p>If you are working with the Shell in the Fauna UI, you can simply use the “Open file” option (or copy and paste it)</p><h3>Intermezzo: Try it our in Fauna UI</h3><p>Just to see it in action, let’s make a few todos and see our new function and indexes in action.</p><p>Start by going to the Fauna UI, open the Todo collection and create a few document with something like the following:</p><pre>{<br>  &quot;todo&quot;: &quot;Wash up&quot;,<br>  &quot;status&quot;: &quot;NEW&quot;<br>}</pre><p>Now we can jump into the GraphQL playground and test out our queries. I created 1 todo in status NEW called “Wash up” and 1 todo in status DONE called “Take a shower”. To get the 2nd item, I could either query it by status or perform a search on the word shower. Let’s see both in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rJ79La-Bh14uK6e33vPP2w.png" /><figcaption>Query by status DONE, gives back the 2nd item.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WdPHzyyMQ3PlWru2zhwDbA.png" /><figcaption>We can also use the todosByText query to get the same result.</figcaption></figure><h3>Step 7: Define the queries and mutations in code</h3><p>Before we can start using GraphQL in our project we need to install Apollo+GraphQL as well as define the queries and mutations we are going to use in the project. We will store them in graphql/queries and graphql/mutations respectively.</p><p>Let’s start with the dependencies, to add them to our project we will simply use npm or yarn</p><pre>npm install graphql @apollo/client</pre><pre># or for yarn<br>yarn add graphql @apollo/client</pre><p>For the queries, we will need 3 files, one for each of the queries we defined earlier (allTodos, todosByText and todosByStatus ). Each file will simply contain a single query which we will subsequently be able to use in our project. The resulting queries would be something like this</p><pre>import { gql } from &#39;<a href="http://twitter.com/apollo/client">@apollo/client</a>&#39;;</pre><pre>export const allTodosQuery = gql`<br>    query AllTodos($cursor: String) {<br>        allTodos(_cursor: $cursor) {<br>            data {<br>                _id,<br>                _ts,<br>                todo,<br>                status<br>            },<br>            before,<br>            after<br>        }<br>    }<br>`;</pre><pre>export const todosByStatus = gql`<br>    query TodosByStatus($status: TodoStatus!, $cursor: String) {<br>        todosByStatus(status: $status, _cursor: $cursor) {<br>            data {<br>                _id,<br>                _ts,<br>                todo,<br>                status<br>            },<br>            after,<br>            before<br>        }<br>    }<br>`;</pre><pre>export const todosByText = gql`<br>    query TodosByText($text: String!, $cursor: String) {<br>        todosByText(text: $text, _cursor: $cursor) {<br>            data {<br>                _id,<br>                _ts,<br>                todo,<br>                status<br>            },<br>            after,<br>            before<br>        }<br>    }<br>`;</pre><p>We will also add a createTodo mutation in graphql/mutations/createTodo.ts, which uses the exact same format.</p><pre>import { gql } from &#39;<a href="http://twitter.com/apollo/client">@apollo/client</a>&#39;;</pre><pre>export const createTodoQuery = gql`<br>    mutation CreateTodo($todo: String!) {<br>        createTodo(data: {<br>            todo: $todo,<br>            status: NEW<br>        }) {<br>            _id,<br>            _ts,<br>            todo,<br>            status<br>        }<br>    }<br>`;</pre><h3>Step 8: Generate TypeScript files</h3><p>With our queries and mutations added we should generate some types. To do this, we can use <a href="https://graphql-code-generator.com/">graphql-code-generator</a></p><p>First we need to install the codegen cli and the appropriate plugins for our project. We are going to use the default typescript plugins, as well as the Apollo React plugin. We can install them by running the following install command:</p><pre>npm install --save-dev @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo</pre><pre># or for yarn<br>yarn add -D @graphql-codegen/cli @graphql-codegen/typescript @graphql-codegen/typescript-operations @graphql-codegen/typescript-react-apollo</pre><p>Secondly we need to add a configuration file called codegen.yml in our project root. This is used by the generator and should contain a few bits and should look something like this:</p><pre>overwrite: true<br>schema:<br>  - <a href="https://graphql.fauna.com/graphql">https://graphql.fauna.com/graphql</a>:<br>      headers:<br>        Authorization: &quot;Bearer ${FAUNA_KEY}&quot;<br>generates:<br>  graphql/generated/graphql.ts:<br>    documents:<br>      - graphql/queries/*.ts<br>      - graphql/mutations/*.ts<br>    plugins:<br>      - &quot;typescript&quot;<br>      - &quot;typescript-operations&quot;<br>      - &quot;typescript-react-apollo&quot;</pre><p>So what does all of this mean?</p><ul><li>schema, this is the location of the GraphQL schema. We are pointing it to the Fauna URL as opposed to our local file, because our local file does not contain fields such as _id and _ts . We also add a headers section, so we can pass along our FAUNA_KEY, which is necessary for authenticating with Fauna.</li><li>generates , Here we define what we want to generate. In our case we are simply generating some TypeScript code. This is done based on the documents specification within, pointing to our previously created files, and uses 3 plugins: “typescript”, “typescript-operations” and “typescript-react-apollo”.</li></ul><p>This is all we need to be able to generate our TypeScript, so let’s give it a go by running the codegen command</p><pre>FAUNA_KEY=&lt;FAUNA_KEY&gt; yarn graphql-codegen</pre><h3>Step 9: Setup Apollo</h3><p>Let’s start by removing the default api/hello.ts file as we don’t need it.</p><p>Secondly we should provide our FAUNA_KEY to Next.js by adding it to a file called .env.local . This should look as follows (it will be prefixed with NEXT_PUBLIC_ as we will be using the key in our front-end. Of course, in reality you should not use an admin key for this and properly secure the API or wrap the Fauna API with your own GraphQL layer)</p><pre>NEXT_PUBLIC_FAUNA_KEY=&lt;FAUNA_KEY&gt;</pre><p>With this in place, we can create a ApolloClient . Let’s make a file in graphql in client.ts and add the following code</p><pre>import { ApolloClient, InMemoryCache } from &#39;<a href="http://twitter.com/apollo/client">@apollo/client</a>&#39;;</pre><pre>export const ApiClient = new ApolloClient({<br>    uri: &#39;<a href="https://graphql.fauna.com/graphql&#39;">https://graphql.fauna.com/graphql&#39;</a>,<br>    cache: new InMemoryCache(),<br>    headers: {<br>        authorization: `Bearer ${process.env.FAUNA_KEY}`<br>    }<br>});</pre><p>Lastly we need to provide our client to the React app using the ApolloProvider . We wrap this in our custom app component as it should be available everywhere. The resulting _app.tsx will look as follows</p><pre>import &#39;../styles/globals.css&#39;<br>import { AppProps } from &#39;next/app&#39;<br>import { ApolloProvider } from &#39;<a href="http://twitter.com/apollo/client">@apollo/client</a>&#39;;<br>import { ApiClient } from &#39;../graphql/client&#39;;</pre><pre>function MyApp({ Component, pageProps }: AppProps) {<br>  return (<br>    &lt;ApolloProvider client={ApiClient}&gt;<br>      &lt;Component {...pageProps} /&gt;<br>    &lt;/ApolloProvider&gt;<br>  )<br>}</pre><pre>export default MyApp</pre><h3>Step 10: Putting all the pieces together</h3><p>Now we have all our pieces in place, we can start putting it to use. Let’s start by showing a list of our Todos.</p><p>I will not be applying any styling in this guide, so it will just be plain HTML, but it will at least work!</p><p>First off we can get rid of all the contents in our homepage index.tsx file and replace it with the following code</p><pre>import * as React from &#39;react&#39;;<br>import { useAllTodosQuery } from &#39;../graphql/generated/graphql&#39;;</pre><pre>export default function Home() {<br> const { data, loading } = useAllTodosQuery();</pre><pre>if (loading) {<br>   return (<br>     &lt;p&gt;Loading ...&lt;/p&gt;<br>   );<br> }</pre><pre>if (!data || !data.allTodos.data.length) {<br>  return (<br>    &lt;p&gt;No tasks&lt;/p&gt;<br>  );<br> }</pre><pre>return (<br>  &lt;div&gt;<br>    &lt;ul&gt;<br>      {data.allTodos.data.map(t =&gt; (<br>        &lt;li key={t?._id}&gt;<br>          &lt;p&gt;{t?.todo}&lt;/p&gt;<br>          &lt;small&gt;{t?.status}&lt;/small&gt;<br>        &lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br> );<br>}</pre><p>You can now run the app and open the page, you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/802/1*ejDQz_r1MekYN1GQoBlPlg.gif" /></figure><p>Awesome!</p><p>Let’s also add a simple submission form to add new todo’s, so we can put our mutation to the test:</p><pre>import * as React from &#39;react&#39;;<br>import { useAllTodosQuery, useCreateTodoMutation } from &#39;../graphql/generated/graphql&#39;;</pre><pre>export default function Home() {<br> const { data, loading, refetch } = useAllTodosQuery();<br> const [addTodo, addTodoStatus] = useCreateTodoMutation();</pre><pre>const onSubmit = React.useCallback(async (event: React.FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>   event.preventDefault();<br>   const text = event.currentTarget.todo.value;<br>   if (text &amp;&amp; typeof text === &#39;string&#39;) {<br>      event.currentTarget.todo.value = &#39;&#39;;<br>     await addTodo({ variables: { todo: text } });<br>     refetch();<br>   }<br> }, []);</pre><pre>if (loading) {<br>   return (<br>     &lt;p&gt;Loading ...&lt;/p&gt;<br>   );<br> }</pre><pre>if (!data || !data.allTodos.data.length) {<br>  return (<br>    &lt;p&gt;No tasks&lt;/p&gt;<br>  );<br> }</pre><pre>return (<br>  &lt;div&gt;<br>    &lt;form onSubmit={onSubmit}&gt;<br>      &lt;input type=&quot;text&quot; name=&quot;todo&quot; /&gt;<br>    &lt;/form&gt;<br>    &lt;ul&gt;<br>      {data.allTodos.data.map(t =&gt; (<br>        &lt;li key={t?._id}&gt;<br>          &lt;p&gt;{t?.todo}&lt;/p&gt;<br>          &lt;small&gt;{t?.status}&lt;/small&gt;<br>        &lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br> );<br>}</pre><p>And lastly let’s add a search box to search by tag or by text:</p><pre>import * as React from &#39;react&#39;;<br>import { TodoStatus, useAllTodosLazyQuery, useCreateTodoMutation, useTodosByStatusLazyQuery, useTodosByTextLazyQuery } from &#39;../graphql/generated/graphql&#39;;</pre><pre>export default function Home() {<br>  const [searchQuery, setSearchQuery] = React.useState(&#39;&#39;);<br>  const [getAllTodos, allTodos] = useAllTodosLazyQuery();<br>  const [getTodosByStatus, todosByStatus] = useTodosByStatusLazyQuery();<br>  const [getTodosByText, todosByText] = useTodosByTextLazyQuery();<br> const [addTodo, addTodoStatus] = useCreateTodoMutation();</pre><pre>const todosQuery = searchQuery.startsWith(&#39;tag:&#39;) ? todosByStatus : (<br>   !!searchQuery ? todosByText : allTodos<br> );<br> const todos = todosQuery.data &amp;&amp; (<br>   &#39;allTodos&#39; in todosQuery.data<br>    ? todosQuery.data.allTodos<br>    : (&#39;todosByStatus&#39; in todosQuery.data ?  todosQuery.data.todosByStatus : todosQuery.data.todosByText)<br> );</pre><pre>React.useEffect(() =&gt; {<br>    if (searchQuery.startsWith(&#39;tag:&#39;)) {<br>      getTodosByStatus({ variables: { status: searchQuery.replace(&#39;tag:&#39;, &#39;&#39;).toUpperCase() as TodoStatus } })<br>    } else if (!!searchQuery) {<br>      getTodosByText({ variables: { text: searchQuery } })<br>    } else {<br>      getAllTodos();<br>    }<br>  }, [searchQuery]);</pre><pre>const onAddTodoSubmit = React.useCallback(async (event: React.FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>   event.preventDefault();<br>   const text = event.currentTarget.todo.value;<br>   if (text &amp;&amp; typeof text === &#39;string&#39;) {<br>      event.currentTarget.todo.value = &#39;&#39;;<br>     await addTodo({ variables: { todo: text } });<br>   }<br> }, []);</pre><pre>const onSearchSubmit = React.useCallback(async (event: React.FormEvent&lt;HTMLFormElement&gt;) =&gt; {<br>  event.preventDefault();<br>  const query = event.currentTarget.search.value.trim();<br>  if (query &amp;&amp; typeof query === &#39;string&#39;) {<br>    setSearchQuery(query);<br>  }<br>}, []);</pre><pre>if (todosQuery.loading) {<br>   return (<br>     &lt;p&gt;Loading ...&lt;/p&gt;<br>   );<br> }</pre><pre>return (<br>  &lt;div&gt;<br>    &lt;form onSubmit={onAddTodoSubmit}&gt;<br>      &lt;input type=&quot;text&quot; name=&quot;todo&quot; /&gt;<br>    &lt;/form&gt;<br>    &lt;form onSubmit={onSearchSubmit}&gt;<br>      &lt;input type=&quot;search&quot; name=&quot;search&quot; placeholder=&quot;Search&quot; /&gt;<br>    &lt;/form&gt;<br>    &lt;ul&gt;<br>      {todos?.data.map(t =&gt; (<br>        &lt;li key={t?._id}&gt;<br>          &lt;p&gt;{t?.todo}&lt;/p&gt;<br>          &lt;small&gt;{t?.status}&lt;/small&gt;<br>        &lt;/li&gt;<br>      ))}<br>    &lt;/ul&gt;<br>  &lt;/div&gt;<br> );<br>}</pre><p>The implementation of the search is not the prettiest, but it shows off how it woks with Apollo in combination with Fauna.</p><p>All code for this project can be found <a href="https://github.com/LiamMartens/faunadb-nextjs-apollo-typescript">here</a></p><p>Give a thumbs up if you learnt something new 👍</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cfe1fa938e4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>