<?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 Zoran Šaško on Medium]]></title>
        <description><![CDATA[Stories by Zoran Šaško on Medium]]></description>
        <link>https://medium.com/@zoransasko?source=rss-8e90b4376a8d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*8yp6EiVsATElZUbKZuvJxQ.jpeg</url>
            <title>Stories by Zoran Šaško on Medium</title>
            <link>https://medium.com/@zoransasko?source=rss-8e90b4376a8d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 09:14:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zoransasko/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[How to collect user data from chat conversation using OpenAI API]]></title>
            <link>https://zoransasko.medium.com/how-to-collect-user-data-from-chat-conversation-using-openai-api-1849322735ac?source=rss-8e90b4376a8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/1849322735ac</guid>
            <category><![CDATA[chatgpt]]></category>
            <category><![CDATA[openai]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[chatbots]]></category>
            <dc:creator><![CDATA[Zoran Šaško]]></dc:creator>
            <pubDate>Sat, 31 Aug 2024 09:01:23 GMT</pubDate>
            <atom:updated>2024-09-02T12:05:47.721Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-4OTiVjaQQjTkcFv_70OoQ.png" /></figure><p>If you are interested in ways how to collect some user data during conversation, using OpenAI API, this article is made for you.</p><p>In this article we’ll explore two approaches to collect product ordering request data. We’ll suppose that user wants to order some product from our simple chat application and in this process, system will ask the user for the product name, his name and his email. When all data is collected, we’ll print this data in system log. Instead of printing in system log, you can implement sending data somewhere or storing data in local database.</p><p>The final application that we’ll create will look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*4qjt07TqWkWp09-Qn1CVrg.png" /><figcaption>Chat</figcaption></figure><p><strong>First approach — creating custom model</strong></p><p>In this approach, we need to create a custom model where we should make a conversation that is very similar to the conversation that user would make with the system.</p><p>In official documentation for ‘Fine Tuning’:</p><ul><li><a href="https://platform.openai.com/docs/guides/fine-tuning/fine-tuning-examples">https://platform.openai.com/docs/guides/fine-tuning/fine-tuning-examples</a></li></ul><p>and under ‘Tool Calling’ section, we can see how ‘messages’ need to be specified in model, in order to make a model with a data flow from which we can get extract relevant information (product name, user name and email).</p><p>In this approach we need to specify at least 10 example conversations, to make this model usable at bear minimum. The more examples that we specify, model will work better, i.e. it will more easier detect fields that needs to be extracted. This approach wasn’t the best for me because I had only 10 examples and sometimes chat system would ask the wrong question in wrong order or some other problem occurred. This might be resolved with more conversation examples, but I found the easier approach and this second approach will be described in next section.</p><p><strong>Second approach — specify system initial message to collect data</strong></p><p>In this approach, we’ll specify initial system message that will contain all the business logic for collecting the data. Fields that we want to extract will be specified in right order with appropriate data type. It will contain instructions what to so when everything is collected i.e invoke appropriate Python function for storing collected data.</p><p>This example we’ll make in Python, so if you’re not familiar with Python, we’ll work from ground zero.</p><p>So, lets firstly create an virtual environment in folder where we want to have our project, by invoking the following command:</p><pre>python -m venv venv</pre><p>After that, we should activate our virtual environment by writing command:</p><pre>source venv/bin/activate</pre><p>After we have activated virtual environment, we need to install some of the libraries that are needed in project, so we have to create ‘requirements.txt’ file with the following Python libraries:</p><pre>annotated-types==0.7.0<br>anyio==4.4.0<br>certifi==2024.7.4<br>click==8.1.7<br>distro==1.9.0<br>exceptiongroup==1.2.2<br>fastapi==0.112.2<br>h11==0.14.0<br>httpcore==1.0.5<br>httpx==0.27.2<br>idna==3.8<br>openai==1.37.1<br>pydantic==2.8.2<br>pydantic_core==2.20.1<br>python-dotenv==1.0.1<br>sniffio==1.3.1<br>starlette==0.38.2<br>tqdm==4.66.5<br>typing_extensions==4.12.2<br>uvicorn==0.30.6<br>websockets==13.0</pre><p>Then, we need to install requirements in virtual environment by invoking the following command:</p><pre>pip install -r requirements.txt</pre><p>Now, we have installed all the libraries that we need, let’s specify the ‘.env’ file.</p><p>Since we’ll need to specify OpenAI API Key, we have to register and obtain one from:</p><ul><li><a href="https://platform.openai.com/api-keys">https://platform.openai.com/api-keys</a></li></ul><p>and put it in ‘.env’ file:</p><pre>OPENAI_API_KEY = &#39;some_api_key&#39;</pre><p>Now, we are ready to write some chat logic. Chat logic will be created in ‘main.py’ so we’ll start with specifying some imports and specifying which file will be served to the client, when Python server is running (‘index.html’ — which we’ll make later in this article).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f34c216e21d6518acf4243e54a3751b/href">https://medium.com/media/3f34c216e21d6518acf4243e54a3751b/href</a></iframe><p>As you can see from code above, we are initializing the FastAPI which will be used for handling our main route (‘/’ route) and handling the route for web socket (‘/ws’ route).</p><p>We are also specifying the ‘client’ variable which is the OpenAI client object that allows us to invoke chat functionalities from OpenAI API.</p><p>Array ‘conversation_history’ will contain conversation steps between user and a system that is needed in OpenAI API calls so it can know what is the context of previous conversation steps and so it can find what is the next step. We’ll clear this array after we have got all the data that we need.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/92f9f6b2b2c89e83b4b79546c2217b23/href">https://medium.com/media/92f9f6b2b2c89e83b4b79546c2217b23/href</a></iframe><p>We’ve specified that port on which our application is running is port 8000, but we can change this easily to some other value.</p><p>In order for OpenAI to able to detect if some function from the Python, or client side, should be executed, we need to specify it in JSON form like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8df216bbaa0d409cf44814de741a7c8b/href">https://medium.com/media/8df216bbaa0d409cf44814de741a7c8b/href</a></iframe><p>Here we specified the function ‘save_product_order’ with appropriate parameters and their data types. Later in the article we’ll make a Python function with the same name that will be invoked when OpenAI API decides that this function should be invoked.</p><p>The next function that we’ll implement is the function which will invoke OpenAI API, i.e. based on user input it will return some output from OpenAI API.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0136ef6f3df615b8aab6267f4d812739/href">https://medium.com/media/0136ef6f3df615b8aab6267f4d812739/href</a></iframe><p>Variable ‘bot_instructions’ is the most important thing in specifying how OpenAI API will work. In this variable we have to specify what happens if user writes a message where he’s saying that he wants to order some product. It also should be specified what data should be asked from user and what should be done with the data. All this information is stored in ‘bot_instructions’ variable. It’s specified as a first message in ‘conversation_history’ as a message from ‘system’.</p><p>Invoking function ‘await client.chat.completions.create’ we are saying that we want to get response from OpenAI API. We have to specify conversation that we have until now, with ‘tools’ ( which specified what custom function can be invoked from Python side), which model is used and ‘tools_choice’ set to ‘auto’ (means that OpenAI API decides when it should invoke custom tool/function).</p><p>If in response message, ‘tool_calls’ attribute is not specified, it means that OpenAI API didn’t find a need to invoke our custom tool/function based on the current conversation, so we are putting the response of first Chat Completion call in ‘conversation_history’ array and returning that response to the user.</p><p>If in response message, ‘tool_calls’ attribute exists, we’ll put this message in ‘conversation_history’ array to keep track of this call and try to invoke a custom function that is assigned to the appropriate tool call, by invoking</p><pre>await invoke_function_in_tool_calls(tool_calls)</pre><p>After we get response from executing our custom Python function (function ‘save_product_order‘), we’ll put this response in ‘chat_history’ array and for second time invoke OpenAI API to get the result with response that was returned from our custom Python function.</p><pre>second_response = await client.chat.completions.create</pre><p>In this Chat Completions invocation, we specify model, chat history array and we set temperature to be very low, so randomness of response is also very low. With the response of second request we know that our custom function is invoked so we can clear ‘conversation_history’ array and return data to the user.</p><p>Two methods that need to be defined are ‘invoke_function_in_tool_calls’ where we specify which functions that OpenAI API detect that should be invoked from client side, with appropriate Python function, that in this case has the same name. We also need to parse arguments from ‘function_args’ and invoke this function by invoking ‘async function_to_call’. After we get response from function calling we need to format it in appropriate JSON and use it in later Chat Completion function invocation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eea5d22856b392235d7c6ec8302e2432/href">https://medium.com/media/eea5d22856b392235d7c6ec8302e2432/href</a></iframe><p>A function that will invoke storing product order currently logs this data to the console. Here you can specify logic for sending this data to some email or store this data in local database.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37b86dd9c67c30ab19a700c6a42a117c/href">https://medium.com/media/37b86dd9c67c30ab19a700c6a42a117c/href</a></iframe><p>Now we have created all the logic for running the python web page, handling chat completions and the next step is to define ‘index.html’ where all the data will be displayed and where chat functionality can be tested, via web sockets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9ce85a5858cb82cf43b0f5f4056942a/href">https://medium.com/media/e9ce85a5858cb82cf43b0f5f4056942a/href</a></iframe><p>In the HTML from above, we’ve created a simple chat layout with input field for writing a message, submit button that invokes ‘sendMessage’ function. There is also a functionality for receiving web socket messages via ‘onmessage’ method and handling this messages in ‘displayMessage’ function. If received message is from ‘user’, it has different formatting that if message is from ‘assistant’.</p><p>Now we are fully ready to run our application by invoking the following command:</p><pre>python main.py</pre><p>In the console where you invoked a command for running a python script, after you specified all order data you can see that all the order data is logged out from a Python function that handles this data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*drn__vpE6GYcrfjPomMiAw.png" /><figcaption>Python debug log</figcaption></figure><p>Congratulations, you’ve made your first chat application using OpenAI. 😀</p><p>I hope it will help you with your chat application and in case if something is not working with your code, you can download a complete solution from GitHub repository:</p><p>— <a href="https://github.com/zsasko/collect-data-from-conversation-openai-sample">https://github.com/zsasko/collect-data-from-conversation-openai-sample</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1849322735ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Create Web Page Scraper in NodeJs]]></title>
            <link>https://medium.com/weekly-webtips/how-to-create-web-page-scraper-in-nodejs-fcf1fccc1e21?source=rss-8e90b4376a8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcf1fccc1e21</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[cheeriojs]]></category>
            <category><![CDATA[scraping]]></category>
            <category><![CDATA[puppeteer]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Zoran Šaško]]></dc:creator>
            <pubDate>Tue, 06 Apr 2021 07:51:21 GMT</pubDate>
            <atom:updated>2021-04-07T06:47:16.210Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*xsRYaFsEcCGkbUqmdyTddA.png" /></figure><blockquote>Web scraping, web harvesting, or web data extraction is data scraping used for extracting data from websites. The web scraping software may directly access the World Wide Web using the Hypertext Transfer Protocol or a web browser.</blockquote><blockquote>Web scraping is used for contact scraping, and as a component of applications used for web indexing, web mining and data mining, online price change monitoring and price comparison, product review scraping etc.¹</blockquote><p>In this article we’ll explore a way how we can extract some data from Amazon product page, using NodeJs. At the bottom of the article, you can find a source code of the application that we are going to build.</p><p>So let’s start by initializing a NodeJs project, by executing the following command:</p><pre>npm init</pre><p>After project initialization, we’ll add the library that will do the job of loading web page content:</p><pre>npm i puppeteer</pre><p>The main purpose of ‘puppeteer’ library is to fetch website content. It contains an open-source Chromium browser that is used for loading web pages. Library itself can also be used for creating PDF screenshots, automated form submissions, etc.</p><p>The library that we’ll use for extracting/parsing data from the fetched web page is called ‘cheerio‘ and we can add it to our project by invoking the following command:</p><pre>npm i cheerio</pre><p>The last dependency that we’ll use in the project is ‘express‘ which is a minimalistic and flexible NodeJs framework. It can be added by invoking the following command:</p><pre>npm install express — save</pre><p>Now we are ready to start the coding part. We are going to create a file that will contain a method for parsing website content. The attributes that we’ll try to extract from web page content are title, image, price, name of the seller, and features list.</p><p>So, let’s start to find the title of the product, by opening the web page:</p><ul><li><a href="https://www.amazon.com/Fit-Over-Blue-Light-Glasses/dp/B08T14RV4M">https://www.amazon.com/Fit-Over-Blue-Light-Glasses/dp/B08T14RV4M</a></li></ul><p>and by right-clicking on the title and clicking on ‘Inspect Element’ button (or on similarly named button). There we can see that the title element has an id of ‘productTitle’ which will be important in order the extract the value out of it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/921/1*Pp5Ol2x0eHquQTWDYnUSkg.png" /></figure><p>In a similar manner, we can try to find ‘id’ values of other elements that we want to extract from web page content (like price, name of the seller, etc.).</p><p>The method that does all the hard work of launching webpage and parsing webpage content is displayed below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8cfedbd2dba1e127843fe511f39b6977/href">https://medium.com/media/8cfedbd2dba1e127843fe511f39b6977/href</a></iframe><p>As you can see, on the top of ‘scrap’ method are the methods for loading Chromium browser (using ‘puppeteer’ library) and afterward all we are focused on extracting the data.</p><p>The file that will be used for loading the NodeJs application will contain the single endpoint for invoking the scraping job and there we’ll include our ‘scraper_amazon’ which contains a method for scraping web page content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/296ffd5a59be3c1bbda29789b3195a2c/href">https://medium.com/media/296ffd5a59be3c1bbda29789b3195a2c/href</a></iframe><p>After we’ve made both files, we can run the sample by invoking the command:</p><pre>node index.js</pre><p>and that’s it. 😃</p><p>This was a brief tutorial on how web scraping is done using NodeJs and I wish you many projects that is using this nice feature!</p><p>Source code of sample application:</p><ul><li><a href="https://github.com/zsasko/nodejs-web-page-scraper-sample">https://github.com/zsasko/nodejs-web-page-scraper-sample</a></li></ul><p>[1]: “Web scraping”, Wikipedia, <a href="https://en.wikipedia.org/wiki/Web_scraping">https://en.wikipedia.org/wiki/Web_scraping</a>.<br>Accessed 5 April 2021.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcf1fccc1e21" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weekly-webtips/how-to-create-web-page-scraper-in-nodejs-fcf1fccc1e21">How To Create Web Page Scraper in NodeJs</a> was originally published in <a href="https://medium.com/weekly-webtips">Webtips</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 detect Internet Connectivity Change in Android?]]></title>
            <link>https://medium.com/swlh/how-to-detect-internet-connectivity-change-in-android-bdfff33e6a8b?source=rss-8e90b4376a8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdfff33e6a8b</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[connection]]></category>
            <category><![CDATA[internet]]></category>
            <category><![CDATA[connectivity]]></category>
            <category><![CDATA[wifi]]></category>
            <dc:creator><![CDATA[Zoran Šaško]]></dc:creator>
            <pubDate>Mon, 15 Feb 2021 16:20:29 GMT</pubDate>
            <atom:updated>2021-09-13T15:28:48.935Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Nl-TxNrgjGo79F5T4P1tDQ.jpeg" /><figcaption>No Internet Connection Image¹</figcaption></figure><p>In some of the applications we want to know if internet connection has dropped or established. If internet connection is dropped, we might store data in local database and when internet connection is established again, we could send this data to the backend.</p><p>If you want to send the data as soon as internet connection is established you can find ‘<a href="https://developer.android.com/topic/libraries/architecture/workmanager/how-to/define-work">WorkManager</a>’ class useful for that purpose, but scheduling Jobs is not a purpose of this article.</p><p>In this article we’ll explore two approaches for listening internet connectivity change in Android apps. These approaches can detect internet connectivity change from both WiFi and mobile data internet providers.</p><p>So, let’s start. 😃</p><p><strong>Using Broadcast Receiver</strong></p><p>In this approach we are going to use broadcast receiver in order to receive ‘CONNECTIVITY_ACTION<em>’. </em>Apps targeting Android 7.0 (API level 24) and higher do not receive this broadcast if they declare the broadcast receiver in their manifest and that’s the reason why we declared broadcast receiver in abstract class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c128904d10a7caae6b98fee57eb98d60/href">https://medium.com/media/c128904d10a7caae6b98fee57eb98d60/href</a></iframe><p>Methods for registering connectivity change contains also lifecycle observer which unregister broadcast receiver in ‘ON_DESTROY’ lifecycle event, so we don’t need to unregister it manually.</p><p>If we want to start listening internet connectivity change in activity, we could invoke it like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d7f75145179c3919c4c14b67b37b772/href">https://medium.com/media/3d7f75145179c3919c4c14b67b37b772/href</a></iframe><p><strong>Using ‘ConnectivityManager’ class</strong></p><p>The following code demonstrates how we can use ‘ConnectivityManager’ class and appropriate callback for listening network change events:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c490fc82b91b0e565ae6179a55b12736/href">https://medium.com/media/c490fc82b91b0e565ae6179a55b12736/href</a></iframe><p>Callback ‘networkCallback’ will receive connection-established or connection-dropped events. We can see that ‘ConnectivityManager’ class has different methods for registering network callback on different Android API so they can work nicely, on different Android versions.</p><p>If we want to start listening for internet connectivity change, we can start it in ‘onCreate’ method of activity, like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0abce3aa54946d7da1cc3ea01ad3c1d8/href">https://medium.com/media/0abce3aa54946d7da1cc3ea01ad3c1d8/href</a></iframe><p>The only limitation of the code from above is that is supported from Android API version 21 (and that’s why our method for listening internet connectivity has ‘RequiresApi’ annotation), so this method won’t work on applications that are targeted to API version smaller then 21.</p><p>Because we’ve started listener in ‘onCreate’ method, we have to unregister it in ‘onDestroy’ method by invoking the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a7f81b4ab05249e21fd9c211b28a572/href">https://medium.com/media/1a7f81b4ab05249e21fd9c211b28a572/href</a></iframe><p>Method ‘log’ is used for logging messages in android system messages log.</p><p>In this article we have seen two approaches for listening the connectivity change in Android apps and it’s on you which approach you’ll decide to use, based on the minimum Android API version that your app must support and your subjective feeling which approach is the best.</p><p>Happy coding! 😃</p><p>[1]: “How to fix No Internet Connection Problem with Three Solutions”, IT Phobia, <a href="https://itphobia.com/how-to-fix-no-internet-connection/">https://itphobia.com/how-to-fix-no-internet-connection/</a>.<br>Accessed 15 Feb. 2021.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdfff33e6a8b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/how-to-detect-internet-connectivity-change-in-android-bdfff33e6a8b">How to detect Internet Connectivity Change in Android?</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Android Notifications In Unity Game]]></title>
            <link>https://medium.com/swlh/implementing-android-notifications-in-unity-game-15642d316c9e?source=rss-8e90b4376a8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/15642d316c9e</guid>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[games]]></category>
            <dc:creator><![CDATA[Zoran Šaško]]></dc:creator>
            <pubDate>Mon, 01 Feb 2021 17:01:59 GMT</pubDate>
            <atom:updated>2021-02-04T16:48:43.587Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*i_2yARFp4Uv9BkvzmRVULw.jpeg" /><figcaption>Game Notification Preview¹</figcaption></figure><p>What are notifications and why they are important in applications or games?</p><blockquote>A notification is a message that Android displays outside your app’s UI to provide the user with reminders, communication from other people, or other timely information from your app. Users can tap the notification to open your app or take an action directly from the notification.²</blockquote><p>In a context of a game, notification can be used in many different contexts. For example, it can remind a user that he will receive some bonus if he returns to a gameplay, it can notify a user that some other player wants to play with him, it can be used to send some informations about discount for in-app purchase items in the game etc.</p><p>In the sample application that we are going to build in this article, we are going to explore how we can display inactivity notification — i.e. notification that will be scheduled and displayed 3 days after user didn’t started the game. If user opens the game before this 3 days period is done, ‘old’ inactivity notification will be deleted and new inactivity will be scheduled for the next 3 days period.</p><p>Notifications for inactivity are very useful for letting the users know that the game still exists on their phones and that they can resume gameplay. Otherwise they will stop playing the game or even worse, uninstall your game — and that’s what we are trying to prevent.</p><p>At the bottom of this article you can find a sample app that we are going to build in this article, so if you want to check the sample right now you are free to do so.</p><p>So, let’s dig in. 😃</p><p>In an empty Unity project, we’ll add the most important plugin for enabling notifications on Android/iOS platforms, named ‘Mobile Notifications’, via Unity’s Package Manager:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/1*ctk14pwrnX7lXO2ibVLn9g.png" /></figure><p>After we have installed the ‘Mobile Notifications’ in our project, we should see it in ‘Packages’ section of our project.</p><p>Next thing that’s important to import in project is ‘Mobile Notifications Wrapper’ which can be downloaded from here:</p><ul><li><a href="https://github.com/Unity-Technologies/NotificationsSamples">https://github.com/Unity-Technologies/NotificationsSamples</a></li></ul><p>which is basically a wrapper around classes in ‘Mobile Notification’ package and it helps us to implement methods for scheduling notifications very easily.</p><p>So, download ‘NotificationsSample’ from the link above and extract it in ‘Assets’ folder of our project. Rename it from ‘NotificationsSamples-master’ to ‘NotificationsSample’, as it’s displayed on the following photo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/241/1*1T7QR0nUJo4yCm9yjgrIZg.png" /></figure><p>We have imported the required dependencies that will help us display mobile notifications on Android device, so we can start with more interesting part of this project. With designing the layout and writing some code, of course. 😃</p><p>The layout of our application will consist of single label that will display an information when the notification will be scheduled for display.</p><p>In the scene we are going to add a ‘Canvas’ game object (from ‘GameObject -&gt; UI -&gt; Canvas’ menu) and in ‘Canvas Scaler’ we are going to specify the property ‘UI ScaleMode’ to ‘Scale With Screen Size’, so the canvas is scaled appropriately on all screen sizes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/370/1*OdN3-usjj_3RL55U0itMzg.png" /></figure><p>The next game object that we are going to add as a child of ‘Canvas’ is ‘Panel’ where we’ll set color to white with ‘alpha’ property set to 255:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/1*U7NKkmnJ58dSgyZuNcoktw.png" /></figure><p>As a child of ‘Panel’ game object, we are going to add a ‘Text’ game object, that will be used for displaying a message when next notification is going to be scheduled.</p><p>We can rename this ‘Text’ game object to ‘NotificationScheduledText’, so we’ll know for what this object is used. We are also going to change some of the properties of ‘NotificationScheduledText’ game object:</p><ul><li>Position: <strong>X:0, Y:0, Z:0</strong></li><li>Width: <strong>230</strong></li><li>Font size: <strong>34</strong></li><li>Alignment: <strong>center </strong>(both horizontal and vertical)</li><li>Vertical overflow: <strong>overflow</strong></li></ul><p>Before we start making the class that will invoke method for scheduling a notification, let us import a custom notification icons.</p><p>In the following link:</p><ul><li><a href="https://romannurik.github.io/AndroidAssetStudio/icons-notification">https://romannurik.github.io/AndroidAssetStudio/icons-notification</a></li></ul><p>we are going to search for ‘videogame_asset’ (in ‘Clipart’ category) and download zip with notification icons in different resolutions.</p><p>We are going to import only two icons from the zip and firstly the icon from ‘drawable-xhdpi’ folder and this icon we are going to rename to ‘small_notification_icon.png’, and put it in newly created ‘Icons’ folder. Another icon that we are going to copy from extracted zip file is the one in ‘drawable-xxxhdpi’ folder, which we are going to rename to ‘big_notification-icon.png’ and also put in ‘Icons’ folder.</p><p>This is how the icons should be placed inside of ‘Icons’ folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/1*Pwa7KrFCo19WJNUuoH8hrg.png" /></figure><p>The last step of icon customization is to change their type to ‘Sprite’, so click on first of the icons and in ‘Inspector’ panel change ‘Texture Type’ from ‘Default’ to ‘Sprite (2D and UI)’, enable checkbox ‘Read/Write Enabled’ and click ‘Apply’ button. Do the same for the second notification icon.</p><p>Now, we are going to assign these icons to be used in our app. We have to open ‘Mobile Notifications’ section of ‘Project Settings’ panel by opening this panel via ‘Edit -&gt; Project Settings -&gt; Mobile Notifications’ menu and put both notifications icons there as it’s displayed in the picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1014/1*7_D-_eLN7jQXuqtfVFmyjQ.png" /></figure><p>Notification icon identifiers ‘icon_0’ and ‘icon_1’ we are going to use later in coding section.</p><p>The next important step is to add a game object for handling of mobile notifications. So add an empty ‘GameObject’ to the scene, rename it to ‘Game Notification Manager’ and assign to it a ‘GameNotificationManager’ script in game object inspector panel.</p><p>From ‘GameNotificationManager’ script we’ll select ‘No Queue’ value of ‘Mode’ property:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*FBynAToUmtU2l129UiM9Yg.png" /></figure><p>More about queueing modes of ‘GameNotificationManager’ you can learn from here:</p><ul><li><a href="https://github.com/Unity-Technologies/NotificationsSamples">https://github.com/Unity-Technologies/NotificationsSamples</a></li></ul><p>So far, we’ve made a lot of notification configuration setup. We’ve designed the very basic layout of our application and we are ready for writing some code that will actually schedule a notification.</p><p>Let us create empty game object named ‘AppNotificationManager’ and create-and-assign the same named script to it. Double click on ‘AppNotificationManager’ script in order to open it in C# editor and we’ll start writing some code.</p><p>At the top of ‘AppNotificationManager’ class we are going to add some GameObject references and constants (just above ‘Start’ method):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8587ea52f955f47699b894ceb72cd5c9/href">https://medium.com/media/8587ea52f955f47699b894ceb72cd5c9/href</a></iframe><p>We are also going to need the following imports:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc5184731da47bc01c3b04a9e12c19b6/href">https://medium.com/media/cc5184731da47bc01c3b04a9e12c19b6/href</a></iframe><p>After we have added the code from above, we’ll connect references to ‘manager’ and ‘notificationDateText’. So, save all the changes in the ‘AppNotificationManager’ class and return to the scene.</p><p>Select ‘AppNotificationManager’ and keep it selected all the time. Drag ‘GameNotificationManager’ GameObject to ‘Manager’ property of ‘AppNotificationManager’ script and drag ‘NotificationScheduledText’ (located inside of ‘Canvas -&gt; Panel’) to ‘Notification Scheduled Text’ property, like it’s displayed on the picture:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*qTl_WzO3nrzXkhfgI8thgw.png" /></figure><p>Very nice, let us resume writing code in ‘AppNotificationManager’ class and don’t forget to save the scene.</p><p>In ‘Start’ method we are going to invoke some function calls:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d4f6af7c5e2f24585c69b9164e4a0ed0/href">https://medium.com/media/d4f6af7c5e2f24585c69b9164e4a0ed0/href</a></iframe><p>In order to display notifications in Android we need to initialize a channel which will be used for sending notifications.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4693aee2be025e584cbdce7415e05b1a/href">https://medium.com/media/4693aee2be025e584cbdce7415e05b1a/href</a></iframe><p>More about notification channels you can read from here:</p><ul><li><a href="https://developer.android.com/training/notify-user/channels">https://developer.android.com/training/notify-user/channels</a></li></ul><p>The method ‘ScheduleNotificationForUnactivity’, contains method calls for cancelling old notifications and scheduling new notification:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9e25ce703b969cd7ea471751ced483b/href">https://medium.com/media/c9e25ce703b969cd7ea471751ced483b/href</a></iframe><p>Method ‘ScheduleNotificationForUnactivity’ is invoking ‘SendNotification’ method with predefined notification attributes. It takes only one parameter ‘daysIncrement’ which specifies after how many days notification is going to be displayed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d273990deb7451e4c6770fbcd7df72c/href">https://medium.com/media/3d273990deb7451e4c6770fbcd7df72c/href</a></iframe><p>Method that will display a scheduled notification timestamp is called ‘DisplayPendingNotification’ using ‘notificationScheduledText’ game object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/871173adb68cf48e5b9dbd0e5083b0c5/href">https://medium.com/media/871173adb68cf48e5b9dbd0e5083b0c5/href</a></iframe><p>That’s it, we’ve written all the necessary code for scheduling a notification, so it’s time to build the app and see what we’ve done.</p><p>Don’t forget to add the current scene in ‘Build Settings’ and we can run the app. You can change current date in your phone and fast-forward it to 3 days in the future for the testing purposes.</p><p>If you want to learn more about how mobile notifications can be implemented and check all different options that mobile notifications can provide, check the link below:</p><ul><li><a href="https://docs.unity3d.com/Packages/com.unity.mobile.notifications@1.3/manual/index.html">https://docs.unity3d.com/Packages/com.unity.mobile.notifications@1.3/manual/index.html</a></li></ul><p>Also, you can setup mobile notifications on iOS platform by following configuration steps from the link from above.</p><p>Source code of sample app:</p><ul><li><a href="https://github.com/zsasko/android-notifications-in-unity-sample">https://github.com/zsasko/android-notifications-in-unity-sample</a></li></ul><p>[1]: “How to Block Notifications and Calls While Playing Games on Android Phones”, Itigic, <a href="https://itigic.com/block-notifications-calls-while-playing-games-android/">https://itigic.com/block-notifications-calls-while-playing-games-android/</a>.<br>Accessed 1 Feb. 2021.</p><p>[2]: “Notifications Overview”, Google Developers, <a href="https://developer.android.com/guide/topics/ui/notifiers/notifications">https://developer.android.com/guide/topics/ui/notifiers/notifications</a>. Accessed 31 Jan. 2021.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=15642d316c9e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/implementing-android-notifications-in-unity-game-15642d316c9e">Implementing Android Notifications In Unity Game</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Detecting and rejecting incoming phone calls on Android]]></title>
            <link>https://medium.com/swlh/detecting-and-rejecting-incoming-phone-calls-on-android-9e0cff04ef20?source=rss-8e90b4376a8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e0cff04ef20</guid>
            <category><![CDATA[phone-call]]></category>
            <category><![CDATA[reject-call]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[call]]></category>
            <category><![CDATA[incoming-call]]></category>
            <dc:creator><![CDATA[Zoran Šaško]]></dc:creator>
            <pubDate>Tue, 17 Nov 2020 20:26:42 GMT</pubDate>
            <atom:updated>2020-11-17T20:56:31.734Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*FMw7ldQyDZOj7TE6Fx-V5Q.jpeg" /></figure><p>In this article we are going to explore how we can detect, intercept and reject incoming phone calls on different Android versions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*PcSSxnA2NpDSv8hrJBeFlw.jpeg" /></figure><p>At the bottom of this article you’ll find sample code, so you can check it in case if you have some problems with following the steps described in this article.</p><p>So, let’s start by adding the appropriate permissions in Manifest file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7ddd71cb0a557bf046826e7843aad9b/href">https://medium.com/media/c7ddd71cb0a557bf046826e7843aad9b/href</a></iframe><p>The class that will be responsible for intercepting and then answering on the phone call request is: ‘<a href="https://developer.android.com/reference/android/telecom/CallScreeningService">CallScreeningService</a>’, from ‘android.telecom’ package.</p><p>It’s a android service that allows us to make a default dialer app (which we won’t create in this article since it isn’t necessary for phone call intercepting) and it also gives us a possibility to allow or disallow incoming calls before they are displayed to the user. So, we need to extend this service in a new class (called ‘MyCallScreeningService’) in order to get call details via ‘onScreenCall’ callback method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5446b6079aad1b9401bc48cab6a21fca/href">https://medium.com/media/5446b6079aad1b9401bc48cab6a21fca/href</a></iframe><p>In ‘MyCallScreeningService’ we can see that we are overriding ‘onScreenCall’ method which contains informations about incoming phone call. Via ‘getPhoneNumber’ method we are getting formatted incoming phone number. Method ‘handlePhoneCall’ handles the incoming phone call. In this method we are checking if incoming phone call number is equal to the phone number that’s forbidden and in this case, we are rejecting the call, by applying the following properties to ‘CallResponse.Builder’:</p><pre>setRejectCall(true)<br>setDisallowCall(true)<br>setSkipCallLog(false)</pre><p>With this properties and with original call details object, we are invoking ‘respondToCall’ method, which is responsible for all the hard work of handling incoming call. Method ‘displayToast’ is displaying simple Toast message, from ‘NotificationManager’ class. If you are planning to use some DI library, like Hilt, you can inject this class into ‘MyCallScreeningService’.</p><p>Custom EventBus class is used for sending events (i.e. ‘MessageEvent’) to main activity, so the events can be displayed in a main activity log:</p><pre>class MessageEvent(val message: String) {}</pre><p>In order to use EventBus library, we need to import it in app ‘build.gradle’ file:</p><pre>implementation &#39;org.greenrobot:eventbus:3.2.0&#39;</pre><p>and for logging we are going to use Timber library, so we need also to add the following dependency:</p><pre>implementation &#39;com.jakewharton.timber:timber:4.7.1&#39;</pre><p>We are using two extension methods ‘removeTelPrefix’ and ‘parseCountryCode’ in order to format incoming phone call string into some nicer format:</p><pre>fun String.removeTelPrefix() = this.<em>replace</em>(<em>TEL_PREFIX</em>, &quot;&quot;)<em><br></em>fun String.parseCountryCode(): String = Uri.decode(this)</pre><p>After we have created our custom ‘CallScreeningService’ implementation, we need to register this service in manifest:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67b6e59798db4338f80069475f14b34e/href">https://medium.com/media/67b6e59798db4338f80069475f14b34e/href</a></iframe><p>It’s important to put appropriate permission (‘android.permission.BIND_SCREENING_SERVICE’) to the service and appropriate intent-filter, so our call screening service will work as expected.</p><p>In manifest file, under the main activity section, we need to add two intent filters:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/454a242645da4fb9da6cb43d7dc8c58c/href">https://medium.com/media/454a242645da4fb9da6cb43d7dc8c58c/href</a></iframe><p>In both intent filter we are specifying that main activity will handle ‘android.intent.action.DIAL’ action. The action that is invoked when incoming call is placed.</p><p>In order to display Toast messages, we are going to build a ‘NotificationManagerImpl’ class that provides a method for displaying Toast notification:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/048ae5e9f29bc92c69786904cae63654/href">https://medium.com/media/048ae5e9f29bc92c69786904cae63654/href</a></iframe><p>Very nice, so far we have created the most important, base setup steps for intercepting phone call functionality.</p><p>We’ll resume on creating main activity functionality. In main activity we need to implement the following functionalities:</p><ul><li>display manifest permissions alert dialog</li><li>invoking dialog where user must specify our app as default dialer app, but only on versions that are equal or above Android Q</li><li>displaying a list of messages (intercepted phone calls)</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/793932f20b5c066d1938752be52d776d/href">https://medium.com/media/793932f20b5c066d1938752be52d776d/href</a></iframe><p>Don’t worry about a lot new classes that are used in main activity. In next paragraph, we are going to explain for what are they used.</p><p>The layout for main activity is very simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf4522cd8ac2e1028a1327564b4f014b/href">https://medium.com/media/cf4522cd8ac2e1028a1327564b4f014b/href</a></iframe><p>Dimension values used for main layout:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f4be4e8060cc8fe415000b7de8a66a7/href">https://medium.com/media/0f4be4e8060cc8fe415000b7de8a66a7/href</a></iframe><p>String values used in main layout and other classes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b38bf1a9d47048298c52ffe738a4a875/href">https://medium.com/media/b38bf1a9d47048298c52ffe738a4a875/href</a></iframe><p>At the top of ‘build.gradle’, in ‘plugins’ section add:</p><pre>id &#39;kotlin-android-extensions&#39;</pre><p>so we can use Kotlin extensions.</p><p>A class called ‘ManifestPermissionRequesterImpl’ is a class that holds all the required functionalities for requesting manifest permissions. We could put the functionality for invoking manifest permissions in main activity, without using this class, but it’s used because it makes code in main activity more cleaner.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/28f87564b8d1d49e69b3c148b9a4283b/href">https://medium.com/media/28f87564b8d1d49e69b3c148b9a4283b/href</a></iframe><p>In ‘ManifestPermissionRequesterImpl’, we need to specify WeakReference variable to the activity from which we will invoke requesting manifest permissions. For requesting manifest permissions we’ll be using ‘SimplePermissions’ library, so we’ll have to add appropriate gradle dependency:</p><pre>implementation &#39;pub.devrel:easypermissions:3.0.0&#39;</pre><p>and implement ‘EasyPermissions.PermissionCallbacks’ callbacks. In each callback method we are sending appropriate SingleLiveData event to main activity, so main activity can handle next actions. If ‘READ_PHONE_STATE’ permission is granted, ‘PhoneManifestPermissionsEnabled’ event is sent to the main activity. We can see that ‘listenForUiEvents’ method handles receiving different messages sent via uiEvent LiveData variable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39317e1b4ae8e6cb6723a7f5955fbcce/href">https://medium.com/media/39317e1b4ae8e6cb6723a7f5955fbcce/href</a></iframe><p>If user has accepted ‘READ_PHONE_STATE’ permission dialog, we are invoking ‘invokeCapabilitiesRequest’ method from ‘CapabilitiesRequestorImpl’ class that displays a dialog where user must select current app as default dialer app. This functionality is mandatory only on android versions equal or bigger than Android Q.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e04c1a50a76cd2338f6b82ab499c4a54/href">https://medium.com/media/e04c1a50a76cd2338f6b82ab499c4a54/href</a></iframe><p>In ‘CapabilitiesRequestorImpl’ we must specify variable that will contain weak reference to activity that’s invoking the dialer capability. Method ‘invokeCapabilitiesRequest’ starts the functionality of checking if phone dialer functionality really needs to be enabled or not.</p><p>Method ‘requestDialerPermission’ displays a dialer selection dialog by invoking activity extension method ‘startCallScreeningPermissionScreen<em>’ </em>on Android Q and method ‘startSelectDialerScreen’ invokes displaying dialer selection popup on android versions lower than Android Q<em>. </em>Extension method ‘<em>hasDialerCapability’</em> is responsible for checking if dialer capability is needed in order to intercept incoming phone calls:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/405f89c17d8ab76bb73148b8f8b10bb8/href">https://medium.com/media/405f89c17d8ab76bb73148b8f8b10bb8/href</a></iframe><p>If our app is set as default dialer app, event ‘PhoneCapabilityEnabled’ will be send to main activity. Don’t worry if we didn’t specified dialer UI layout, it’s not mandatory to implement this functionality if we only want to intercept phone calls. If user didn’t set current app as dialer app, method ‘displayCallScreeningPermissionDialog’ will be invoked showing message that you need to set our app as default android dialer app.</p><p>Now, we are going to implement ‘BaseActivity’, which is the abstract class that our main activity extends.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af07fd8490df29a425310a2773e71591/href">https://medium.com/media/af07fd8490df29a425310a2773e71591/href</a></iframe><p>It contains only one variable ‘uiEvent’ which is a ‘SingleLiveEvent’, a basically LiveData object that can be consumed only once.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac79e99d231e958045df97c6e95f4a0a/href">https://medium.com/media/ac79e99d231e958045df97c6e95f4a0a/href</a></iframe><p>In ‘UiEvent’ class we have defined all the events that can be sent to LiveData object of ‘BaseActivity’ and our main activity is listening for events received in this LiveData object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54bc9401e7fa76d20d3c8ff5ed33b350/href">https://medium.com/media/54bc9401e7fa76d20d3c8ff5ed33b350/href</a></iframe><p>The last step of our application is to specify some constants:</p><pre>const val <em>TEL_PREFIX </em>= &quot;tel:&quot;<br>const val <em>FORBIDDEN_PHONE_CALL_NUMBER </em>= &quot;6505551212&quot;</pre><p>Now we can try to make an incoming call from ‘6505551212’ and we should see that this phone call is rejected. All other phone calls should be allowed.</p><p>In this article have learned about ‘CallScreeningService’ class, that allows us to intercept and reject incoming phone calls. We have learned how it works and what should we specify in order to listen for incoming phone calls. :)</p><p>Source code of sample app built in this article:</p><ul><li><a href="https://github.com/zsasko/phone-call-intercepting-sample">https://github.com/zsasko/phone-call-intercepting-sample</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e0cff04ef20" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/detecting-and-rejecting-incoming-phone-calls-on-android-9e0cff04ef20">Detecting and rejecting incoming phone calls on Android</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Notes App with React, React Router, Redux, and Redux Form]]></title>
            <link>https://javascript.plainenglish.io/using-react-react-router-redux-redux-form-in-building-simple-notes-app-fd3114f5131a?source=rss-8e90b4376a8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd3114f5131a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Zoran Šaško]]></dc:creator>
            <pubDate>Mon, 12 Oct 2020 07:59:25 GMT</pubDate>
            <atom:updated>2020-10-13T05:53:29.320Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*rdkungEkCSMAau5a2jH1lQ.png" /></figure><p>Before we start with the coding, let us remind ourselves what is React. React is a JavaScript library for building user interfaces. It allows us to create reactive interfaces very easily because it can listen for state change and when state change occurs, it will update UI layout. It’s component based and it uses XML-like syntax called JSX.</p><p>In this article we are going to build simple Notes App that will use NestJS backend. In order to start backend app please download it’s source code and check it’s <em>README.md</em>:</p><ul><li><a href="https://github.com/zsasko/nestjs-mysql-typeorm-sample">https://github.com/zsasko/nestjs-mysql-typeorm-sample</a><br>(Don’t worry, you have to do only few steps in order to make it work 😃)</li></ul><p>At the end of this article you can find source code of React application that we are going to build in this article.</p><h4>Let’s start!</h4><p>Firstly, we are going to initialize React project by invoking the following <em>npm</em> command:</p><pre>npx create-react-app react_redux_form_sample</pre><p>And from ‘src’ folder remove all the files. We’ll put our classes there, so we don’t need pregenerated ones.</p><p>In generated <em>index.html </em>(located inside of ‘public’ folder’) please add link to <em>bootstrap.css</em> file inside of ‘head’ tag:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dc86fac9c11265fb62d455ee4982ebf/href">https://medium.com/media/1dc86fac9c11265fb62d455ee4982ebf/href</a></iframe><p>And at the very bottom of ‘body’ tag put the following JavaScript libraries that will allow us to have bootstrap style of application:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/89c679069c09bab1a8325204990205d9/href">https://medium.com/media/89c679069c09bab1a8325204990205d9/href</a></iframe><p>We can now add all required libraries in ‘dependencies’ section of ‘package.json’:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62b010c8146e56dd3493295b8c67c463/href">https://medium.com/media/62b010c8146e56dd3493295b8c67c463/href</a></iframe><p>And install them by invoking the following command:</p><pre>npm install</pre><p>Our app classes (inside of ‘src’ folder) will be the structured by using the following folders:</p><ul><li><strong>actions</strong>: Contains all actions that user can make</li><li><strong>apis</strong>: A place for storing different API configurations (in our case only one api config)</li><li><strong>components</strong>: Containing all the components that will be used in building of our app, like Header, LoadingSpinner etc.</li><li><strong>reducers</strong>: Containing all reducers</li></ul><p>Let us start by creating ‘history.js’ file that will return method for handling of React browser history:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67fb4aa0ef6116178fe941303493adef/href">https://medium.com/media/67fb4aa0ef6116178fe941303493adef/href</a></iframe><p>This method will be used in different places, in different classes of the app and it will be used for routing to different routes.</p><p>Creating actions that user can make we can start by specifying which action types user can start. So let’s create ‘actions/types.js’ file with the following action types:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/161e48cff7f9fcaae72947b74158d696/href">https://medium.com/media/161e48cff7f9fcaae72947b74158d696/href</a></iframe><p>After we have specified action types, we can resume on writing the different actions methods (in ‘actions/index.js’ file):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d88ce7388ba6ae60352929759d7d6a1a/href">https://medium.com/media/d88ce7388ba6ae60352929759d7d6a1a/href</a></iframe><p>In every action method we are doing some async request via ‘notes’ api. Notes API class is basically preconfigured <em>axios </em>object with base url pointing to our backend. After we made some request, like POST request to our backend, we are dispathing the result to the reducer by invoking ‘dispatch’ command with type of action and with response data as ‘payload’. In some methods like ‘createNote’ after dispatching the response from the backend, we are using session history object in order to redirect user to main screen (route ‘/’).</p><p>In the ‘apis/notes.js’ file we are exporting note api, which is basically <em>axios</em> object with preconfigured base url:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1cc06ce5085a76165e074929cdfc716/href">https://medium.com/media/e1cc06ce5085a76165e074929cdfc716/href</a></iframe><p>The reason why we want to create separate note api file is because of simplicity of updating base url if it’s need to be changed.</p><p>The next step after creating actions is to create reducers that are reducing response fetched via actions into a state, that can be read from our components.</p><p>Let us start by writing the code of ‘reducers/noteReducer.js’:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94fdafa35765d9e80e2afe253b674f00/href">https://medium.com/media/94fdafa35765d9e80e2afe253b674f00/href</a></iframe><p>In our reducer we are handling different types of actions and their payload. Data is stored in state in ‘key: value’ format, where the ‘key’ is the ID of note and ‘value’ is note object itself. We are using <em>lodash </em>library to make mappings (in ‘FETCH_NOTES’) and removal (in ‘DELETE_NOTE’) easier.</p><p>After we’ve created notes reducer, let us create combine our notes reducer with form reducer (‘reducer/index.js’):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35bc8603394568c28a617176f3edec92/href">https://medium.com/media/35bc8603394568c28a617176f3edec92/href</a></iframe><p>Redux form is used to manage form state in Redux. Redux Form Reducer is used for updating the Redux store based on the changes that are coming from the application. Later in the article we are going to use ‘reduxForm’ and ‘Field’ components that will allows us the mentioned functionalities work seamlesly.</p><p>So far, we have created actions, reducers, api and now we can resume on creating components. Firstly we are going to create ‘index.js’ where we are going to create Redux store and we are going to render our main App component into the DOM.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/063be500118876639b17cd0524e7ecbf/href">https://medium.com/media/063be500118876639b17cd0524e7ecbf/href</a></iframe><p>Method ‘createStore’ creates a Redux store that holds the complete state tree of the app. It takes reducers that are returning the next state tree and it also takes Redux Thunk middleware. Redux Thunk middleware allows us to write action creators that return a function instead of an action.</p><p>The ‘Provider’ makes Redux store available to all nested components because it’s rendered on the top level of the app.</p><p>In the listing above you can see that we are also using Redux DevTools Extension which will allow us to see the Redux state. We can also see the actions with payload that are executed when user for example saves or updates a note.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/797/1*aiPF811jkarjj18FtQo_0g.png" /></figure><p>First component that we are going to create is <em>App.js</em> (in folder ‘components’):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2bd0ed59df50f6177cac741b3c45453/href">https://medium.com/media/f2bd0ed59df50f6177cac741b3c45453/href</a></iframe><p>Don’t be afraid of a lot of import statements, on the top of this class. We are going to create all those components later in this article.</p><p>It also contains React Router, the component that will allow us to navigate to different ‘pages’, i.e. it will be responsible for rendering different components (like ‘NoteCreate’ component, when user navigates to the ‘/note/new’ url).</p><p>As we can see in <em>App </em>component, we are rendering ‘Header’ component and afterwards different components based on current url. The ‘Switch’ is used for rendering the first ‘Route’ that matches it’s location attribute. Some ‘Route’ components have ‘exact’ property and this is used in order not to invoke similar ‘Route’ with very similar location attribute.</p><p>Before we start writing our own components, let us remind ourselves which types of components exist in React apps:</p><ul><li><strong>Functional</strong> — it’s just a function that accepts props and returns React element</li><li><strong>Class</strong> — a class that requires you to extend from React.Component and to create a ‘render’ method in order to return React element</li></ul><p>The main difference between functional and class components is that you can’t use state and lifecycle hooks in functional components.</p><p>The second component that we are going to create is ‘Header’ component, which is functional component (since it’s not class and doesn’t extends from ‘React.Component’).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/35357c24f0987eb1fa050e8ab50baa2d/href">https://medium.com/media/35357c24f0987eb1fa050e8ab50baa2d/href</a></iframe><p>The ‘Header’ component renders simple header for our application.</p><p>In our app, we are going use simple progress indicator, so we are going to create appropriate functional component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1f5446ceb96911d381356a29b1fff23/href">https://medium.com/media/f1f5446ceb96911d381356a29b1fff23/href</a></iframe><p>First page that user will see when the app is loaded will display a list of notes. Component that will be responsible for rendering a list of notes is ‘notes/NoteLists.js’ component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dac77e712da9b9b5eb7d9e9a50894af1/href">https://medium.com/media/dac77e712da9b9b5eb7d9e9a50894af1/href</a></iframe><p>NotesList is a class component and it loads data via ‘this.props.fetchNotes’ method called inside of ‘componentDidMount’ lifecycle method. The lifecyle method ‘componentDidMount’ runs after the component output has been rendered to the DOM.</p><p>Method ‘render’ is class-based component method for rendering a content. Inside of this method we are invoking appropriate methods for displaying a list of notes in case where there are notes available (method ‘renderList’) or appropriate message, in case when notes list is empty (method ‘renderEmptyListMessage’).</p><p>Method ‘renderList’ displays a list of messages, by going through all notes and by rendering appropriate list content with note data. ‘Link’ component is used for creating a link to appropriate endpoint by using React Router.</p><p>Method ‘renderEmptyListMessage’ displays a message in a case when there is no notes available.</p><p>On the bottom of component, we can find ‘connect’ wrapper function that is responsible for connecting a React component to a Redux store. By ‘mapStoreToProps’ we are subscribed to Redux store updates. That means any time store is updated, ‘mapStoreToProps’ will be called. The result of ‘mapStateToProps’, a plain object, will be merged to component props. The second argument of ‘connect’ function are action creators (in our case ‘fetchNotes’ action) that can be invoked via props object of our component.</p><p>Very nice, another component that we are going to create is ‘notes/NoteShow.js’:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ffb77f84a4cf9a1897f9c32191e4c557/href">https://medium.com/media/ffb77f84a4cf9a1897f9c32191e4c557/href</a></iframe><p>In this component we are invoking ‘fetchNote’ method with appropriate note ID, taken from url, when component is mounted. In method ‘mapStateToProps’ we are taking note from Redux store, that we have fetched via note api. In ‘connect’ wraper function we are loading two action creators: ‘fetchNote’ and ‘deleteNote’ that will be responsible for invoking a note fetch or delete functionality.</p><p>Because the form for editing and creating new note will contain the same field, we are going to create generic component that will be used in both component for editing and creating note and it will notify parent component when it’s submitted:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb2a89520d4e9e01e7a1234401bc52a9/href">https://medium.com/media/bb2a89520d4e9e01e7a1234401bc52a9/href</a></iframe><p>In ‘render’ method we are rendering a form with appropriate elements inside of it. Here we can see ‘Field’ component that is Redux Form component that connects the input component with the Redux Form logic. Method ‘renderInput’ is a method that returns rendered input fields. It also contains prop with meta information that will be used for validation.</p><p>Method ‘renderError’ checks if error message should be displayed, based on if user has accessed the field and didn’t specified any value.</p><p>In form, you can see that ‘onSubmit’ has assigned ‘handleSubmit’ handler with ‘submit’ handler inside of it. You can think of the redux-form ‘handleSubmit’ as a middle layer for your our submit handler that will be accessible in our parent component.</p><p>Method ‘onSubmit’ sends the form values to the parent component (that we are going to create next).</p><p>Validate constant is used by Redux Form to check weather some field has failed validation, and if returns not empty list, it means that form has failed a validation.</p><p>On the bottom of file, we can see wrapper function ‘reduxForm’ that allows us to use redux form fields and validation to work.</p><p>Finally we are now going to create a component responsible for creating new note:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c9fca5d57e99ce1deadb48be2a3f0e7/href">https://medium.com/media/6c9fca5d57e99ce1deadb48be2a3f0e7/href</a></iframe><p>Because we are using ‘NoteForm’ component, we are assigning its prop ‘onSubmit’ to the same named function inside of ‘NoteForm’ to handle invoking of action creator ‘createNote’ with form values.</p><p>On the bottom we can see ‘connect’ wrapper function without ‘mapStateToProps’ assigned, but with assigned ‘createNote’, since we are only to use this action creator in context of this component. So that’s all the code for component that’s responsible for creating a new note. Neat! 😃</p><p>Edit note component will be slightly bigger than component for creating a new note, since it need to load existing note data form DB:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5c24c359f0fe6acb50d3f47fb7966d1/href">https://medium.com/media/d5c24c359f0fe6acb50d3f47fb7966d1/href</a></iframe><p>In ‘render’ method we are checking if note data is loaded and if it isn’t, we are displaying appropriate loading spinner (‘LoadingSpinner’ component). If note data is loaded from state, we are assigning it’s data to ‘NoteForm’ component via ‘initialValues’ prop. We are using <em>lodash</em> library method called ‘pick’ in order to take only few attributes from note object that are used in form (for example, a note object will also contain a ‘ID’ property, but it’s not used in ‘NoteForm’ so we are not picking it). On the prop ‘onSubmit’ we are assigning method with the same name which invokes ‘editNote’ action with appropriate note data.</p><p>In ‘componentDidMount’ we are fetching a note based on note ID.</p><p>Function ‘mapStateToProps’ is used for taking an note from store, afterwards the note fetching request was finished.</p><p>On the bottom of file we have a ‘connect’ wrapper method that besides of mapping state to props contains a mapper for action creators like ‘fetchNote’ and ‘editNote’.</p><p>Very nice. Congratulations, you have finished the app and you can start it by invoking the following command:</p><pre>npm start</pre><p><em>Btw, make sure that backend server is also running. 😃</em></p><p>Source code of sample app built in this article:</p><ul><li><a href="https://github.com/zsasko/react-redux-form-sample">https://github.com/zsasko/react-redux-form-sample</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd3114f5131a" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/using-react-react-router-redux-redux-form-in-building-simple-notes-app-fd3114f5131a">Build a Notes App with React, React Router, Redux, and Redux Form</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[Build a Notes App with NestJS, MySQL, TypeORM]]></title>
            <link>https://javascript.plainenglish.io/using-nestjs-mysql-typeorm-in-building-simple-notes-app-5cdbee9712e0?source=rss-8e90b4376a8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cdbee9712e0</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[nestjs]]></category>
            <dc:creator><![CDATA[Zoran Šaško]]></dc:creator>
            <pubDate>Mon, 12 Oct 2020 07:58:37 GMT</pubDate>
            <atom:updated>2021-03-28T11:05:23.923Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*zeOv4blDpgcoqTLUvfmbXQ.png" /></figure><p>Nest (NestJS) is a framework for building efficient, scalable Node.js server-side applications.</p><p>Nest provides an out-of-the-box application architecture which allows developers and teams to create highly testable, scalable, loosely coupled and easily maintainable applications.</p><p>The main reasons why you should consider to use NestJS as framework in your projects is because it’s very powerful but super friendly to use, documentation is very easy to understand, provides very easy development and testing, supports Typescript and GraphQL etc.</p><p>In our project we are going to build simple backend application for storing and retrieving notes.</p><p>At the bottom of this article you’ll find sample code, so you can check it in case if you have some problems with following the steps described in this article.</p><p>In order to create new Nest application, we’ll install Nest CLI and execute command for creating new Nest application:</p><pre>npm i -g @nestjs/cli<br>nest new nestjs-mysql-typeorm-sample</pre><p>And choose <em>npm </em>as package manager.</p><p>In the app, we are going to use MySQL database and we are going to use TypeORM library for storing and retrieving data from MySQL so we need to invoke the following command in order to install these libraries:</p><pre>npm install --save @nestjs/typeorm typeorm mysql</pre><p>In order to setup TypeORM connection to MySQL, we need to create <em>ormconfig.json</em> with appropriate MySQL configuration data (please make sure that you specify the right username, password and database name):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c38916e23f4dc1fa6d2f20e51a6a82c4/href">https://medium.com/media/c38916e23f4dc1fa6d2f20e51a6a82c4/href</a></iframe><p>TypeORM configuration data will be loaded from <em>ormconfig.json</em> file, so in in main application module file (<em>app.module.ts</em> file) we have to import ‘TypeOrmModule’ by invoking ‘forRoot’ without any options:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0850b641a5fee49031d0c37ec9580821/href">https://medium.com/media/0850b641a5fee49031d0c37ec9580821/href</a></iframe><p>As we can see, NestJS app structure is made of three core files:</p><ul><li><strong>app.controller.ts </strong>- basic controller with single route</li><li><strong>app.module.ts</strong> - the root module of application</li><li><strong>main.ts </strong>- the entry file of application which uses the core function <em>NodeFactory </em>to create Nest application instance</li></ul><p>Because our application will provide only one feature and that is creating, updating, retrieving a list of notes, we are going to create appropriate notes module, service, provider and controller (all of those in separate notes folder). By doing that, we are clearly separating notes functionality from other functionalities that application might have and we are making the code cleaner and more readable.</p><p>We’ll put some validation of model fields, so we’ll need to invoke the following <em>npm </em>command and install ‘class-validator’ library that will validate our model object, when user will try to insert new or edit an existing note object in database:</p><pre>npm install class-validator</pre><p>We’ll also install ‘class-transformer’ package that will allow us to transform plain object to an instance of class and vice versa:</p><pre>npm install class-transformer</pre><p>Before we are going to create controllers, services and other classes, let’s us create our main data class, <em>Note </em>entity object (in ‘notes/Note.entity.ts’ file):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca7f403a9991ab1372b4c9eead79bb3c/href">https://medium.com/media/ca7f403a9991ab1372b4c9eead79bb3c/href</a></iframe><p>As we can see, <em>Note </em>entity class contains different decorators. TypeORM related decorators are: ‘@Entity’, ‘@PrimaryGeneratedColumn’ and ‘@Column’. Class validator related decorators are all other decorators related to data type and value validation, for example ‘@MinLength’ or ‘@IsString’.</p><p>The next class that we are going to create will be notes service (‘notes/notes.service.ts’ file) which will be responsible for providing methods that are retrieving or storing data in MySQL database, to our notes controller:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6d87fcc75db823b12f04371f3c328f2/href">https://medium.com/media/e6d87fcc75db823b12f04371f3c328f2/href</a></iframe><p>As we can see in notes service, there is a lot of methods that are responsible for storing or retrieving notes from MySQL database, all done by using repository data pattern provided by TypeORM.</p><p>The next class that we are going to create will be notes controller and his main responsibility is to handle incoming requests and return response to the client:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/369d1c2e34b4cb05a9669cc3ce63e91e/href">https://medium.com/media/369d1c2e34b4cb05a9669cc3ce63e91e/href</a></iframe><p>In constructor we are injecting notes service, that will handle MySQL database operations, via notes repository. Every method in service has it’s own appropriate decorator (like ‘@GET’) and it’s assigned to appropriate method which this decoration handles. Each method with decorator is handling appropriate HTTP method call (like ‘@Get’ decorator handles ‘HTTP GET’ call).</p><p>By now we have created notes controller that will handle incoming requests and it will return response and note service that will be used for data storage and retrieval.</p><p>The last part is to create notes module that will make keep notes-related dependencies organized under the same file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1324bbbf7b4213a9d9089398d3982135/href">https://medium.com/media/1324bbbf7b4213a9d9089398d3982135/href</a></iframe><p>and we need to import notes module in app module:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/764e8107212b9f498f9f5420b2f1b489/href">https://medium.com/media/764e8107212b9f498f9f5420b2f1b489/href</a></iframe><p>In the main entry file of our application (file ‘main.ts’) we need to set that app uses ‘ValidationPipe’ which will ensure that all endpoints are protected from receiving the incorrect data. Also we’ll enable ‘CORS’ so we can access our backend app endpoints from frontend applications.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5abe7fbdcb2e5db2aaf10cc12d6eec0/href">https://medium.com/media/c5abe7fbdcb2e5db2aaf10cc12d6eec0/href</a></iframe><p>Make sure that port is set to ‘3001’, because our frontend application that we are going to create in <a href="https://medium.com/@zoransasko/using-react-react-router-redux-redux-form-in-building-simple-notes-app-fd3114f5131a">this</a> article will point to port ‘3000’.</p><p>So, now we have prepared everything that is required for our backend app to work and we can start it by invoking the following command:</p><pre>npm start</pre><p>We can try to insert new note via Postman:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/659/1*t9NuC1pf1AeiXBPQTFxlXQ.png" /></figure><p>and we can also check if validation works by providing the invalid ‘description’ data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*JpwcWMmS1QqsGDKG-6WHQA.png" /></figure><p>Congratulations, we have successfully created NestJS backend app that stores and fetches data from MySQL database.</p><p>In the next article we are going to explore how we can display notes data in React frontend app:</p><p><a href="https://medium.com/@zoransasko/using-react-react-router-redux-redux-form-in-building-simple-notes-app-fd3114f5131a">Using React, React Router, Redux, Redux Form in building simple Notes App</a></p><p>Source code of sample app built in this article: <a href="https://github.com/zsasko/nestjs-mysql-typeorm-sample">https://github.com/zsasko/nestjs-mysql-typeorm-sample</a></p><p>Enjoyed this article? If so, get more similar content by <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>subscribing to Decoded, our YouTube channel</strong></a><strong>!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cdbee9712e0" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/using-nestjs-mysql-typeorm-in-building-simple-notes-app-5cdbee9712e0">Build a Notes App with NestJS, MySQL, TypeORM</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[Sending Push Notifications from NodeJS backend App to Flutter Android App]]></title>
            <link>https://medium.com/weekly-webtips/sending-push-notifications-from-nodejs-backend-app-to-flutter-android-app-8a261c3c2c61?source=rss-8e90b4376a8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a261c3c2c61</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[push]]></category>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Zoran Šaško]]></dc:creator>
            <pubDate>Thu, 27 Aug 2020 19:04:05 GMT</pubDate>
            <atom:updated>2020-08-28T20:26:34.238Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*mU4A4Vwn1Skb0PefskUfnQ.jpeg" /></figure><p>Notifications about new articles, price changes, product offers are expanding interactivity scope of mobile applications.</p><blockquote><em>A notification is a message that pops up on the user’s device. Notifications can be triggered locally by an open application, or they can be “pushed” from the server to the user even when the app is not running. They allow your users to opt-in to timely updates and allow you to effectively re-engage users with customized content.¹</em></blockquote><p>Push notifications are great marketing tools because they help to increase user-to-app interactivity level.</p><p>In this article we are going to explore how we can send push notifications from NodeJS backend application to Flutter Android application, using FCM messages. Device tokens will be stored in MySQL database and in the NodeJS, we are going to validate input.</p><p>At the bottom of this article, you can see sample applications and feel free to check them out.</p><h3>Creating NodeJS backend App</h3><p>In this section, we are going to build NodeJS backend application that will be responsible for storing push device tokens and sending push notifications.</p><p>Backend app will have the following dependencies in ‘package.json’:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25535f55dd52364cce3fcf4cf062ba62/href">https://medium.com/media/25535f55dd52364cce3fcf4cf062ba62/href</a></iframe><p>and by executing:</p><pre>npm install</pre><p>we are going to install these dependencies.</p><p>Next point is to create ‘App.js’, which will be the starting point of our NodeJS app:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1396db8579e1e9c7b9803c116f948645/href">https://medium.com/media/1396db8579e1e9c7b9803c116f948645/href</a></iframe><p>In the ‘App.js’ we can see that we are going to create few routes for handling requests for displaying homepage, sending messages, and storing device token.</p><p>It’s also very important to set up ‘.env’ file with appropriate configuration values:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/359accedd2ce3e7345c2e1f271d5f670/href">https://medium.com/media/359accedd2ce3e7345c2e1f271d5f670/href</a></iframe><p>In order to send FCM push notifications from our NodeJS app, we need to make new Firebase Project and generate ‘serverKey’:</p><p>1. Create a new Firebase Project (via <a href="https://console.firebase.google.com/">https://console.firebase.google.com</a>/).</p><p>2. Click on ‘Project Overview &gt; Project Settings’ page.</p><p>3. In the ‘Settings’ page, click on ‘Cloud Messaging’ tab. Copy ‘Server key’ value and paste it as a value of ‘FCM_SERVER_KEY’ key, inside of ‘.env’ file.</p><p>The next step in creating our NodeJS backend app is to create data models.</p><pre>npx sequelize init</pre><p>By executing the command from above, we have initialized folder where model files will be stored and initial database configuration. The next step is to adjust the database configuration.</p><p>The first step in the configuration of the way how data will be stored and retrieved, using ‘sequelize’ library is to specify ‘.sequelizerc’ file with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f7ae70f97ab11b26bc4f31b3696e8d9/href">https://medium.com/media/4f7ae70f97ab11b26bc4f31b3696e8d9/href</a></iframe><p>The above lines ensures that MySQL configuration is fetched from ‘config/config.js’ file with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/27920744571a2ac1a2a7c24a57bceb85/href">https://medium.com/media/27920744571a2ac1a2a7c24a57bceb85/href</a></iframe><p>So, in ‘config.js’ we have specified that we are going to use MySQL database with connection data loaded from ‘.env’ file.</p><p>The last step of database configuration is to replace the following line from ‘models/index.js’:</p><pre>const config = require(__dirname + &quot;/../config/<strong>config.json</strong>&quot;)[env];</pre><p>to:</p><pre>const config = require(__dirname + &quot;/../config/<strong>config</strong>&quot;)[env];</pre><p>By now we have successfully implemented all the configuration steps from above and we are confident to invoke a command that will generate data model ‘PushDevice’ with appropriate attributes.</p><pre>npx sequelize-cli model:generate --name PushDevice --attributes uuid:string,token:String,platform:enum:&#39;{android,ios}&#39;</pre><p>in ‘models/pushdevice.js’ and appropriate migration in ‘migrations’ folder.</p><p>We need to migrate our ‘PushDevice’ into MySQL database, by execute the following command:</p><pre>npx sequelize db:migrate</pre><p>Very nice, so far we have made models and we have prepared everything for storing ‘PushDevice’ data in MySQL database.</p><p>Next step is to create our main layout (in ‘views/index.ejs’):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e74c9e36d5900ed8012e12eb8186d0bf/href">https://medium.com/media/e74c9e36d5900ed8012e12eb8186d0bf/href</a></iframe><p>In order to send a message, we are going to use JQuery POST method, which will be created in a separate JS file (stored in ‘public/js/index.js’ file):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2c8dfd8741a6bdf595df8f19ee1d135/href">https://medium.com/media/e2c8dfd8741a6bdf595df8f19ee1d135/href</a></iframe><p>In the script above we can see that in ‘sendMessage’ method we are creating POST request to NodeJS backend URL for handling of send push notification messages.</p><p>In the next step we are going to create ‘routes/index.js’ file with methods that will handle different route options:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5157dc27f1169438a17d068eb9f792c/href">https://medium.com/media/d5157dc27f1169438a17d068eb9f792c/href</a></iframe><p>Method ‘sendMessage’ checks if ‘message’ parameter is valid, fetches android devices token and sending ‘gcm.Message’ message via ‘gcm.Sender’ object.</p><p>In ‘sendToken’ method we are validating if all parameters are valid and created a new ‘PushDevice’ object in MySQL database.</p><p>Very nice!</p><p>We have implemented NodeJS Push notification server and we can start the NodeJS app by executing:</p><pre>nodemon App.js</pre><p>In the next step, we are going to create a Flutter Android app.</p><h3>Creating Flutter Android App</h3><p>In this step, we are going to create a Flutter Android application that will be able to receive push notifications. In order to our app to be able to receive push notification, we need to make a Firebase App setup:</p><p>1. In project level ‘build.gradle’ add the following dependencies:</p><pre>classpath &#39;com.android.tools.build:gradle:3.5.3&#39;<br>classpath &#39;com.google.gms:google-services:4.3.2&#39;</pre><p>2. In app-level ‘build.gradle’ add the following dependency to the bottom of file:</p><pre>apply plugin: &#39;com.google.gms.google-services&#39;</pre><p>3. In app-level ‘build.gradle’ make sure that ‘applicationId’ is set to the same package name that we have specified in Firebase Android setup process.</p><pre>applicationId &quot;com.zsasko.flutterpushsample&quot;</pre><p>We need to configure Firebase for Android in order to get push notifications in our Flutter Android app.</p><p>4. In Firebase console click on ‘Project Overview &gt; Project Settings’ and on the bottom of ‘General’ tab, you can find ‘Your Apps’ section. In this section click on ‘Android’ icon in order to start wizard for adding Firebase into Flutter Android project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nmXME2RtVznpb6uPfiBWQQ.png" /></figure><p>5. In the ‘Add Firebase to Android app’ dialog, put the package name that will be used in the Flutter app and proceed with wizard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/645/1*yfyBIu-POTVzMnJW5Q9d-w.png" /></figure><p>6. In the next step, click ‘Download google-services.json’ and put his file in ‘app’ folder:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/760/1*x0aesVsIyGzEd19-TsBBhw.png" /></figure><p>4. We are going to create custom ‘Application’ class with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e3024b593dce5e9ca7be950f16e007c/href">https://medium.com/media/6e3024b593dce5e9ca7be950f16e007c/href</a></iframe><p>and assign it to ‘android:name’ property of ‘application’ manifest tag:</p><pre>&lt;application<br> android:label=&quot;push_notification_flutter_sample&quot;<br> <strong>android:name=&quot;.Application&quot;</strong><br> android:icon=&quot;@mipmap/ic_launcher&quot;&gt;</pre><p>5. In manifest, inside of ‘MainActivity’ add the following intent filter:</p><pre>&lt;intent-filter&gt;<br> &lt;action android:name=&quot;FLUTTER_NOTIFICATION_CLICK&quot; /&gt;<br> &lt;category android:name=&quot;android.intent.category.DEFAULT&quot; /&gt;<br>&lt;/intent-filter&gt;</pre><p>6. In ‘dependencies’ section of app ‘build.gradle’ add the following dependencies:</p><pre>implementation &#39;com.google.firebase:firebase-messaging:20.2.4&#39;<br>implementation &#39;com.google.firebase:firebase-analytics:17.5.0&#39;</pre><p>Very nice, so far we have specified all the required initial setup required for receiving push notifications in Flutter Android apps.</p><p>Dependencies that will be used in the Flutter app are the following:</p><pre>firebase_messaging: ^7.0.0<br>http: ^0.12.2<br>intl: ^0.16.1</pre><p>and by executing the following command, we are going to install these dependencies:</p><pre>flutter pub get</pre><p>The next step is to create Flutter Android app layout and appropriate methods for subscribing and handling push notification response.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6fa6dbe13fb91a82d7f9caa479efdca8/href">https://medium.com/media/6fa6dbe13fb91a82d7f9caa479efdca8/href</a></iframe><p>Method ‘sendTokenToServer’ sends push device token to our NodeJS backend application so when the user sends a message from the backend app, it will be sent to our exact device.</p><p>Object ‘_firebaseMessaging’ is responsible for receiving push notifications.</p><p>Class ‘MessageItem’ (stored in ‘model/message_item.dart’) will be used for generating list view items:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e2ac63f604cef7196887e8730061c6eb/href">https://medium.com/media/e2ac63f604cef7196887e8730061c6eb/href</a></iframe><p>Data model for parsing notification data (file named ‘model/notification_data.dart’):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5be975dc50895486ea83363e831bcbd7/href">https://medium.com/media/5be975dc50895486ea83363e831bcbd7/href</a></iframe><p>Folder ‘test’ we can delete since we don’t need to make any Unit tests.</p><p>DEVELOPER TIP: If you want to access NodeJS backend that’s running on ‘localhost’ from your physical device, you can download an app called ‘ngrok’.</p><p>Start the app by executing the following command:</p><pre>ngrok http 5000</pre><p>which will create ‘Forwarding’ URL that we can reuse in ‘sendTokenToServer’ method and we’ll be able to use our physical device instead of emulator for receiving push messages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/698/1*kOBRQDEjxkayEUhP5ls2bA.png" /></figure><p>We can now start our Flutter Android app in an emulator/physical device and send push notification from the NodeJS app.</p><p>Congratulations!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*9ahOY7mwTbluKug00qu3Uw.jpeg" /></figure><p>You have implemented NodeJS backend app for sending push notifications and simple Flutter Android app for receiving push notifications :)</p><p>Source code of sample applications created in this article:</p><ul><li><a href="https://github.com/zsasko/nodejs-push-notification-sample">https://github.com/zsasko/nodejs-push-notification-sample</a></li><li><a href="https://github.com/zsasko/flutter-push-notification-sample">https://github.com/zsasko/flutter-push-notification-sample</a></li></ul><p>[1]: “Introduction to Push Notifications”, Google Developers, <a href="https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications">https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications</a>. Accessed 26 Aug. 2020.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a261c3c2c61" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weekly-webtips/sending-push-notifications-from-nodejs-backend-app-to-flutter-android-app-8a261c3c2c61">Sending Push Notifications from NodeJS backend App to Flutter Android App</a> was originally published in <a href="https://medium.com/weekly-webtips">Webtips</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating simple AR App in Unity3D using ARCore]]></title>
            <link>https://medium.com/swlh/creating-simple-ar-app-in-unity3d-using-arcore-4c0ef0c72c6e?source=rss-8e90b4376a8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c0ef0c72c6e</guid>
            <category><![CDATA[ar]]></category>
            <category><![CDATA[unity3d]]></category>
            <category><![CDATA[3d]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Zoran Šaško]]></dc:creator>
            <pubDate>Sun, 23 Aug 2020 12:41:10 GMT</pubDate>
            <atom:updated>2020-08-29T15:34:38.845Z</atom:updated>
            <content:encoded><![CDATA[<p>AR and VR applications are emerging more and more, providing new possibilities and new perspectives to end user. In this article we’ll explore how AR library called ARCore can be implemented using Unity3D in order to display simple chair object.</p><p>Before we dig in into coding, let us remind ourselves what is AR and VR?</p><blockquote>Augmented reality (AR) is an enhanced version of reality created by the use of technology to overlay digital information on an image of something being viewed through a device (such as a smartphone camera).¹</blockquote><blockquote>Virtual reality (VR) is an artificial environment which is experienced through sensory stimuli (such as sights and sounds) provided by a computer and in which one’s actions partially determine what happens in the environment.²</blockquote><p>The main difference between VR and AR is that VR creates whole new, detached virtual experience — for example, you can enter in virtual hotel, walk there, all while sitting in your chair using VR goggles and controller in your hand. AR adds virtual objects, for example chair in real world space and thus enhances the experience of real world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LSH6LXD28urqNJCH2xyMAQ.jpeg" /><figcaption>Augmented Reality Example App³</figcaption></figure><p>Applications that provides AR/VR experiences are mostly used in cinematic, gaming, educational, automotive, healthcare, travel &amp; tourism experiences etc.</p><p>Before we can start with implementation of our AR app, we need to check some requirements (according to the ‘ARCore Quickstart for Android’):</p><ul><li><a href="https://developers.google.com/ar/develop/unity/quickstart-android">https://developers.google.com/ar/develop/unity/quickstart-android</a></li></ul><p>At the bottom of this article you can find sample code.</p><h3>Project preparation</h3><p>In order to make our AR application, we need to make the following project preparation steps:</p><ol><li>Install ‘Unity 2017.4.34f1’ or later. Unity version used for creating this sample is ‘Unity 2019.2.12f1’. Make sure that ‘Android Build support’ is checked because we are going to runt the app on Android device.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*zK5QGwwlkO89OmU21Bv9kQ.png" /></figure><p>2. Download ‘ARCore SDK for Unity 1.18.0’ or later:<br><a href="https://github.com/google-ar/arcore-unity-sdk/releases">https://github.com/google-ar/arcore-unity-sdk/releases</a></p><p>3. After you have downloaded ‘ARCore SDK’, start Unity3D and create new project, with ‘3D’ template selected.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*0E5tMJJ11EpbzyxB8qczvQ.png" /></figure><p>4. Import ‘ARCore SDK’ (file will be named like ‘arcore-unity-sdk-1.18.0.unitypackage’) downloaded in step 2, while Unity3D is running.</p><p>5. If you are using Unity3D 2019, select ‘Window &gt; Package Manager’ and install the following packages:</p><ul><li><strong>Multiplayer HLAPI</strong></li><li><strong>XR Legacy Input Helpers</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/791/1*doprhVLw21sePQBkgdspqw.png" /></figure><p>6. In Unity3D we need to open scene named ‘ObjectManipulation’ which is located in the following folder:</p><ul><li>Assets/GoogleARCore/Examples/ObjectManipulation/Scenes/</li></ul><p>This scene will be our main scene for application, so the next step is to configure Android build settings.</p><h3>Configuring Android Build Settings</h3><p>In order to make Android builds, we need to implement some steps in order to enable that functionality:</p><ol><li>Go to ‘File &gt; Build Settings’ and open ‘Build Settings’ window</li><li>Click on ‘Switch Platform’ near ‘Android’ Platform and wait until Unity finishes compiling scripts.</li><li>Click on ‘Player Settings’ and make sure that ‘Player’ settings item is selected.</li><li>Expand ‘Other Settings’ and in ‘Graphic APIs’ delete ‘Vulkan’ graphic API.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*SB9TUvKpMOz2hbeVnyjbYQ.png" /></figure><p>5. In the same settings section (section called ‘Other Settings’), make sure that ‘Multithreaded rendering’ is checked.</p><p>6. Scroll down to find ‘Package Name’ property and set package name by as you wish (like: ‘com.zsasko.arcore-sample’).</p><p>7. In ‘Minimum API Level’ property select Android 7.0 ‘Nougat’ (API Level 24) or higher.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*pMZ3RIIuO3hLoWClj7bWNw.png" /></figure><p>8. In ‘XR Settings’ section, make sure that ‘ARCore Supported’ is checked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/412/1*OBFmjqV1OtDT8wifW2kaqg.png" /></figure><p>9. Now we can close ‘Project Settings’ window and in previous window ‘Build Settings’ click on ‘Add Open Scenes’ button. It will add current ‘ObjectManipulation’ scene as main scene for application. This scene will allows us also to reposition our chair and even change it’s size.</p><p>If you want to learn more on how all the Game Objects are connected, you can read the following simple guide:</p><ul><li><a href="https://developers.google.com/ar/develop/unity/tutorials/object-manipulation-sample">https://developers.google.com/ar/develop/unity/tutorials/object-manipulation-sample</a></li></ul><p>Very nice, we have imported and configured ‘ARCore SDK’ in our Unity project. We can now run the app by clicking ‘Ctrl + B’ or pressing ‘File &gt; Build And Run’ button. The app will show the pawn figure which we are going to replace with nice chair object.</p><p>When the app is running make sure that you move the camera until you see white grid:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*2eSKGf98OsmGSxIxLyMATw.jpeg" /></figure><p>This white grid indicates that user can click somewhere on the grid and by doing that he will place some object in this location.</p><p>If you have some difficulties in project setup or Android Build setup, you can read similar setup instructions on ‘ARCore Quickstart Android guide’ page:</p><ul><li><a href="https://developers.google.com/ar/develop/unity/quickstart-android">https://developers.google.com/ar/develop/unity/quickstart-android</a></li></ul><h3>Adding custom Chair model</h3><p>In the following step, we are going to replace default pawn object with our custom chair model. Custom chair model we can download from here:</p><ul><li><a href="https://free3d.com/3d-model/chair-v1--401627.html">https://free3d.com/3d-model/chair-v1--401627.html</a></li></ul><p>Extract chair model to some folder and move ‘Char_leather.jpg’ and ‘12283_Chair_v1_L3.obj’ files into ‘Materials’ folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MfGYUr9MapB9sFA0ktHGWQ.png" /></figure><p>Now we are going to create chair prefab. Create new empty ‘Game Object’ called ‘Char’ and move newly imported ‘12283_Chair_v1_L3’ material into it. Apply to the ‘12283_Chair_v1_L3’ object the following Transform values:</p><ul><li>Position: x = 0, y = 0, <strong>z = -0.54</strong></li><li>Rotation: <strong>x = -90</strong>, y = 0, z = 0</li><li>Scale: <strong>x = 0.05, y = 0.05, z = 0.05</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*3DD8hKIrAP91xsdckkAo6A.png" /></figure><p>On parent ‘Chair’ object put the following transform values:</p><ul><li>Scale: <strong>x= 0.15, y = 0.15, z = 0.15</strong></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*hPrL8JuitlJB-Wkd12qsdg.png" /></figure><p>In order to create prefab from scaled chair object, we need to move ‘Chair’ object into ‘Prefabs’ folder. Now we have successfully created prefab.</p><p>Delete ‘Chair’ GameObject from scene since it will be automatically instantiated when ARCore will detect appropriate plane for positioning it. The next step is to apply leather material to chair.</p><p>Right-click on ‘Materials’ folder add new material named ‘Leather’. In material inspector, click on ‘Albeido’ property and select ‘Chair_leather.jpg’ in order to apply this image to leather material.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/918/1*l4WQfpywj0RWZAcblir10Q.png" /></figure><p>In order to do so, we need to open prefab for editing, by double-clicking on ‘Chair’ prefab.</p><p>In ‘Chair’ object, we can see different parts of chair (like ‘Chair_back’) and to all parts we need to apply leather material, by specifying it in ‘Element 0’ property of ‘Mesh Renderer’ object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/936/1*U0y1ComKKJ82Q9cMq6xkKw.png" /></figure><p>Now return to our ‘ObjectManipulation’ scene and select ‘Pawn Generator’ game object and in ‘Pawn Prefab’ select our newly created chair prefab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*nGGJ8He5HhtcOOY5UmyzwQ.png" /></figure><p>and save scene.</p><p><strong>Voilà!</strong> Start the app and play with placing the chair.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*Xg6jFxHC9IAEzvU0dJ0R8w.png" /></figure><p>I wish you a lot of AR projects in the future! :)</p><p>Source code of sample application created in this article:</p><ul><li><a href="https://github.com/zsasko/arcore-unity-sample">https://www.github.com/zsasko/arcore-unity-sample</a></li></ul><p>[1]: “Augmented reality.” <em>Merriam-Webster.com Dictionary</em>, Merriam-Webster, <a href="https://www.merriam-webster.com/dictionary/augmented%20reality.">https://www.merriam-webster.com/dictionary/augmented%20reality.</a> Accessed 21 Aug. 2020.</p><p>[2]: “Virtual reality.” <em>Merriam-Webster.com Dictionary</em>, Merriam-Webster, <a href="https://www.merriam-webster.com/dictionary/virtual%20reality.">https://www.merriam-webster.com/dictionary/virtual%20reality.</a> Accessed 21 Aug. 2020.</p><p>[3]: Jan Tißler; “Augmented Reality in Marketing: 8 Current Examples”; dmexco, 21 Aug. 2020., <a href="https://dmexco.com/stories/augmented-reality-in-marketing-8-current-examples-2/">https://dmexco.com/stories/augmented-reality-in-marketing-8-current-examples-2/</a>; photograph.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c0ef0c72c6e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/creating-simple-ar-app-in-unity3d-using-arcore-4c0ef0c72c6e">Creating simple AR App in Unity3D using ARCore</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Facebook, Google and Email Authentication in NodeJS]]></title>
            <link>https://medium.com/swlh/implementing-facebook-google-and-email-authentication-in-nodejs-f1898c64330f?source=rss-8e90b4376a8d------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1898c64330f</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[facebook]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[email]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Zoran Šaško]]></dc:creator>
            <pubDate>Sun, 16 Aug 2020 18:26:00 GMT</pubDate>
            <atom:updated>2020-08-18T21:22:02.553Z</atom:updated>
            <content:encoded><![CDATA[<p>Every web application that stores user data need to have login and registration functionality. Besides of email login functionality, we can add login with different social network providers like Google, Facebook etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/876/1*XpU8fmdPGCRwSlcuWahzdQ.jpeg" /></figure><p>In this article we’ll explore how we can login with email, Google and Facebook. In the article we’ll also cover storing user data in MySQL database and user input validation.</p><p>At the end of this article you’ll find code sample, so if you have missed some steps, you can see the complete code sample.</p><p>Firstly, we need to put some dependencies in ‘<em>package.json</em>’:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc3d8f3ba729f47050f7297b0cff6308/href">https://medium.com/media/bc3d8f3ba729f47050f7297b0cff6308/href</a></iframe><p>In order to install all the required dependencies, we need to run the following command:</p><pre>npm install</pre><p>If you’ll encounter in some problem with parsing ‘<em>package.json</em>’ file, please execute the following commands:</p><pre>npm cache clean — force<br>npm install</pre><p>After installing all required dependencies, we can import them in ‘<em>App.js’</em>. We are going to initialize MySQL connection, initialize session and initialize other objects required for our web application. We are going to use ‘<em>EJS</em>’ templating engine and web pages will be stored in ‘<em>views</em>’ folder. Data model files will be stored in ‘<em>models</em>’ folder and configuration files will be stored in ‘<em>config</em>’ folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f73a49f387d5f75d6d856bbf84b61b5/href">https://medium.com/media/7f73a49f387d5f75d6d856bbf84b61b5/href</a></iframe><p>In ‘<em>.env</em>’ file we need to specify some general variables and the MySQL connection variables:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b852af147e2db4edf12e153ab9f861c6/href">https://medium.com/media/b852af147e2db4edf12e153ab9f861c6/href</a></iframe><p>We are going to use Sequelize ORM for fetching and storing data in MySQL database. Sequelize has it’s own CLI so we will use this tool to generate data model for us.</p><p>Firstly we need to initialize Sequelize by executing the following command:</p><pre>npx sequelize init</pre><p>and after that, we are going to generate our ‘<em>User</em>’ data model:</p><pre>npx sequelize-cli model:generate --name User --attributes name:string,email:string,social_user_id:string,password:string,registration_type:enum:&#39;{email,google,facebook}&#39;</pre><p>In ‘<em>models</em>’ folder you can see newly generated ‘<em>User</em>’ model and in migrations you can see migration generated by ‘<em>User</em>’ model. You can see that we have also specified data types for different attributes of ‘<em>User</em>’ class, in ‘<em>sequelize-cli’</em> command above.</p><p>Before we can execute the command that will create appropriate model in our MySQL database, we need to edit MySQL connection settings. We are going to use custom Sequelize configuration that will take connection data from ‘<em>.env’ </em>variable (instead of using connection data from ‘<em>config.json</em>’ file). So in order to do that, we are going to create ‘<em>.sequelizerc</em>’ file with path of database configuration file (file<em> ‘config/config.js’</em>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52a69ae1062e8e9ec83445f5a90e4540/href">https://medium.com/media/52a69ae1062e8e9ec83445f5a90e4540/href</a></iframe><p>And in ‘<em>config/config.js</em>’ we are going to set MySQL connection variables to be loaded from ‘<em>.env’</em> file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/592ec2a193e4c37746c77d19628aadf9/href">https://medium.com/media/592ec2a193e4c37746c77d19628aadf9/href</a></iframe><p>In ‘<em>models/index.js</em>’ we need to modify ‘<em>config</em>’ constant in order to load configuration from ‘.<em>js</em>’ file, instead of ‘.<em>json</em>’ file:</p><pre>const config = require(__dirname + ‘/../config/config’)[env];</pre><p>Now we are ready to make an migration, by invoking the following command</p><pre>npx sequelize db:migrate</pre><p>After successfully invoked migration, we can proceed with designing layout.</p><p>First layout file that we are going to make is home page (‘<em>views/index.ejs</em>’). In home page we are going to show appropriate messages in case if use is not authorized and if it’s authorized:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1f5effe38eb9048b5f51edc51f11aab/href">https://medium.com/media/b1f5effe38eb9048b5f51edc51f11aab/href</a></iframe><p>and for main menu we are going to use layout that will be reusable (‘<em>menu.ejs’ </em>file), so we need to put it in ‘<em>partials</em>’ folder:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7cbdcf2d3eda62379041005c35348f8/href">https://medium.com/media/f7cbdcf2d3eda62379041005c35348f8/href</a></iframe><h3>Login via email</h3><p>Configuration data for login via email, Facebook or Google is set in ‘<em>config/passport.js’</em> file. In order to add configuration for email login, we need to add ‘<em>LocalStrategy</em>’.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00f233425a9503ac6f408fdbfaf348d2/href">https://medium.com/media/00f233425a9503ac6f408fdbfaf348d2/href</a></iframe><p>In ‘<em>LocalStrategy</em>’ we are checking if user with the requested email exist. If it doesn’t exist we are sending appropriate callback notification. If it does exist, we are checking if our password is the same as encrypted password from user stored in database, by using ‘<em>bcrypt.compare</em>’ method.</p><p>Layout for the login, will also have very basic layout:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fafd431e6724406ccf4ed4e8a8e1fd0b/href">https://medium.com/media/fafd431e6724406ccf4ed4e8a8e1fd0b/href</a></iframe><p>and here we’ll going to use some other reusable component, for displaying error messages (‘<em>flash_messages.ejs</em>’ file):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e3b6c8fa950c677130823a8d8abd280/href">https://medium.com/media/4e3b6c8fa950c677130823a8d8abd280/href</a></iframe><p>Now we need to link our newly created layout files with appropriate routes, so in ‘<em>routes’ </em>folder we’ll add ‘<em>index.js’</em> route file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b6d44dbc3aa5aae876b76eab6c43ffbf/href">https://medium.com/media/b6d44dbc3aa5aae876b76eab6c43ffbf/href</a></iframe><p>In ‘<em>App.js</em>’ we are going to load this route:</p><pre>const { getHomePage } = require(‘./routes/index’);</pre><p>and assign it to appropriate request method:</p><pre>app.get(‘/’, getHomePage);</pre><p>So, now when we open our main application page, we’ll see home page.</p><p>Let us make an login route:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/62884774707b8e61d1311222e4491db3/href">https://medium.com/media/62884774707b8e61d1311222e4491db3/href</a></iframe><p>And we need to assign those routes in ‘<em>App.js’</em> file:</p><pre>const { handleLogout, postLogin, getLogin } = require(‘./routes/login’);</pre><p>To appropriate request methods:</p><pre>app.post(‘/login’, postLogin);<br>app.get(‘/login’, getLogin);<br>app.get(‘/logout’, handleLogout);</pre><p>And now we can test the email login.</p><p>For email registration (‘<em>register.ejs</em>’ file), we are going to use the following form:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b894e1e1721700ae02d341fa9e98609/href">https://medium.com/media/2b894e1e1721700ae02d341fa9e98609/href</a></iframe><p>In order to display registration form, we are going to create methods that will handle registration route methods:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63a72d2265f4b04671800db5a1916207/href">https://medium.com/media/63a72d2265f4b04671800db5a1916207/href</a></iframe><p>In ‘<em>submitRegister</em>’ method we can see that we are firstly validating user input. We are checking if user has entered the fields with right length and if email is not already used. After that, we are creating new user and redirecting it to default route (‘/’).</p><p>Note that we’ll need use registration form only for email registration, since registration via social networks will use Object data that is provided with appropriate social network library.</p><p>Now we need to add registration routes in App.js:</p><pre>const { getRegister, submitRegister } = require(‘./routes/register’);</pre><pre>app.get(‘/register’, getRegister);<br>app.post(‘/register’, submitRegister);</pre><p>Now we can check how registration via email works :)</p><h3>Login via Facebook</h3><p>Before we can implement login via Facebook in out app, we need to create API keys in Facebook app following the steps:</p><ol><li>In Developers Facebook page (https://developers.facebook.com/apps/) create new application and add ‘<em>Facebook Login</em>’ as a product.</li><li>Choose ‘Web’ integration.</li><li>For ‘Site URL’ we can put ‘<a href="http://localhost/">http://localhost</a>’.</li></ol><p>For local development, we dont’t need to specify redirect url-s, but we need to put valid url if we are deploying app to production server.</p><p>Make sure that in ‘<em>.env’</em> file, you have added appropriate facebook keys, like:</p><pre>FACEBOOK_APP_ID=your_fb_app_id<br>FACEBOOK_APP_SECRET=your_fb_app_secret<br>FACEBOOK_APP_CALLBACK_URL=http://localhost:5003/auth/facebook/callback</pre><p>Now we need to add appropriate strategy in ‘<em>config/passport.js’</em>, so passport library will be able to handle facebook login callbacks.</p><p>On the top of ‘<em>passport.js</em>’ we’ll import ‘<em>FacebookStrategy’ </em>object:</p><pre>const FacebookStrategy = require(“passport-facebook”).Strategy;</pre><p>and we’ll specify other configuration options required for Facebook authorization:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e7b46f6399b602d83e5dd9a963e18d4/href">https://medium.com/media/5e7b46f6399b602d83e5dd9a963e18d4/href</a></iframe><p>In asynchronous function in ‘<em>FacebookStrategy’</em>, we are creating new user if it doesn’t exist and returning already existing user to callback ‘<em>cb</em>’.</p><p>In order to display facebook login page, we need to add two methods for handling facebook login routes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e7365569822fd1b87302c89a6134e4f6/href">https://medium.com/media/e7365569822fd1b87302c89a6134e4f6/href</a></iframe><p>and for above specified methods, we need to assign appropriate routes:</p><pre>const { getFacebookLogin, handleFacebookLogin } = require(&#39;./routes/facebook_login&#39;);</pre><pre>app.get(‘/auth/facebook’, getFacebookLogin);<br>app.get(‘/auth/facebook/callback’, handleFacebookLogin);</pre><p>In the similar way, we are going to implement login via Google.</p><h3>Login via Google</h3><p>In order to make Login via Google possible, we need to create appropriate project and API keys.</p><p>The steps to get Google API Keys:</p><ol><li>In Google Api Console (https://console.developers.google.com/) create new project.</li><li>In ‘<em>Credentials</em>’ page and create new ‘OAuth Client ID’. If you need to create content for consent screen, in ‘Oauth Consent screen’ choose ‘External’ as ‘User Type’ and get back to ‘Creadentials’ page to start creating ‘OAuth Client ID’ again.</li><li>In ‘<em>Authorized Redirect URIs</em>’ field add calback url:<br><a href="http://localhost:5000/auth/google/callback">http://localhost:5000/auth/google/callback</a></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f70LF57vvXz3SQfyXv-XFQ.png" /></figure><p>Make sure that in ‘<em>.env’</em> file, you have added appropriate google keys, like:</p><pre>GOOGLE_CLIENT_ID=your_google_client_id<br>GOOGLE_CLIENT_SECRET=your_google_client_secret<br>GOOGLE_APP_CALLBACK_URL=http://localhost:5000/auth/google/callback</pre><p>Firstly we need to import Google Strategy in passport.js:</p><pre>const GoogleStrategy = require(“passport-google-oauth20”).Strategy;</pre><p>And we need to add ‘<em>GoogleStrategy’</em>, to ‘<em>passport</em>’ object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52190664712c4866e365cfee02aa7736/href">https://medium.com/media/52190664712c4866e365cfee02aa7736/href</a></iframe><p>Similarly like in ‘<em>FacebookProvider’</em>, in ‘<em>GoogleProvider’ </em>asynchronous function we are going to return existing user or insert new user, if user is not already existing.</p><p>Google login methods we are specifying in ‘<em>google_login.js</em>’ route file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f03de9bcbe5d9ed46f27d30eadab433e/href">https://medium.com/media/f03de9bcbe5d9ed46f27d30eadab433e/href</a></iframe><p>and they need to be assigned to appropriate routes in ‘<em>App.js</em>’:</p><pre>const { getGoogleLogin, handleGoogleLogin } = require(‘./routes/google_login’);</pre><pre>app.get(‘/auth/google’, getGoogleLogin);<br>app.get(‘/auth/google/callback’, handleGoogleLogin);</pre><p>Congratulations, you have successfully created application with multiple authorization providers!</p><p>Source code of sample application built in this article:</p><ul><li><a href="https://github.com/zsasko/nodejs-social-auth-example">https://github.com/zsasko/nodejs-social-auth-example</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1898c64330f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/implementing-facebook-google-and-email-authentication-in-nodejs-f1898c64330f">Implementing Facebook, Google and Email Authentication in NodeJS</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>