<?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 Thinley Norbu on Medium]]></title>
        <description><![CDATA[Stories by Thinley Norbu on Medium]]></description>
        <link>https://medium.com/@thinley-norbu?source=rss-1f903ec5531a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*KlPYd79-KiPimB1lz32hAQ.jpeg</url>
            <title>Stories by Thinley Norbu on Medium</title>
            <link>https://medium.com/@thinley-norbu?source=rss-1f903ec5531a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 19:02:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thinley-norbu/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[Introduction to D3 js]]></title>
            <link>https://thinley-norbu.medium.com/introduction-to-d3-js-8fbce95b1008?source=rss-1f903ec5531a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fbce95b1008</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[svg]]></category>
            <category><![CDATA[js]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[d3js]]></category>
            <dc:creator><![CDATA[Thinley Norbu]]></dc:creator>
            <pubDate>Tue, 29 Jun 2021 04:49:04 GMT</pubDate>
            <atom:updated>2021-07-21T01:39:54.427Z</atom:updated>
            <content:encoded><![CDATA[<p>Getting to know D3 js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MdbrEJqtKZULv8U3tnG9Dw.png" /><figcaption>Data-driven document</figcaption></figure><p>This article aims to give you an overview of D3(Data-Driven Documents). It is an open-source JavaScript library that can be used to create data visualizations on the web by using HTML, CSS, and SVG.</p><p>What do we use D3 JS for:</p><ul><li>Create different styles of visual representation for data.</li><li>Create dynamic visualization with transitions and transformation.</li><li>DOM manipulation</li><li>Interaction and animation</li></ul><p>So without any further ado, let’s proceed towards understanding some concepts related to D3.</p><p>Installing d3 onto your existing project is pretty straightforward. Just go through this <a href="https://www.npmjs.com/package/d3">link</a> and you’ll be good to go.</p><p><strong>Fundamental concepts of D3</strong></p><ul><li><strong>Selection</strong>: Jquery-like selection is used to select DOM elements.</li><li><strong>DOM manipulation: </strong>After having the DOM element selected, add or modify something within the DOM element.</li><li><strong>Method Chaining: </strong>create a pipeline of methods that each transform an object.</li><li><strong>Data joins: </strong>Bind data to selected elements to loop through to make the DOM manipulation easier.</li></ul><ol><li><strong>Selection</strong>:</li></ol><p>We can select the DOM element in different ways. I normally use selection in three ways.</p><ul><li>By element:</li></ul><pre>&lt;body&gt;</pre><pre>&lt;div&gt;Showing effect of the style method&lt;/div&gt;</pre><pre>&lt;/body&gt;</pre><p>For eg: If our DOM structure looks like this. We can select the div by simply calling our selection like this.</p><pre>d3.select(&#39;div&#39;);</pre><p>If we want to select all the divs that are present in the DOM. We can use the selectAll function of D3.</p><pre>d3.selectAll(&#39;div&#39;);</pre><ul><li>By class name:</li></ul><pre>&lt;body&gt;</pre><pre>&lt;div class=&quot;select-me&quot;&gt;Showing effect of the style method&lt;/div&gt;</pre><pre>&lt;/body&gt;</pre><p>We can select a DOM element by using their class name similar to Jquery syntax.</p><pre>d3.selectAll(&#39;.select-me&#39;);</pre><p>This will select all the DOM elements which match the class ‘select-me’.</p><ul><li>By id:</li></ul><pre>&lt;body&gt;</pre><pre>&lt;div id=&quot;select-me&quot;&gt;Showing effect of the style method&lt;/div&gt;</pre><pre>&lt;/body&gt;</pre><p>Select the DOM element by</p><pre>d3.select(&#39;#select-me&#39;);</pre><p>2. <strong>DOM manipulation:</strong></p><p>We can manipulate the DOM element after they are selected. We can use the style() method to the selection to style the element like we intend to.</p><p>Similarly, we can use manipulating methods such as attr(), append() and many more to manipulate the selection.</p><p>3. <strong>Method Chaining</strong>:</p><p>As the name suggests, it lets us chain multiple methods together. For eg:</p><pre>d3.select(&#39;#select-me&#39;).style(&quot;color&quot;, &quot;red&quot;).style(&quot;width&quot;, &quot;40px&quot;);</pre><p><strong>What does the above code suggest?</strong></p><p>First, select a DOM element with ‘select-me’ id. Apply ‘red’ color to that selection and then apply ‘40px’ width to that selection. Pretty simple, right?</p><pre>d3.select(&#39;#select-me&#39;).style(&quot;color&quot;, &quot;red&quot;).style(&quot;width&quot;, &quot;40px&quot;).selectAll(&#39;div&#39;);</pre><p>Similarly, the above example does all the tasks explained earlier and then gives us the selection of all the div which are children of the earlier selection. From there, we can do more manipulation to the newly selected children.</p><p>4. <strong>Data joins:</strong></p><p>Now this concept was a bit hard to understand at first for me.</p><p>Data joins allow us to bind selected elements to the data of an array. By using data joins, the visualization we create becomes more reactive to the data.</p><p>Three main methods for the data join process are</p><ul><li>data(): This is used to bind data. It’s much like looping through a set of data. The data() function joins the specified array of data to the selected DOM elements and returns the updated selection.</li></ul><pre>&lt;script&gt;<br>        var myData = [&quot;Hello World!&quot;];<br>     <br>        var p = d3.select(&quot;body&quot;)<br>            .selectAll(&quot;p&quot;)<br>            .data(myData)<br>            .text(function (d) {<br>                return d;<br>            });<br>&lt;/script&gt;</pre><p>In the above example, it will return “Hello world” once as myData only has one element in the array.</p><ul><li>enter(): This is used to execute certain manipulation when there is remaining data from the bind data but there is no selection left. The <strong>d3.selection.enter()</strong> function in D3.js is used to create the missing elements and return the enter selection. For eg:</li></ul><pre>&lt;body&gt;<br>// NO div are here<br>&lt;/body&gt;<br>&lt;script&gt;<br>        var myData = [&quot;Hello&quot;,&quot;World&quot;,&quot;!&quot;];<br>     <br>        var p = d3.select(&quot;div&quot;)<br>            .data(myData)<br>            .enter().append(&#39;div&#39;)<br>            .text(function (d) {<br>                return d;<br>            });<br>&lt;/script&gt;</pre><p>It will result in adding three new div with text contents of the array myData.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/253/1*vwLiGy0F2CDyl7X4EDaCAg.png" /><figcaption>Example of enter()</figcaption></figure><ul><li>merge(): This is used to merge the DOM manipulation before and after enter() together.</li></ul><pre>u.enter().append(&quot;circle&quot;).attr(&quot;r&quot;,5)<br>     .merge(u)//after this, any update applies to both u &amp; enter()             <br>     .attr(&quot;cx&quot;, d =&gt; d.x)<br>     .attr(&quot;cy&quot;, d =&gt; d.y)</pre><ul><li>exit(): D3 doesn’t naturally delete excess selections. Exit() comes in handy when you want to do some manipulation to the excess selections. Usually, I use it to remove the excess selections because that is the more expected output.</li></ul><pre>function print(data) {<br>var divs = d3.selectAll(&#39;div&#39;).data(data);</pre><pre>divs.enter();<br>   .append(&#39;div&#39;)<br>   .merge(divs)<br>   .text(d =&gt; {<br>     return d;<br>    });</pre><pre>// divs.exit().remove();</pre><pre>}</pre><pre>print([&#39;The&#39;,&#39;great&#39;, &#39;exit&#39;, &#39;function&#39;, &#39;in&#39;, &#39;action&#39;]);</pre><pre>print([&#39;Remove&#39;, &#39;excess&#39;, &#39;selection&#39;])</pre><p>By removing the divs.exit().remove(), we get a strange output that may look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/113/1*QFU_w2oqVVcBQ4LUDQXLuA.png" /></figure><p>Yes, we expected the ‘Remove’,’ excess’, and ‘selection’ div to be printed but we are getting ‘function’, ‘in’, and ‘action’ divs which were appended by the earlier function call. We can fix this by uncommenting the divs.exit().remove() line. After that, we execute remove() on the additional selection left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/140/1*S2Bg5R-nSBQ7a6NmW6Xiyg.png" /></figure><p>Fixed. Pheww! :D</p><p>I hope you got a basic overview of how things work in D3 with this article. Well, there are much more features provided by D3. Another interesting concept to grasp would be scales provided by D3. I will be writing about scales in my next article. Till then, I hope this article will help someone curious about D3. Happy Learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fbce95b1008" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PDF generation in GO]]></title>
            <link>https://articles.wesionary.team/pdf-generation-in-go-8385cfc6660b?source=rss-1f903ec5531a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8385cfc6660b</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[wkhtmltopdf]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[pdf]]></category>
            <dc:creator><![CDATA[Thinley Norbu]]></dc:creator>
            <pubDate>Thu, 26 Nov 2020 16:20:43 GMT</pubDate>
            <atom:updated>2020-11-27T08:16:19.540Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/781/0*biNvWUr6EtEXY5Nu.jpg" /><figcaption>PDF generation in GOlang</figcaption></figure><p>Previously, we talked about generating PDF in React. While it works fine, there are various scenarios where generating PDF in React might not be a viable solution. So in this article, I want to demonstrate a quick way to generate PDF in GO.</p><p>I came across a lot of packages in GO for PDF generation after some research viz. gopdf, gofpdf, go-wkhtmltopdf, etc. While packages like gopdf and gofpdf offer us a solution for PDF generation but I found it takes lot of work to generate PDF with complex design.</p><p>So for this article, we will only talk about go-wkhtmltopdf because I found it easy to use. Basically, what we do is use html template to generate a PDF.</p><p>We can install this package by running the following command.</p><pre>go get -u github.com/SebastiaanKlippert/go-wkhtmltopdf</pre><p>Bear in mind that this package is a Golang command line wrapper for wkhtmltopdf. So we got to have wkhtmltopdf installed in our system. We can have it installed easily by running following command.</p><pre>sudo apt-get install xvfb libfontconfig wkhtmltopdf</pre><p>Now we are ready to do some PDF generation. Have a look at below code.</p><pre>package pdfGenerator<br><br>import (<br>	&quot;bytes&quot;<br>	&quot;html/template&quot;<br>	&quot;io/ioutil&quot;<br>	&quot;log&quot;<br>	&quot;os&quot;<br>	&quot;strconv&quot;<br>	&quot;time&quot;<br><br>	&quot;github.com/SebastiaanKlippert/go-wkhtmltopdf&quot;<br>)<br><br>//pdf requestpdf struct<br>type RequestPdf struct {<br>	body string<br>}<br><br>//new request to pdf function<br>func NewRequestPdf(body string) *RequestPdf {<br>	return &amp;RequestPdf{<br>		body: body,<br>	}<br>}<br><br>//parsing template function<br>func (r *RequestPdf) ParseTemplate(templateFileName string, data interface{}) error {<br><br>	t, err := template.ParseFiles(templateFileName)<br>	if err != nil {<br>		return err<br>	}<br>	buf := new(bytes.Buffer)<br>	if err = t.Execute(buf, data); err != nil {<br>		return err<br>	}<br>	r.body = buf.String()<br>	return nil<br>}<br><br>//generate pdf function<br>func (r *RequestPdf) GeneratePDF(pdfPath string) (bool, error) {<br>	t := time.Now().Unix()<br>	// write whole the body<br>	err1 := ioutil.WriteFile(&quot;storage/&quot;+strconv.FormatInt(int64(t), 10)+&quot;.html&quot;, []byte(r.body), 0644)<br>	if err1 != nil {<br>		panic(err1)<br>	}<br><br>	f, err := os.Open(&quot;storage/&quot; + strconv.FormatInt(int64(t), 10) + &quot;.html&quot;)<br>	if f != nil {<br>		defer f.Close()<br>	}<br>	if err != nil {<br>		log.Fatal(err)<br>	}<br><br>	pdfg, err := wkhtmltopdf.NewPDFGenerator()<br>	if err != nil {<br>		os.Remove(&quot;storage/&quot; + strconv.FormatInt(int64(t), 10) + &quot;.html&quot;)<br>		log.Fatal(err)<br>	}<br><br>	pdfg.AddPage(wkhtmltopdf.NewPageReader(f))<br><br>	pdfg.PageSize.Set(wkhtmltopdf.PageSizeA4)<br><br>	pdfg.Dpi.Set(300)<br><br>	err = pdfg.Create()<br>	if err != nil {<br>		log.Fatal(err)<br>	}<br><br>	err = pdfg.WriteFile(pdfPath)<br>	if err != nil {<br>		log.Fatal(err)<br>	}<br>	os.Remove(&quot;storage/&quot; + strconv.FormatInt(int64(t), 10) + &quot;.html&quot;)<br><br>	return true, nil<br>}</pre><p>We have some setup done for functions that uses wkhtmltopdf. We can use this functions as our need in our app flow.</p><p>Next thing is our html template. Create a html and add required CSS. We can leave space for our data by following syntax.</p><pre>{{.Data}}</pre><p>This way, we can replace this variable by actual data in our document.</p><pre>package main<br><br>import (<br>	&quot;fmt&quot;<br>	&quot;os&quot;<br><br>	u &quot;github.comm/gofpdftable/pdfGenerator&quot;<br>)<br><br>func main() {<br><br>	r := u.NewRequestPdf(&quot;&quot;)<br><br>	//html template path<br>	templatePath := &quot;templates/sample.html&quot;<br><br>	//path for download pdf<br>	outputPath := &quot;./storage/pdf.pdf&quot;<br>	<br><br>	//html template data<br>	templateData := struct {<br>	    Data string<br>	}{<br>	   Data: &quot;data&quot;<br>	}<br><br>	if err := r.ParseTemplate(templatePath, templateData); err == nil {<br>		ok, _ := r.GeneratePDF(outputPath)<br>		fmt.Println(ok, &quot;pdf generated successfully&quot;)<br>	} else {<br>		fmt.Println(err)<br>	}<br>}</pre><p>We can supply data to our template by this way. Now, the Data’s string “data” will be put to the place where {{.Data}} is kept in our html template.</p><p>Now run main.go, we should have PDF generated from our html template.</p><p>We can also make a loop inside our html template to make the content dynamic. We can follow this syntax to do so.</p><pre>{{ range $key, $value := $value }}</pre><pre>&lt;div&gt;{{ $value }}&lt;/div&gt;</pre><pre>{{ end }}</pre><p>This way, we can have our PDF generated in a easy and non tiring way. What is your thoughts on this method? Any suggestions and feedback are welcome. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8385cfc6660b" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/pdf-generation-in-go-8385cfc6660b">PDF generation in GO</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Highlight header according to scroll section]]></title>
            <link>https://articles.wesionary.team/highlight-header-according-to-scroll-section-3ee21be0185e?source=rss-1f903ec5531a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ee21be0185e</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[stickyheader]]></category>
            <category><![CDATA[navbar]]></category>
            <dc:creator><![CDATA[Thinley Norbu]]></dc:creator>
            <pubDate>Tue, 06 Oct 2020 17:26:51 GMT</pubDate>
            <atom:updated>2020-10-06T17:26:51.660Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I had to make a sticky header such that when the page gets scrolled, the items on the header got highlighted accordingly. You might have seen them in many websites, the ones where we can click on the certain section of the header to get scrolled down to that section. At first glance, I thought it would be easy to implement it. But as I tried implementing it, I realized it wasn’t as easy as I thought it would be. :)</p><p>So, I tried using <a href="https://www.npmjs.com/package/react-visibility-sensor">react-visiblity-sensor</a>. This package lets us know if a certain component is visible in our view-port. I thought I can implement the highlight according to which component is visible in our view-port. Theoretically, I thought it would be a great solution. But after going halfway through, I came to a realization that when two section are present in the view-port, the results were not quite accurate. So I had to look for another solution.</p><p>After looking around for quite a bit, I had to completely dump the use of react-visibility sensor. I will explain what I did as a solution by demonstrating each step from a practice project.</p><p>For the header, we have three buttons in header. They are Red, Green and Blue.</p><pre>&lt;div className=&quot;sticky&quot;&gt;<br>&lt;div className=&quot;header&quot; ref={headerRef}&gt;</pre><pre>&lt;button<br>type=&quot;button&quot;<br>className={`header_text ${visibleSection === &quot;red&quot; ? &quot;selected&quot; : &quot;&quot;}`}<br>onClick={() =&gt; {<br>scrollTo(redRef.current);<br>}}&gt;</pre><pre>Red</pre><pre>&lt;/button&gt;</pre><pre>&lt;button<br>type=&quot;button&quot;<br>className={`header_text ${visibleSection === &quot;green&quot; ? &quot;selected&quot; : &quot;&quot;}`}<br>onClick={() =&gt; {<br>scrollTo(providerRef.current);<br>}}&gt;</pre><pre>Green</pre><pre>&lt;/button&gt;</pre><pre>&lt;button<br>type=&quot;button&quot;<br>className={`header_text ${visibleSection === &quot;blue&quot; ? &quot;selected&quot; : &quot;&quot;}`}<br>onClick={() =&gt; {<br>scrollTo(blueRef.current);<br>}}&gt;</pre><pre>Blue</pre><pre>&lt;/button&gt;</pre><pre>&lt;/div&gt;</pre><pre>&lt;/div&gt;</pre><p>To make the header sticky, add following css to sticky class name.</p><pre>.sticky {<br>position: sticky;<br>top: 0;<br>left: 0;<br>right: 0;<br>z-index: 10;<br>}</pre><p>Now, you may wonder where all those refs in our code is coming from. We use the useRef Hook to create ref for each sections.</p><pre>const headerRef = useRef(null);<br>const redRef = useRef(null);<br>const providerRef = useRef(null);<br>const blueRef = useRef(null);</pre><pre>const sectionRefs = [<br>{ section: &quot;red&quot;, ref: redRef },<br>{ section: &quot;green&quot;, ref: providerRef },<br>{ section: &quot;blue&quot;, ref: blueRef },<br>];</pre><p>And then attach each ref to its respective section such as:</p><pre>&lt;div className=&quot;section&quot; id=&quot;red&quot; ref={redRef} /&gt;</pre><pre>&lt;div className=&quot;section&quot; id=&quot;green&quot; ref={providerRef} /&gt;</pre><pre>&lt;div className=&quot;section&quot; id=&quot;blue&quot; ref={blueRef} /&gt;</pre><p>Now, we use the following functions to update our state according to the section we are currently viewing.</p><pre>const [visibleSection, setVisibleSection] = useState();</pre><pre>const getDimensions = ele =&gt; {<br>const { height } = ele.getBoundingClientRect();<br>const offsetTop = ele.offsetTop;<br>const offsetBottom = offsetTop + height;<br>return {<br>height,<br>offsetTop,<br>offsetBottom,<br>};<br>};</pre><pre>useEffect(() =&gt; {<br>const handleScroll = () =&gt; {<br>const { height: headerHeight } = getDimensions(headerRef.current);<br>const scrollPosition = window.scrollY + headerHeight;<br>const selected = sectionRefs.find(({ section, ref }) =&gt; {<br>const ele = ref.current;<br>if (ele) {<br>const { offsetBottom, offsetTop } = getDimensions(ele);<br>return scrollPosition &gt; offsetTop &amp;&amp; scrollPosition &lt; offsetBottom;<br>}<br>});</pre><pre>if (selected &amp;&amp; selected.section !== visibleSection) {<br>setVisibleSection(selected.section);<br>} else if (!selected &amp;&amp; visibleSection) {<br>setVisibleSection(undefined);<br>}<br>};</pre><pre>handleScroll();<br>window.addEventListener(&quot;scroll&quot;, handleScroll);<br>return () =&gt; {<br>window.removeEventListener(&quot;scroll&quot;, handleScroll);<br>};<br>}, [visibleSection]);</pre><p>What we are doing basically is that we calculate the total scroll position that are viewing, then calculate in which position is the section according to the scroll position. getDimension function returns us the height, offsetTop and offsetBottom by using the refs we attached earlier. After putting it all together, we get something that looks like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g9Suq6VMZ0DS_Hyujn39Eg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*ZhS7VG7kQIqCinDqh2RyIw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*LZUCM-t38bT58rz4evwAHg.png" /><figcaption>Header items getting highlighted according the section we are viewing.</figcaption></figure><p>I hope this will article will help to create a similar sticky header. Here, is the link to the <a href="https://github.com/ThinleyN/stickyHighlightHeader"><strong><em>repo</em></strong></a> if you want to play around with it yourself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ee21be0185e" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/highlight-header-according-to-scroll-section-3ee21be0185e">Highlight header according to scroll section</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PDF generation in React.]]></title>
            <link>https://articles.wesionary.team/pdf-generation-in-react-1f5bb8064c5f?source=rss-1f903ec5531a------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f5bb8064c5f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[jspdf]]></category>
            <category><![CDATA[html2canvas]]></category>
            <category><![CDATA[pdf]]></category>
            <dc:creator><![CDATA[Thinley Norbu]]></dc:creator>
            <pubDate>Thu, 20 Aug 2020 12:59:06 GMT</pubDate>
            <atom:updated>2020-08-20T12:59:06.638Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Discussion on PDF generation in React.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6M5zTS3K-pH06-Kt.jpg" /><figcaption>PDF generation in React.</figcaption></figure><p>Generating PDF can be a troublesome task. To style the whole PDF document can be a real pain. While there are several approaches to generate PDF. Generating PDF on server side being one of them. I personally felt this approach a bit cumbersome. But you can surely go and have a look.</p><p>So, we are going to discuss some methods for PDF generation in React.</p><ol><li>Using jspdf.</li><li>Using html2canvas and jspdf</li><li>Using React-PDF</li></ol><h4>1. Using jspdf.</h4><p>The first method is the inefficient way to generate the PDF in my POV because by this method, we have to design the whole PDF in the code. It can take a good amount of time to generate PDF using this method.</p><h4>How this works?</h4><pre><strong>import</strong> { jsPDF } <strong>from</strong> &quot;jspdf&quot;;</pre><pre>const doc <strong>=</strong> <strong>new</strong> jsPDF();</pre><pre>doc.text(&quot;Hello world!&quot;, 10, 10);</pre><pre>doc.save(&quot;a4.pdf&quot;);</pre><p><a href="https://www.npmjs.com/package/jspdf">jsPdf</a> provides us methods to add text and images in our PDF. We have to define each x and y co-ordinates for our text and images and design our PDF likewise. In addition to this, design with dynamic content can be huge issue here. This method can be used if the PDF to be generated is not of a complex design.</p><h4>2. Using html2canvas and jspdf</h4><p>I personally found this method easy and effective as it allows us to take a HTML element, convert it to image form and add it to our PDF. This way it eliminates the need for us to design our PDF because we are simply taking our web design into the page.</p><p><a href="https://html2canvas.hertzen.com/">html2canvas</a> is a fairly simple library that allows us to take DOM element and convert it canvas element which can be useful in handful of scenarios.</p><p>We take the canvas obtained from html2canvas and then convert it to a PNG image. And finally, render it to the PDF using jspdf.</p><p>Lets go by an example:</p><pre>import html2canvas from &#39;html2canvas&#39;;<br>import { jsPDF } from &quot;jspdf&quot;;</pre><pre>const divToDisplay = document.getElementById(&#39;div&#39;)</pre><pre>html2canvas(divToDisplay).then(function(canvas) {<br>     const divImage = canvas.toDataURL(&quot;image/png&quot;);<br>     const pdf = new jsPDF();<br>    pdf.addImage(divImage, &#39;PNG&#39;, 0, 0);<br>    pdf.save(&quot;download.pdf&quot;);<br>})</pre><p>This way we can directly get a target element to render on our PDF.</p><p>So far looking good. But, what if the content of the target elements is longer than the PDF page. Now, we have to write some logic for the page break.</p><p>Logic for page break:</p><ol><li>Calculate the height of the HTML content.</li><li>Calculate the height of the PDF page.</li><li>Calculate the total page required for overall content. <em>(Math.ceil(heightOfHTML/heightOfPage))</em></li><li>Render each part of HTML content on its respective page.</li></ol><pre>for (var i = 1; i &lt;= totalPDFPages; i++) {<br>    pdf.addPage();<br>    pdf.addImage(imgData, &#39;JPG&#39;, 0, (-HTMLContent_Height*i),width,height)<br>}</pre><p>So now, we solved page break issue as well. It must work well in case of mulitple page generation now.</p><p>NOTE: <em>If images from outer source are present in the HTML content, this method won’t catch such images. In such cases, the images must be converted into Base64 string.You can follow </em><a href="https://stackoverflow.com/questions/22172604/convert-image-url-to-base64"><em>this</em></a><em> to do that. I personally, spent a good amount of time trying to solve this. Hopefully, this note will help someone in future.</em></p><h4>3. React-PDF</h4><p>This library allows us to render PDF in our React app. It supports the generation of it as well. React-PDF goes with the React-Native approach. It gives us its own components like &lt;Page&gt;, &lt;View&gt;,&lt;Text&gt;, etc. Then, we have to design our PDF using the given components.</p><p>The reason I didn’t go with this approach is that, we now had to design the whole page for the second time just to get them in PDF. And it doesn’t allow us to use native HTML too. But surely, this method also provides us some level of flexibility. We can definitely try this method to get the feel of it.</p><p>All in all, there are several method we can go by to solve the problem. There are paid services such as <a href="https://blog.usejournal.com/lets-make-a-resume-in-react-2c9c5540f51a"><strong>Kendo-React</strong></a><strong> </strong>which makes the whole process easier. You go through them as well if you are interested.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f5bb8064c5f" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/pdf-generation-in-react-1f5bb8064c5f">PDF generation in React.</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CRUD API using GO]]></title>
            <link>https://articles.wesionary.team/crud-api-using-go-d55b0ace211e?source=rss-1f903ec5531a------2</link>
            <guid isPermaLink="false">https://medium.com/p/d55b0ace211e</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[gorm]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[gin]]></category>
            <dc:creator><![CDATA[Thinley Norbu]]></dc:creator>
            <pubDate>Tue, 18 Aug 2020 10:09:21 GMT</pubDate>
            <atom:updated>2020-08-20T09:50:36.610Z</atom:updated>
            <content:encoded><![CDATA[<h3>CRUD API using GO, GIN, MySql</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L5Kvhh3Xy5jT46Xb.png" /></figure><p>GO has been around for a quite long time now. It is considered as one of the fastest programming language with high performance. In this article, I will be sharing how I wrote CRUD API using GO. Technologies used in this article are GO, Gin, GORM and Mysql.</p><blockquote>Gin is a web framework written in Go (Golang). It features a martini-like API with performance that is up to 40 times faster thanks to <a href="https://github.com/julienschmidt/httprouter">httprouter</a>.</blockquote><p>GORM is a ORM library for GOlang.</p><p>I am providing the <a href="https://github.com/ThinleyN/toDoGolang/tree/master/bookCRUD">github link</a> to the repository for this article.</p><p>So let’s start writing CRUD API now. Create a new GO project and install the related dependencies. We install GORM, Gin and Mysql by running following commands.</p><pre>go get github.com/go-sql-driver/mysql<br>go get github.com/gin-gonic/gin<br>go get github.com/jinzhu/gorm</pre><p>For setting up our Mysql database. We can add the following piece of code.</p><pre>package models</pre><pre>import (<br>&quot;fmt&quot;<br>_ &quot;github.com/go-sql-driver/mysql&quot;<br>&quot;github.com/jinzhu/gorm&quot;<br>)</pre><pre>// SetupDB : initializing mysql database</pre><pre>func SetupDB() *gorm.DB {<br>USER := &quot;root&quot;<br>PASS := &quot;password&quot;<br>HOST := &quot;localhost&quot;<br>PORT := &quot;3306&quot;<br>DBNAME := &quot;bookCRUD&quot;<br>URL := fmt.Sprintf(&quot;%s:%s@tcp(%s:%s)/%s?charset=utf8&amp;parseTime=True&amp;loc=Local&quot;, USER, PASS, HOST, PORT, DBNAME)</pre><pre>db, err := gorm.Open(&quot;mysql&quot;, URL)</pre><pre>if err != nil {<br>panic(err.Error())<br>}</pre><pre>return db</pre><pre>}</pre><p>For the sake of simplicity, I have left the user ,password and other credentials hard coded. You can load it from env file too. We connect to mysql using the gorm.Open.</p><p>Now we create our first model. We can create our model by using following code.</p><pre>// models/book.go<br>package models</pre><pre>type Task struct {</pre><pre>ID         uint   `json:&quot;id&quot; gorm:&quot;primary_key&quot;`</pre><pre>AssingedTo string `json:&quot;assignedTo&quot;`</pre><pre>Task       string `json:&quot;task&quot;`</pre><pre>}</pre><p>Nothing much here, we just have id, assigedto and task field. Id is unique int whereas assignedto and task are strings.</p><p>Now,we move towards configuring our routes for the API. Generally, we make a separate file for routes but to keep it short, I have added the routes in the main.go file. It can look something like this.</p><pre>package main</pre><pre>import (<br>&quot;bookCRUD/controllers&quot;<br>&quot;bookCRUD/models&quot;<br>&quot;net/http&quot;<br>&quot;github.com/gin-gonic/gin&quot;<br>)</pre><pre>func main() {<br>r := gin.Default()<br>db := models.SetupDB()<br>db.AutoMigrate(&amp;models.Task{})<br>r.Use(func(c *gin.Context) {<br>c.Set(&quot;db&quot;, db)<br>})</pre><pre>r.GET(&quot;/&quot;, func(c *gin.Context) {<br>c.JSON(http.StatusOK, gin.H{&quot;data&quot;: &quot;hello world&quot;})<br>})<br>r.GET(&quot;/tasks&quot;, controllers.FindTasks) <br>r.POST(&quot;/tasks&quot;, controllers.CreateTask)<br>r.GET(&quot;/tasks/:id&quot;, controllers.FindTask)<br>r.PATCH(&quot;/tasks/:id&quot;, controllers.UpdateTask)<br>r.DELETE(&quot;tasks/:id&quot;, controllers.DeleteTask)<br>r.Run()<br>}</pre><p>We can now make controllers that handles the request on the routes configured. The controllers file can be something like this.</p><pre>// controllers/books.go</pre><pre>package controllers</pre><pre>import (</pre><pre>// &quot;bookc/models&quot;<br>&quot;bookCRUD/models&quot;<br>&quot;net/http&quot;<br>&quot;github.com/gin-gonic/gin&quot;<br>&quot;github.com/jinzhu/gorm&quot;</pre><pre>)</pre><pre>type CreateTaskInput struct {<br>AssingedTo string `json:&quot;assignedTo&quot;`<br>Task       string `json:&quot;task&quot;`<br>}</pre><pre>type UpdateTaskInput struct {<br>AssingedTo string `json:&quot;assignedTo&quot;`<br>Task       string `json:&quot;task&quot;`<br>}</pre><pre>// GET /tasks</pre><pre>// Get all tasks<br>func FindTasks(c *gin.Context) {<br>db := c.MustGet(&quot;db&quot;).(*gorm.DB)<br>var tasks []models.Task<br>db.Find(&amp;tasks)<br>c.JSON(http.StatusOK, gin.H{&quot;data&quot;: tasks})<br>}</pre><pre>// POST /tasks</pre><pre>// Create new task</pre><pre>func CreateTask(c *gin.Context) {<br>// Validate input<br>var input CreateTaskInput<br>if err := c.ShouldBindJSON(&amp;input); err != nil {<br>c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()})<br>return<br>}</pre><pre>// Create task</pre><pre>task := models.Task{AssingedTo: input.AssingedTo, Task: input.Task}<br>db := c.MustGet(&quot;db&quot;).(*gorm.DB)<br>db.Create(&amp;task)<br>c.JSON(http.StatusOK, gin.H{&quot;data&quot;: task})<br>}</pre><pre>// GET /tasks/:id</pre><pre>// Find a task</pre><pre>func FindTask(c *gin.Context) { // Get model if exist<br>var task models.Task<br>db := c.MustGet(&quot;db&quot;).(*gorm.DB)</pre><pre>if err := db.Where(&quot;id = ?&quot;, c.Param(&quot;id&quot;)).First(&amp;task).Error; err != nil {</pre><pre>c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: &quot;Record not found!&quot;})<br>return<br>}</pre><pre>c.JSON(http.StatusOK, gin.H{&quot;data&quot;: task})</pre><pre>}</pre><pre>// PATCH /tasks/:id</pre><pre>// Update a task</pre><pre>func UpdateTask(c *gin.Context) {</pre><pre>db := c.MustGet(&quot;db&quot;).(*gorm.DB)</pre><pre>// Get model if exist</pre><pre>var task models.Task</pre><pre>if err := db.Where(&quot;id = ?&quot;, c.Param(&quot;id&quot;)).First(&amp;task).Error; err != nil {</pre><pre>c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: &quot;Record not found!&quot;})</pre><pre>return</pre><pre>}</pre><pre>// Validate input<br>var input UpdateTaskInput<br>if err := c.ShouldBindJSON(&amp;input); err != nil {<br>c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: err.Error()})<br>return<br>}</pre><pre>db.Model(&amp;task).Updates(input)</pre><pre>c.JSON(http.StatusOK, gin.H{&quot;data&quot;: task})<br>}</pre><pre>// DELETE /tasks/:id</pre><pre>// Delete a task</pre><pre>func DeleteTask(c *gin.Context) {<br>// Get model if exist<br>db := c.MustGet(&quot;db&quot;).(*gorm.DB)<br>var book models.Task<br>if err := db.Where(&quot;id = ?&quot;, c.Param(&quot;id&quot;)).First(&amp;book).Error; err != nil {<br>c.JSON(http.StatusBadRequest, gin.H{&quot;error&quot;: &quot;Record not found!&quot;})<br>return<br>}</pre><pre>db.Delete(&amp;book)</pre><pre>c.JSON(http.StatusOK, gin.H{&quot;data&quot;: true})</pre><pre>}</pre><p>Now we are ready to run our server and try out what we have created so far.</p><p>Run</p><pre>go run main.go</pre><p>We can try to access the end point described in our main.go file. It must return required values.</p><p>This is a very simple API example. By using this foundation, we can now continue creating more complex APIs.</p><p>Download repo <a href="https://github.com/ThinleyN/toDoGolang/tree/master/bookCRUD">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d55b0ace211e" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/crud-api-using-go-d55b0ace211e">CRUD API using GO</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding GO Routine and Channel]]></title>
            <link>https://articles.wesionary.team/understanding-go-routine-and-channel-b09d7d60e575?source=rss-1f903ec5531a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b09d7d60e575</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[goroutines]]></category>
            <category><![CDATA[go]]></category>
            <dc:creator><![CDATA[Thinley Norbu]]></dc:creator>
            <pubDate>Tue, 07 Jul 2020 12:47:46 GMT</pubDate>
            <atom:updated>2020-07-07T12:47:46.610Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>What is a GO routine?</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/553/1*z93yvlIYe2kMObUaPxYTCg.png" /><figcaption>Go routine for concurrency.</figcaption></figure><p>GO routine is a function or method which is capable of being executed simultaneously with relation to any other GO routine present in a program. The main difference between a normal function and a go routine is that the main program doesn’t wait for the GO routine to be finished which is not true in case of normal function. Go routine is a non-blocking function which starts executing on it’s own once called.</p><p>GO routine can be understood as a light weight thread. The cost for creating and running GO routine is low so there can be thousands of GO routines running simultaneously in a GO application. Each GO routine is only some kb stack size.</p><p>All the program contains at least one Go routine, it is the Main Go Routine. One thing that is to be known is that, all the other GO routines are actually running inside this main GO routine. So if this main GO routine is terminated then all the other GO routines also gets terminated.</p><blockquote>A Go routine is a lightweight thread managed by the Go runtime.</blockquote><p><strong>How to create a GO routine?</strong></p><p>Creating GO routine is simple. All we have to do this add a ‘go’ as a prefix of a function or a method call.</p><p>A example to demonstrate the use of GO routine.</p><pre>package main<br><br>import (  <br>    &quot;fmt&quot;<br>)<br><br>func hello() {  <br>    fmt.Println(&quot;Hello world goroutine&quot;)<br><br>func main() {  <br>    go hello()<br>    fmt.Println(&quot;main function&quot;)<br>}</pre><p>If we run this program, there is a surprising result. We won’t get the ‘Hello world goroutine’ in our console. We will get the ‘main function’ message only. So why does this happen?</p><p>As I mentioned earlier, if the main GO routine is terminated, all the GO routine will also get terminated. And in our case, this is what’s happening. When a GO routine is started, unlike the normal function it doesn’t wait for it to return. Instead, GO routine is returned immediately and the control is passed to the following line.</p><p>We can fix it by using Sleep method provided by time. Edit the file such as:</p><pre>package main<br><br>import (  <br>    &quot;fmt&quot;<br>    &quot;time&quot;<br>)<br><br>func hello() {  <br>    fmt.Println(&quot;Hello world goroutine&quot;)<br><br>func main() {  <br>    go hello()<br>    time.Sleep(1 * time.Second)<br>    fmt.Println(&quot;main function&quot;)<br>}</pre><p>Upon executing this file, we successfully get the “Hello world goroutine”.</p><p>But this seems like a hacky way to achieve the results, doesn’t it?</p><p>So what do we do now?</p><blockquote>Channels can be used to block the main Goroutine until all other Goroutines finish their execution.</blockquote><p>This is where we need Channels.</p><p><strong>What is Channel?</strong></p><p>Channels can be thought as a medium using which GO routines can communicate. Data can be sent or received by using channels. Receiving or sending of data in channel is blocking by nature. Each channel has type defined to it. Data type other than the defined ones cannot be written or read.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*jwKsVn91q2TNoyuF6hc3mA.jpeg" /><figcaption>Receiving or sending of data in channel is blocking by nature.</figcaption></figure><p><strong>Defining Channel.</strong></p><p>Syntax:</p><pre>var Channel_name chan Type</pre><p>We can create channel by using make() as a shorthand declaration.</p><pre>channel_name:= make(chan Type)</pre><p><strong>Reading and Writing to channel.</strong></p><pre>a =: make(chan bool) // Define channel a of type boolean.<br>data := &lt;- a // read from channel a  <br>a &lt;- data // write to channel a</pre><p>Basically, the direction of the arrow with respect to the channel specifies whether the data is sent or received.</p><p>In second line, variable is being declared with the data received from the channel ‘a’. In third line, data is being written to the channel ‘a’.</p><p>So now let’s create a example to demonstrate the use of channel. Create a go file and put the following contents to it.</p><pre>package main</pre><pre>import (<br>  &quot;fmt&quot;<br>)</pre><pre>func hello(done chan bool) {<br>   fmt.Println(&quot;Hello world goroutine&quot;)<br>   done &lt;- true<br>}</pre><pre>func receive(receive bool, anotherDone chan bool) {<br>  if receive == true {<br>    fmt.Println(&quot;from receive&quot;)<br>    anotherDone &lt;- true<br>  }<br>}</pre><pre>func main() {<br>  done := make(chan bool)<br>  anotherDone := make(chan bool)<br>  go hello(done)<br>  toSend := &lt;-done<br>  go receive(toSend, anotherDone)<br>  &lt;-anotherDone<br>  fmt.Println(&quot;main function&quot;)<br>}</pre><p>It is quite a naive example but let’s get into details of it. Here, we have defined two go routines. They are hello and receive. And similarly, we defined two channels viz. done and anotherDone. They both are of type boolean. As we can see that after calling hello routine, we are trying to read done channel’s data into toSend variable. This blocks the control flow which causes the main GO routine to hold until some data is received. Then we are passing the toSend variable into receive routine, where we check it for being true and write true to anotherDone channel. After calling receive, we are reading data from anotherDone but not storing in any variable.</p><p>Upon executing, we can now get the desired results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*eP-eWNT23nv1iqRuu_jajA.png" /></figure><p>One thing to take into consideration while using Channel is possibility of <strong>Deadlock</strong>. When a data is being sent to channel, it is expected that the data is received by some other GO routine. If it doesn’t happen, it causes <strong>Deadlock.</strong></p><p>Similarly, if data is being received by some GO routine then it is expected that some other GO routine should send data to that channel. If it doesn’t happen, it also caused <strong>Deadlock.</strong></p><p>So this was a walk-through of GO routine and channel with a basic example. I hope this article provided enough information to get started with routines and channel.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b09d7d60e575" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/understanding-go-routine-and-channel-b09d7d60e575">Understanding GO Routine and Channel</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mocking Axios in Jest]]></title>
            <link>https://articles.wesionary.team/mocking-axios-in-jest-c68933a1a4fb?source=rss-1f903ec5531a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c68933a1a4fb</guid>
            <category><![CDATA[axios]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[react-testing-library]]></category>
            <dc:creator><![CDATA[Thinley Norbu]]></dc:creator>
            <pubDate>Wed, 24 Jun 2020 18:03:31 GMT</pubDate>
            <atom:updated>2020-06-24T18:09:34.217Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Mock Axios calls using Jest &amp; React Testing Library.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Ua6cWOeiX7lmhFGZdA-dQ.jpeg" /><figcaption>Jest makes it easier to mock asynchronous requests.</figcaption></figure><p>If you are new to the Jest testing. I recommend you to go through my <a href="https://medium.com/wesionary-team/testing-react-component-a146a1551ec7">earlier article</a> on how to get started with Jest. It can help to get familiar with Jest testing.</p><p>While writing tests, it is important to understand that we must not call the real API. It can result in slow run time of tests as well as unwanted changes to data by testing. Mocking request gives us a lot of benefits. Such as:</p><ul><li>Quick and easy response.</li><li>Keeping separate test environment .</li><li>Eliminate chances of server being unavailable.</li><li>Tailor the data as required for the test.</li></ul><h4>So, how do we go about it?</h4><p>For the sake of simplicity, let’s create a fairly simple React component which makes an Axios request and fetches data. This component also lists the fetched data.</p><pre>import React, { useEffect, useState } from &#39;react&#39;;<br>import &#39;./App.css&#39;;<br>import axios from &#39;axios&#39;;</pre><pre>function App() {<br>const [ data, setData ] = useState([]);</pre><pre>useEffect(() =&gt; {<br> fetchData();<br>}, []);</pre><pre>const fetchData = async () =&gt; {<br>  const url = &#39;https://my-json-    server.typicode.com/typicode/demo/posts&#39;;<br>  const res = await axios.get(url);<br>  setData(res.data);<br>};</pre><pre>return (<br>&lt;div className=&quot;App&quot;&gt;<br>    &lt;ul style={{ textAlign: &#39;left&#39; }}&gt;<br>       {data.map((item, key) =&gt; {<br>          return &lt;li key={key}&gt;{item.title}&lt;/li&gt;;<br>       })}<br>    &lt;/ul&gt;<br>&lt;/div&gt;<br>);<br>}</pre><pre>export default App;</pre><p>We have used <em>my-json-server</em> to fake API here. It returns list of titles with ids. You can use <a href="https://my-json-server.typicode.com/"><strong>this website</strong></a> to get fake data. It may come handy in many cases.</p><p>Talking about this component, all it does is fetch the data from the API, update the state and render the data in list.</p><p>Now, let’s mock this Axios request in our test. Create a folder named __mocks__ under your src directory. Since we are mocking axios, create a file named axios.js inside the __mocks__ folder. It is a convention to write all the mock related files inside this __mocks__ folder. And since we have named the file axios.js, Jest identifies it automatically that it has to mock the package axios. Basically, we name the mock file same as the package we are intending to mock.</p><p>Moving on, we are here mocking the get method of axios. So, add this code snippet in the axios.js file.</p><pre>export default {<br>get: jest.fn().mockResolvedValue()<br>};</pre><p>We export a mocked version of axios here. We include a get method which is basically a jest function. After this, we can mock the resolved value returned from a get request in axios. Now, lets write a test for the React component.</p><pre>import React from &#39;react&#39;;<br>import { render, wait, cleanup } from &#39;@testing-library/react&#39;;<br>import App from &#39;./App&#39;;<br>import mockedAxios from &#39;axios&#39;;</pre><pre>afterEach(cleanup);</pre><pre>test(&#39;mocking axios request&#39;, async () =&gt; {<br>const data = {<br>data: [<br> {<br>   id: 1,<br>   title: &#39;title 1&#39;<br> },<br> {<br>   id: 2,<br>   title: &#39;title 2&#39;<br> },<br> {<br>   id: 3,<br>   title: &#39;mocked title&#39;<br>}]<br>};</pre><pre>mockedAxios.get.mockResolvedValueOnce(data);<br>const { getByText } = render(&lt;App /&gt;);<br>await wait(() =&gt; {<br>  expect(getByText(&#39;mocked title&#39;));<br>});<br>});</pre><p>As we can see, we import axios naming it mockedAxios. This imports the mocked version of axios from our __mocks__ folder. Now, we can tailor the data for the test just how we please. We here are mocking the get method of axios with the help of mockResolvedValueOnce method. It helps to resolve different values over multiple async calls. Here, we passed the <em>data</em> variable into mockResolvedValueOnce so the response of the get request on axios will return this <em>data</em> variable.</p><p>Then, we use wait method from @testing-library/react to wait for the API call to finish. We assert the mocked request went successful by expecting the ‘mocked title’ text(returned from the mocked value) in the container. Running this test will show that the ‘mocked title’ was found in the render which hence proves that we have successfully mocked the axios request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*B5eIh9Q2H03mOlQ29E7qTw.png" /><figcaption>Passes the test</figcaption></figure><p>So, this was a walk-through on how to mock the Axios request in Jest. You can definitely give a try to mock other methods of Axios such as POST, DELETE, PUT and etc. All you have to do is add more methods to your mocked version of axios inside your mock file and you are good to go.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c68933a1a4fb" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/mocking-axios-in-jest-c68933a1a4fb">Mocking Axios in Jest</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Testing Library Vs. Enzyme]]></title>
            <link>https://articles.wesionary.team/react-testing-library-vs-enzyme-afd29db380ac?source=rss-1f903ec5531a------2</link>
            <guid isPermaLink="false">https://medium.com/p/afd29db380ac</guid>
            <category><![CDATA[jest]]></category>
            <category><![CDATA[enzyme]]></category>
            <category><![CDATA[react-testing-library]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Thinley Norbu]]></dc:creator>
            <pubDate>Tue, 16 Jun 2020 03:02:33 GMT</pubDate>
            <atom:updated>2020-06-16T06:35:17.311Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Understanding React Testing.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ty88dp5u945xbu4msXpdTg.png" /><figcaption>Comparison between React Testing Library and Enzyme.</figcaption></figure><p>While writing tests cases for React, it can be quite confusing to decide which library to be used. In today’s time, it can be overwhelming to choose between so many available options. React Testing Library and Enzyme has proved to be one of the go-to option while writing tests for React. So in this article, we will be discussing about the differences between these two libraries.</p><p><strong>Enzyme:</strong></p><p>Enzyme is a popular testing library from Airbnb. It provides us with mechanism to test the implementation details of a React component. It can provide us with access to the state, props and children components of a React component while writing test. We use such information about the React component to run our assertions.</p><blockquote>Enzyme is a JavaScript Testing utility for React that makes it easier to test your React Components’ output. You can also manipulate, traverse, and in some ways simulate runtime given the output.</blockquote><p><strong>React Testing Library:</strong></p><p>React Testing Library is a light-weight testing library. It provides light utility functions on top of react-dom and react-dom/test-utils, in a way that encourages good testing practices.</p><blockquote>The more your tests resemble the way your software is used, the more confidence they can give you.</blockquote><p>Unlike Enzyme, it is not focused on the implementation details of the component. React Testing Library uses the render logic to run our assertions. The testing is done from user’s perspective. That’s why this library doesn’t provide us the access to the component’s properties such as it’s state and props. The assertions are made from the DOM elements which can be accessed by the utility provided by React Testing Library.</p><h3><strong>Major differences between Enzyme and React Testing Library</strong></h3><h4>1. Conceptual difference :</h4><p>In Enzyme, we are testing the component using the state and props of the component. This generally means that the tests are brittle. Lets take an example. Let’s say we have already written tests for a component and it is running fine. But what if someone changes the variable name of a state or a props in the component, then even if the functionality of the component hasn’t changed, our test fails. This kind of behavior demonstrate the brittleness of the test.</p><p>Whereas in React Testing Library, we test the component from user’s perspective. Let’s say we want to test a drop down component, we won’t test the component according to it’s state and props. Instead we use the DOM elements to test it, just how the user interacts with it. One guiding principle we can find related to React Testing Library is:</p><blockquote>If it relates to rendering components, it deals with DOM nodes rather than component instances, nor should it encourage dealing with component instances.</blockquote><h4>2. Shallow or deep rendering</h4><p>In React Testing Library, we test using the DOM. So, there is no shallow or deep rendering. But in Enzyme, shallow or deep rendering is present.</p><p>Shallow rendering enables us to ensure that we are not asserting our tests based on the behavior of any child’s component of the component we are testing.</p><p>Enzyme provides us with full rendering of the DOM elements too. It can be useful in cases where we want to test components wrapped inside a higher order component.</p><h4><strong>3. Way of operation</strong></h4><p>Enzyme lets us test the component according to the state, props and other internals of the component but it also lets us access the DOM of the component. So using enzyme, we are not bound to test the internals but we can test the DOM too.</p><p>Whereas in React Testing Library, it enforces us to test the component according to the DOM and doesn’t provide us any means to gain access to the internals of the component.</p><h4>4. Setup</h4><p>In Enzyme, we need to setup the adapter for it to work with React. There are other adapters available which it make it possible to work with Enzyme with other libraries.</p><pre>import Enzyme from &#39;enzyme&#39;;<br>import Adapter from &#39;enzyme-adapter-react-16&#39;;<br><br>Enzyme.configure({ adapter: new Adapter() });</pre><p>We need to setup the adapter for each and every tests, so it is a good practice to setup the adapter in a file and export it and use it else where.</p><p>But in React Testing Library, we can directly install it and we are good to go. <a href="https://medium.com/wesionary-team/testing-react-component-a146a1551ec7">You can look at the steps to write tests in React Testing Library from my previous article.</a></p><h4>Conclusion</h4><p>There is no hard and fast rules on how to test a component. Sometimes, we may need to test the internals of the component when just testing the DOM from user’s perspective may not make sense. In such use cases, it is definitely wise to use Enzyme to do so. And sometimes, it may be tempting to test each and everything when just testing the DOM is enough. In such use cases, React Testing Library is a perfect choice. So, depending on the use cases, we can choose between these two libraries. In my view, it is totally fine to have both of them installed and use it according to their individual use cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=afd29db380ac" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/react-testing-library-vs-enzyme-afd29db380ac">React Testing Library Vs. Enzyme</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Terraform.]]></title>
            <link>https://articles.wesionary.team/introduction-to-terraform-40fec84aebc5?source=rss-1f903ec5531a------2</link>
            <guid isPermaLink="false">https://medium.com/p/40fec84aebc5</guid>
            <category><![CDATA[infrastructure-as-code]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <dc:creator><![CDATA[Thinley Norbu]]></dc:creator>
            <pubDate>Mon, 04 May 2020 12:36:33 GMT</pubDate>
            <atom:updated>2020-05-04T12:36:33.626Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Getting started with Infrastructure as Code with Terraform.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2ci8beRICk0Q3k8cQ9fyQw.png" /><figcaption>Automating provisioning of resources.</figcaption></figure><p>In this article, we are going to discuss about a IaC tool known as Terraform. If you need descriptions about the overall concept of Infrastructure as Code then you can check out my article <a href="https://medium.com/wesionary-team/infrastructure-as-code-8f9a4bf9b5c3">here</a>.</p><p>So for a quick overview of Terraform, we are going to create a simple VM using this tool. So without any further ado, lets get into it.</p><p><strong>What is Terraform?</strong></p><blockquote>Terraform is a tool for provisioning infrastructure(or managing Infrastructure as Code). It supports multiple providers(E.g: AWS, Google Cloud, Azure, OpenStack, etc).</blockquote><p>You can follow <a href="https://learn.hashicorp.com/terraform/getting-started/install.html">this link </a>to get information about the installation process of the Terraform. After the successful installation of Terraform, lets start writing our first configuration.</p><p>Make a file named main.tf in your main project directory. Terraform supports lot of providers such as AWS, Google Cloud Platform, Azure and many more. We are going to use Google Cloud Platform for this article. So in your main.tf file, define your provider such as:</p><pre>provider &quot;google&quot; {<br>     project    =&quot;[YOUR_PROJECT]&quot;<br>     credentials = &quot;[YOUR_SERVICEACCOUNT.JSON]&quot;<br>}</pre><p>Make sure to replace [YOUR_PROJECT] with the name of your project and [YOUR_SERVICEACCOUNT.JSON] with your service account’s filename which you can download from GCP console. Check out this <a href="https://cloud.google.com/iam/docs/creating-managing-service-account-keys">link</a> to get information on how to get your service account file.</p><p>So we just defined our provider information in Terraform. Before writing configuration for a VM, lets get a brief information on variables that we can use while writing configuration.</p><p><strong>Variables</strong></p><p>We can define variables similar to any other programming language to eliminate the need of writing same values over and over again. To define variables in Terraform, we follow the following pattern.</p><pre>variable &quot;abc&quot; {<br>     default = &quot;some_value&quot;<br>}</pre><p>And, to access this variable, we can write something like:</p><pre>${var.abc}</pre><p>Basically we can access our defined variable by ‘var’. So we can refactor our previous code as:</p><pre>provider &quot;google&quot; {<br>   project    =&quot;${var.var_project}&quot;<br>  credentials = &quot;${file(var.var_credential)}&quot;<br>}</pre><p>where we have put our project name in ‘var_project’ and our credentials in ‘var_credential’.</p><p>So back to writing configuration, lets define a VM.</p><pre>resource &quot;google_compute_instance&quot; &quot;default&quot; {<br>  name         <strong>=</strong> &quot;test&quot;<br>  machine_type <strong>=</strong> &quot;n1-standard-1&quot;<br>  zone         <strong>=</strong> &quot;us-central1-a&quot;<br><br>  tags <strong>=</strong> [&quot;foo&quot;, &quot;bar&quot;]<br><br>  boot_disk {<br>    initialize_params {<br>      image <strong>=</strong> &quot;debian-cloud/debian-9&quot;<br>    }<br>  }<br><br>  // Local SSD disk<br>  scratch_disk {<br>    interface <strong>=</strong> &quot;SCSI&quot;<br>  }<br><br>  network_interface {<br>    network <strong>=</strong> &quot;default&quot;<br><br>    access_config {<br>      // Ephemeral IP<br>    }<br>  }<br><br>  metadata <strong>=</strong> {<br>    foo <strong>=</strong> &quot;bar&quot;<br>  }<br><br>  metadata_startup_script <strong>=</strong> &quot;echo hi &gt; /test.txt&quot;<br><br>}</pre><p>So basically, what we did here is that we define a resourcegoogle_compute_instance which gives us a Virtual Machine instance. The machine type for this VM will be n1-standard-1 and we will install debian-cloud/debian-9 as the boot disk image. We can install Ubuntu, Windows as per our needs.</p><p>So to apply this configuration, we need to first hit the following command.</p><pre>terraform init</pre><p>This command will install all the dependencies required for our provider. It will also check whether the configuration for our backend is changed. We will discuss about backend and state files in a while.</p><p>So after hitting that command, we can check whether the written configurations will result into our desired needs. To check it, we can run:</p><pre>terraform plan</pre><p>This command will show us all the changes that the configuration will apply. After verifying whether it is needed or not. We can finally run:</p><pre>terraform apply</pre><p>This will apply all of our changes made in configuration to GCP. You can go to Google Cloud Platform’s console and see that a virtual machine with the mentioned configurations is created.</p><p>So after applying these changes, you can notice in your working directory that a file named “terraform.tfstate” is created. This is an important file which stores the state of our configurations so that when we apply our configuration the next time, it will check on this file and make changes only to those resources whose configuration is changed. We must not edit this file manually, terraform will do it for us automatically.</p><p>It is fine to store this file locally if you are working on your own. But for most of the cases, we work in team. And, while working in a team, storing this file locally is generally a bad idea. Because this means, there will be multiple state files that are responsible for the changes to the resources which can potentially break our overall working of resources. So, to manage the state file, we have to write a backend configuration file which will tell Terraform to store this state in a shared location such as a Storage Bucket.</p><p>By having a shared location for the state file, we solve problems like conflicting state and multiple access to state file at a time. In this article, we use a Storage Bucket to store and share state file with the team. Make a file named ‘backend.tf’ and paste the following configuration.</p><pre>terraform {<br>backend &quot;gcs&quot; {<br>bucket  = &quot;name_of_your_bucket&quot;<br>prefix  = &quot;prod&quot;<br>credentials = &quot;path_to_service_account.json&quot;<br>}<br>}</pre><p>We use a backend resource ‘gcs’ for Google Cloud Platform. Terraform provides us alot of options for this such as :</p><ul><li>S3</li><li>cos</li><li>swift</li><li>consul</li><li>http</li><li>pg</li><li>and many more.</li></ul><p>So after writing configuration for our backend, we run</p><pre>terraform init</pre><p>It will ask us if we want to copy our currently existing state file to our bucket for which you want to do as you please but for most of the cases, we want to keep our existing state so we hit yes. By doing so, we are now storing and managing our state file remotely so there is no conflict in the access of this state file by multiple developer in a team.</p><p>So to wrap it all up, we wrote configuration for provisioning a simple VM and to manage the state file remotely. There is still so much we can do with Terraform. It is a great tool and is widely used. You can dive in more about the concepts of Terraform from their docs. I hope I gave a brief overview of how the Terraform works. Happy learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=40fec84aebc5" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/introduction-to-terraform-40fec84aebc5">Introduction to Terraform.</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Infrastructure as Code.]]></title>
            <link>https://articles.wesionary.team/infrastructure-as-code-8f9a4bf9b5c3?source=rss-1f903ec5531a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f9a4bf9b5c3</guid>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[deployment-manager]]></category>
            <category><![CDATA[gcp]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[Thinley Norbu]]></dc:creator>
            <pubDate>Wed, 22 Apr 2020 04:34:51 GMT</pubDate>
            <atom:updated>2020-04-22T04:34:51.340Z</atom:updated>
            <content:encoded><![CDATA[<p>Brief Intro on IaC and quick start to Deployment Manager</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*NkPYnHki4pHPNCT0hsFfzg.png" /><figcaption>Infrastructure as Code.</figcaption></figure><p>Infrastructure as Code (IaC) is a type of setup which manages infrastructure such as networks, virtual machines, load balancers etc. automatically rather than having to manage them manually. Infrastructures are now in descriptive model in code. The principle that same code generates the same output applies true for IaC. IaC model will always generate the same environment every time it is applied. This ensures us the the application will be consistent throughout various environment which in return saves lot of time and effort.</p><h4><em>Environment drift</em></h4><p>In the release pipeline, developers are bound to run into problems caused by Environment drift. Same program that was running fine stops behaving consistent due to change in environment. Without IaC, developers must be able to maintain each deployment environment manually which can get tremendously tedious overtime. With IaC, developers can store the environment description in code format such as JSON. So, when they need to change the description of the environment, they simply change the source code. Hence, it enables the developers to test the program in production like environment early in development cycle. And, since the infrastructures are defined in code, keeping the track of different version of environment gets easier.</p><h4>Tools for Infrastructure as Code</h4><p>Provisioning of infrastructures are automated by IaC tools. These tools can automate deployments with provisioned infrastructures and help monitor previously provisioned infrastructure. Examples of Iac tools are listed below:</p><ul><li>Terraform</li><li>Ansible</li><li>Chef</li><li>Puppet</li><li>Deployment Manager</li><li>AWS CloudFormation and many more.</li></ul><p>Here in this article, we will use <strong>Deployment Manager</strong> for Google Cloud Platform to demonstrate creation and deletion of virtual machine.</p><p>Before we begin, we have to create a project in GCP. If you do not know how to create project in GCP, <a href="https://cloud.google.com/resource-manager/docs/creating-managing-projects">this link</a> may help. One thing to make sure after you create the project is to enable the billing for your Google cloud project. After that, you have to install gcloud command-line tool. To install gcloud command-line tool, you can follow <a href="https://cloud.google.com/sdk/docs/quickstarts">this link</a>.</p><p>After successful installation of gcloud command-line tool, you have to configure gcloud command tool to use your project. For that, you can use the following command.</p><pre>gcloud config set project [MY_PROJECT]</pre><p>Replace [MY_PROJECT] with your project id. Then, you are good to go.</p><p>There is a <a href="https://github.com/GoogleCloudPlatform/deploymentmanager-samples/tree/master/examples/v2">GitHub repository</a> which provides us with the samples for deployments. We can find various sorts of samples to help us get up and running with simple deployments. And in this article, we are also using a sample provided by that <a href="https://github.com/GoogleCloudPlatform/deploymentmanager-samples/tree/master/examples/v2">GitHub repository</a>.</p><p>Copy the following file to your favorite text editor and save it with name vm.yaml. This is a configuration file that contains our deployment configuration.</p><pre># Copyright 2016 Google Inc. All rights reserved.<br>#<br># Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);<br># you may not use this file except in compliance with the License.<br># You may obtain a copy of the License at<br>#<br>#     http://www.apache.org/licenses/LICENSE-2.0<br>#<br># Unless required by applicable law or agreed to in writing, software<br># distributed under the License is distributed on an &quot;AS IS&quot; BASIS,<br># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.<br># See the License for the specific language governing permissions and<br># limitations under the License.<br><br><br># Put all your resources under `resources:`. For each resource, you need:<br># - The type of resource. In this example, the type is a Compute VM instance.<br># - An internal name for the resource.<br># - The properties for the resource. In this example, for VM instances, you add<br>#   the machine type, a boot disk, network information, and so on.<br>#<br># For a list of supported resources,<br># see https://cloud.google.com/deployment-manager/docs/configuration/supported-resource-types.<br>resources:<br>- type: compute.v1.instance<br>  name: quickstart-deployment-vm<br>  properties:<br>    # The properties of the resource depend on the type of resource. For a list<br>    # of properties, see the API reference for the resource.<br>    zone: us-central1-f<br>    # Replace [MY_PROJECT] with your project ID<br>    machineType: https://www.googleapis.com/compute/v1/projects/[MY_PROJECT]/zones/us-central1-f/machineTypes/f1-micro<br>    disks:<br>    - deviceName: boot<br>      type: PERSISTENT<br>      boot: true<br>      autoDelete: true<br>      initializeParams:<br>        # See a full list of image families at https://cloud.google.com/compute/docs/images#os-compute-support<br>        # The format of the sourceImage URL is: https://www.googleapis.com/compute/v1/projects/[IMAGE_PROJECT]/global/images/family/[FAMILY_NAME]<br>        sourceImage: https://www.googleapis.com/compute/v1/projects/debian-cloud/global/images/family/debian-9<br>    # Replace [MY_PROJECT] with your project ID<br>    networkInterfaces:<br>    - network: https://www.googleapis.com/compute/v1/projects/[MY_PROJECT]/global/networks/default<br>      # Access Config required to give the instance a public IP address<br>      accessConfigs:<br>      - name: External NAT<br>        type: ONE_TO_ONE_NAT</pre><p>Remember to replace all the [MY_PROJECT] with your project id.</p><p>This configuration basically provides us basic configuration of a virtual machine instance with :</p><ul><li>Machine type: f1-micro</li><li>Image family: debian-9</li><li>Zone: us-central1-f</li><li>Root persistent disk: boot</li><li>A randomly assigned external IP address</li></ul><p>Now, we are ready to deploy this. Run the following command.</p><p>gcloud deployment-manager deployments create quickstart-deployment --config vm.yaml</p><p>After the successful deployment, you may get message which looks similar to the following.</p><pre>Create operation operation-1432319707382-516afeb5d00f1-b864f0e7-b7103978 completed successfully.<br>NAME                    TYPE                STATE      ERRORS<br>quickstart-deployment   compute.v1.instance COMPLETED  -</pre><p>After this, you can check on your deployed resources. Hit the following command.</p><pre>gcloud deployment-manager deployments describe quickstart-deployment</pre><h4>Now for deleting the resources we just deployed.</h4><p>Simply, hit the following command.</p><pre>gcloud deployment-manager deployments delete quickstart-deployment</pre><p>You may be prompted for the confirmation. You can hit y on the prompt. We just deleted our resources and deployment permanently.</p><p>So, this was a basic walk-through of Deployment Manager. I hope this article helped you to understand a basic concept of Infrastructure as Code. You can read the <a href="https://cloud.google.com/deployment-manager/docs/step-by-step-guide">official docs</a> for further information on best practices.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f9a4bf9b5c3" width="1" height="1" alt=""><hr><p><a href="https://articles.wesionary.team/infrastructure-as-code-8f9a4bf9b5c3">Infrastructure as Code.</a> was originally published in <a href="https://articles.wesionary.team/">wesionaryTEAM</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>