<?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 Viacheslav Volkov on Medium]]></title>
        <description><![CDATA[Stories by Viacheslav Volkov on Medium]]></description>
        <link>https://medium.com/@vexell?source=rss-d24150e7ad77------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*K77aKitSkjBpeCXOal3SsA.png</url>
            <title>Stories by Viacheslav Volkov on Medium</title>
            <link>https://medium.com/@vexell?source=rss-d24150e7ad77------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:52:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vexell/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 metrics from node.js applications in PM2 with exporting to Prometheus]]></title>
            <link>https://vexell.medium.com/how-to-collect-metrics-from-node-js-applications-in-pm2-with-exporting-to-prometheus-4b99c71a34b3?source=rss-d24150e7ad77------2</link>
            <guid isPermaLink="false">https://medium.com/p/4b99c71a34b3</guid>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Viacheslav Volkov]]></dc:creator>
            <pubDate>Mon, 12 Feb 2024 21:21:44 GMT</pubDate>
            <atom:updated>2024-02-24T07:59:48.414Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ROWp75psGR98Bxo1rjHWlg.png" /></figure><p>It’s no secret that for stable and reliable working of node.js applications, it’s necessary to monitor their performance and get useful insights from their metrics. It means being able to collect information about app state before issues appear to preventing failures.</p><p>In this article, I’d like to present a method for collecting metrics node.js applications from running in PM2 and exporting this data to Prometheus.</p><p>When you simply start a node.js application using the node command or through PM2 with the pm2 start app.js command the new application is launched as a single instance. Collecting and exporting any metrics in this case would not be difficult. To do this, you can install the <a href="https://www.npmjs.com/package/prom-client">prom-client</a> package and add the metrics you need, for example, the number of requests to our application.</p><pre>import client from &#39;prom-client&#39;;<br>import { createServer } from &#39;http&#39;;<br><br>const registry = new client.Registry();<br>const PREFIX = `nodejs_app_`;<br><br>export const metricRequestsTotal = new client.Counter({<br>    name: `${PREFIX}request_counter`,<br>    help: &#39;Show total request count&#39;,<br>    registers: [registry],<br>});<br><br>// Start your application<br>// ...<br>nodejsapp.get(&#39;/*&#39;, async (req, res) =&gt; {<br>    metricRequestsTotal.inc();<br>});<br><br>// Start Prom server for export metrics<br>const promServer = createServer(async (req, res) =&gt; {<br>    res.setHeader(&#39;Content-Type&#39;, registry.contentType);<br>    res.end(await registry.metrics());<br>    return;<br>});<br><br>promServer.listen(9100, () =&gt;<br>    console.log(&#39;Prom server started&#39;)<br>);</pre><p>In this example, when your application is launched, it also stars metric exporting on an additional port 9100. Of course you can use a separate URL with the main application, but it shouldn’t be public for users.</p><p>This approach will work as long as you don’t need to run multiple instances of the application in cluster mode. For collecting metrics in cluster mode, prom-client provides <a href="https://github.com/siimon/prom-client/blob/master/example/cluster.js">a good example</a> with metric aggregation. But what if you’re running the application through the process manager PM2, where you don’t have access to the running cluster?</p><p>In one of <a href="https://vexell.medium.com/pm2-module-to-monitoring-node-js-application-with-export-to-prometheus-and-grafana-43d4b958c563">my previous articles</a>, I talked about the <a href="https://www.npmjs.com/package/pm2-prom-module">pm2-prom-module</a>, which allows collecting overall statistics for PM2 applications but couldn’t collect internal statistics from each application. However, starting from version 2.0, such limitation is no longer present, and all statistics from PM2 and within the application are provided through a single module.</p><p>To communicate between node.js application and <a href="https://www.npmjs.com/package/pm2-prom-module">pm2-prom-module</a>, you need to install the npm package <a href="https://www.npmjs.com/package/pm2-prom-module-client">pm2-prom-module-client</a> in your application. As a result, the example above will look like this:</p><pre>import client from &#39;prom-client&#39;;<br>import { initMetrics } from &#39;pm2-prom-module-client&#39;;<br><br>const registry = new client.Registry();<br>const PREFIX = `nodejs_app_`;<br><br>const metricRequestCounter = new client.Counter({<br>    name: `${PREFIX}request_counter`,<br>    help: &#39;Show total request count&#39;,<br>    registers: [registry],<br>});<br><br>// Register your `registry` to send data to pm2-prom-module<br>initMetrics(registry);<br><br>// ...<br>nodejsapp.get(&#39;/*&#39;, async (req, res) =&gt; {<br>    // ...<br>    metricRequestCounter?.inc();<br>    // ...<br>});</pre><p>Now pm2-prom-module will provide PM2 statistics and also internal statistics from your applications.</p><pre>/// Common metrics from PM2<br><br># HELP pm2_free_memory Show available host free memory<br># TYPE pm2_free_memory gauge<br>pm2_free_memory{serviceName=&quot;my-app&quot;} 377147392<br><br># HELP pm2_cpu_count Show available CPUs count<br># TYPE pm2_cpu_count gauge<br>pm2_cpu_count{serviceName=&quot;my-app&quot;} 4<br><br># HELP pm2_available_apps Show available apps to monitor<br># TYPE pm2_available_apps gauge<br>pm2_available_apps{serviceName=&quot;my-app&quot;} 2<br><br>/// Apps metrics<br># HELP nodejs_app_request_counter Show total request count<br># TYPE nodejs_app_request_counter counter<br>nodejs_app_request_counter{app=&quot;app1&quot;,serviceName=&quot;my-app&quot;} 10<br>nodejs_app_request_counter{app=&quot;app2&quot;,serviceName=&quot;my-app&quot;} 17</pre><p>By default, all statistics are aggregated across all running instances in every app, but if you want detailed statistics for each instance, you can enable this through the module’s configuration parameter:</p><pre>pm2 set pm2-prom-module:aggregate_app_metrics false</pre><p>This module, unlike some others, allows collecting metrics separately for each application, and they do not intersect.</p><p>Overall, the statistics provided by PM2 are enough for basic application monitoring. However, in our case, for example, we wanted more detailed information about page rendering time or loading of certain data blocks. For such purposes, we used Histogram metric type.</p><pre>// ...<br>export const metricRequestTime = new client.Histogram({<br>    name: &#39;nodejs_app_page_execute&#39;,<br>    help: &#39;Time to processing request&#39;,<br>    registers: [registry],<br>    buckets: [0.1, 0.2, 0.3, 0.5, 0.7, 1, 2, 3, 5],<br>    labelNames: [&#39;code&#39;, &#39;page&#39;],<br>});<br><br>// ...<br>const endMetricRequestTime = metricRequestTime.startTimer();<br>// ...<br>endMetricRequestTime({ code: 200, page: &#39;Homepage });</pre><p>In example above, we use 2 additional parameters: code(HTTP response code) and page(page identifier), which provide detailed statistics. For example, you can build such graphs in <a href="https://grafana.com/">Grafana</a>:</p><ul><li>Most frequently pages sum(rate(nodejs_app_page_execute_count{serviceName=”$serviceName”,code=”200&quot;}[5m])) by (page)</li><li>The number of HTTP (response codes) success or errors. sum(rate(nodejs_app_page_execute_count{serviceName=”$serviceName”}[5m])) by (code)</li><li>The page load time specifying, for example, the 99th percentile. histogram_quantile(0.99, sum(rate(nodejs_app_page_execute_bucket{serviceName=”$serviceName”, code=”200&quot;}[1m])) by (page, le))</li><li>And many other graphs for each individual page.</li></ul><p>By the way, I don’t recommend using the URL of the page as the value for page — it will significantly increase memory usage and the size of the response in Prometheus, and mess in the graphs. It’s better to use page identifier.</p><p>So, to summarize, we have a single point for collecting and serving statistics for all applications running in PM2, and a monitoring system built on Prometheus with functional dashboards in Grafana.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fIylPvXmjUqDrwrB_MNh5w.png" /><figcaption>Grafana charts from pm2-prom-module data</figcaption></figure><p>If you like <strong>pm2-prom-module</strong>, I would appreciate if you could <a href="https://github.com/VeXell/pm2-prom-module">star it on Github</a>. Thanks for reading.</p><p><strong>UPD: </strong><a href="https://vexell.ru/content/files/2024/02/grafana2.json">Link to my grafana dashboard</a> with pages and codes</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4b99c71a34b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick and simple way to generate images with node.js and Puppeteer]]></title>
            <link>https://vexell.medium.com/quick-and-simple-way-to-generate-images-with-node-js-and-puppeteer-1cdcb9209d5b?source=rss-d24150e7ad77------2</link>
            <guid isPermaLink="false">https://medium.com/p/1cdcb9209d5b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[image-processing]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Viacheslav Volkov]]></dc:creator>
            <pubDate>Sun, 26 Nov 2023 21:44:52 GMT</pubDate>
            <atom:updated>2023-11-26T22:10:47.074Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yQsIAvdPg5FJfuN7a2BU5Q.jpeg" /></figure><p>In our time, numerous websites create pages that users share in different social networks or messengers. Thanks to <a href="https://ogp.me/">Open Graph</a> tags, links can have a preview image that attracts even more attention, for example with og:image tag. But usually, many websites don’t put much effort into preview images and simply add one image to the majority of pages. If there is no image, parsers try to automatically find the first available suitable image and use it.</p><p>But imagine how great it would be to have a personalized image on the page, for example, when you have profiles of your users or events in which they participate.</p><p>For example, take a look at the image below that we generate for sharing on social networks. It has a custom font, gradient, and even localization of text on the image into different languages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HHJW1CfPp9U6JItk.png" /></figure><p>In our project, the initial versions of images were generated using PHP, and for a while, this was sufficient because the images were quite simple and only contained the user’s picture. However, as soon as we added the user’s name, problems with text positioning immediately arose. For instance, here’s a small example of creating a simple image in PHP:</p><pre>&lt;?php<br><br>$width = 400;<br>$height = 200;<br>$image = imagecreatetruecolor($width, $height);<br><br>$backgroundColor = imagecolorallocate($image, 255, 255, 255);<br>imagefill($image, 0, 0, $backgroundColor);<br><br>$textColor = imagecolorallocate($image, 0, 0, 0);<br><br>// Load a custom TrueType font<br>$fontFile = &#39;path/to/your/font.ttf&#39;;<br><br>// Set the text to be displayed (considering localization)<br>$language = isset($_GET[&#39;lang&#39;]) ? $_GET[&#39;lang&#39;] : &#39;en&#39;;<br>$text = getLocalizedText($language);<br><br>$fontSize = 24;<br><br>// Set the position for the text to be displayed<br>$textbox = imagettfbbox($fontSize, 0, $fontFile, $text);<br>$textX = ($width - ($textbox[2] - $textbox[0])) / 2;<br>$textY = ($height - ($textbox[5] - $textbox[3])) / 2 + ($textbox[5] - $textbox[3]);<br><br>imagettftext($image, $fontSize, 0, $textX, $textY, $textColor, $fontFile, $text);<br><br>header(&quot;Content-Type: image/png&quot;);<br>imagepng($image);<br>imagedestroy($image);<br><br>function getLocalizedText($language) {<br>    switch ($language) {<br>        case &#39;en&#39;:<br>            return &#39;Hello, PHP!&#39;;<br>        case &#39;fr&#39;:<br>            return &#39;Bonjour, PHP!&#39;;<br>        default:<br>            return &#39;Hello, PHP!&#39;;<br>    }<br>}</pre><p>As seen from the example, if the text is too long or if you would like change its size, it may extend beyond the boundaries of the image. And if you add gradients, transparency, different fonts, emojis, the code will become complex and challenging to maintain.</p><p>The solution I would like to present allows you to reduce development time and simplifies the maintenance of such images. Moreover, it is flexible and easily scalable for other purposes.</p><p>So every web developers knows that HTML is the simplest and most convenient markup language. Along with CSS styles, you can create an interface that is flexible and takes into account the positioning of any elements on the page — images, text, tables, lists and etc.</p><p>Let’s have a look and on the example below. This is simple HTML page with many css styles like gradient in text, shadows, limiting text rows for long text and other.</p><pre>&lt;html&gt;<br>    &lt;head&gt;<br>        &lt;style&gt;<br>            html, body {<br>                margin: 0;<br>                padding: 0;<br>            }<br><br>            body {<br>                background-color: #0093E9;<br>                background-image: linear-gradient(160deg, #0093E9 0%, #80D0C7 100%);<br><br>                font-family: Helvetica, sans-serif;<br>                padding: 5%;<br>                text-align: center;<br>            }<br><br>            header {<br>                position: relative;<br>            }<br><br>            header .emoji {<br>                position: absolute;<br>                top: -10px;<br>                left: 0;<br>                transform: rotate(20deg);<br>                font-size: 3rem;<br>            }<br><br>            * {<br>                box-sizing: border-box;<br>            }<br><br>            h1 {<br>                text-transform: uppercase;<br>                font-size: 3rem;<br>                background: -webkit-linear-gradient(45deg, #85FFBD 0%, #FFFB7D 100%);<br>                -webkit-background-clip: text;<br>                -webkit-text-fill-color: transparent;<br>            }<br><br>            .wrapper {<br>                display: flex;<br>                padding-top: 2rem;<br>            }<br><br>            .avatar {<br>                display: flex;<br>                justify-content: center;<br>                align-items: center;<br>            }<br>            .avatar img {<br>                width: 140px;<br>                height: 140px;<br>                border-radius: 100px;<br>                border: 5px solid rgba(255,255,255, 0.5);<br>                box-shadow: 0 0 10px rgba(0,0,0,0.2);<br>                object-fit: cover;<br>            }<br><br>            .content {<br>                padding: 1rem 2rem;<br>            }<br><br>            .content .text {<br>                font-size: 1.5rem;<br>                display: -webkit-box;<br>                -webkit-line-clamp: 3; /* number of lines to show */<br>                        line-clamp: 3; <br>                -webkit-box-orient: vertical;<br>                overflow: hidden;<br>                color: rgba(255,255,255, 0.8);<br>            }<br>        &lt;/style&gt;<br>    &lt;/head&gt;<br>    &lt;body&gt;<br>        &lt;div&gt;<br>            &lt;header&gt;<br>                &lt;h1&gt;Hello, Javascript&lt;/h1&gt;<br>                &lt;div class=&quot;emoji&quot;&gt;🤖&lt;/div&gt;<br>            &lt;header&gt;<br>            &lt;div class=&quot;wrapper&quot;&gt;<br>                &lt;div class=&quot;avatar&quot;&gt;<br>                    &lt;img src=&quot;https://sun9-57.userapi.com/impg/O3egMIWPZjhcKSThZ2hn7ByaQmET8ySOq5e4ww/O_ngP3qqEd8.jpg?size=1178x1789&amp;quality=95&amp;sign=71fcbf49ffff80fad9f0ef39f598cf69&amp;type=album&quot; alt=&quot;&quot;/&gt;<br>                &lt;/div&gt;<br>                &lt;div class=&quot;content&quot;&gt;<br>                    &lt;div class=&quot;text&quot;&gt;&lt;strong&gt;Lorem Ipsum&lt;/strong&gt;  is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&#39;s standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.&lt;/div&gt;<br>                &lt;/div&gt;<br>            &lt;/div&gt;<br>        &lt;/div&gt;<br>    &lt;/body&gt;<br>&lt;/html&gt;</pre><p>What we need it is run a web server which can serve this HTML code and run node.js application with <a href="https://pptr.dev/">Puppeteer</a> library, which launches a headless version of Google Chrome, an then you can take a screenshot of the page and get the desired image.</p><p>Below is an example code that allows you to capture the content of a page with specified width, height and scale. It is crucial to handle exceptions and close the browser pages if something goes wrong; otherwise, it may lead to a memory leak.</p><pre>const browser = await puppeteer.launch({<br>    headless: true,<br>    ignoreHTTPSErrors: true,<br>    executablePath: browserPath,<br>    args: [&#39;--no-sandbox&#39;, &#39;--disable-setuid-sandbox&#39;],<br>    dumpio: true,<br>});<br><br>const page: Page = await browser.newPage();<br>await page.setJavaScriptEnabled(false);<br>await page.setViewport({<br>    width,<br>    height,<br>    deviceScaleFactor,<br>});<br><br>try {<br>    const result = await page.goto(url, {<br>        waitUntil: &#39;load&#39;,<br>    });<br><br>    if (result.status() !== 200) {<br>       page.close();<br>       throw new PageNotFoundError(`Incorrect status page ${result.status()}`);<br>    }<br>} catch (error) {<br>    page.close();<br>    throw new PageFetchError(error as string);<br>}<br><br>const data = await page.screenshot({<br>    type: imageType,<br>    quality: imageQuality,<br>    encoding: &#39;binary&#39;,<br>});<br><br>page.close();</pre><p>And finally as result you can get image like that which you can upload to you S3 storage and serve it to users. This is really simple to support and manage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XVo0rYg7zHE4p34qTNcgiQ.png" /><figcaption>Example of image generation with Puppeteer</figcaption></figure><p>In our case we create a small node.js application with <a href="https://pptr.dev/">Puppeteer</a> that has been packaged into a Docker container and run HTTP server inside to manage external requests. This application allows us to generate images with various format (like png, jpgor webp )for any page of the website.</p><p>So, the full logic of service for OG images generation might be:</p><ol><li>When your React app is rendering a page your generate special link in html meta tags og:image(with user id, required image size and extension) to nginx proxy.</li><li>The proxy server checks if the image is already in the S3 storage or not.</li><li>If the image exists, it is served; if not, a request is made to the node.js service, which generates the image, serves it, and asynchronously uploads it to S3.</li></ol><p>During the development we faced few minor problems such as:</p><ol><li>Chromium issues on a Ubuntu Docker container were resolved by directly downloading Google Chrome.</li><li>Font compatibility: one of our fonts broke Apple emoji font. We decided to replace it.</li></ol><p>Despite minor technical hurdles, the new node.js service significantly reduced image generation and support time compared to the previous PHP code. The solution allows us quickly update images, just change HTML code, simple to test it in the browser and use all power of CSS.</p><p>It’s a great way to achieve flexibility and scalability in generating images dynamically for any of your purposes (not only to generate <a href="https://ogp.me/">Open Graph</a> images).</p><p>If you have any more questions or if there’s anything else I can help you with, feel free to ask!</p><p>Here is example of docker container which we are using with all required libraries to work with images.</p><pre>FROM ubuntu:20.04<br><br>RUN ln -s /usr/share/zoneinfo/Etc/UTC /etc/localtime \<br> &amp;&amp; apt -y update \<br> &amp;&amp; apt -y install \<br>  git \<br>        openssh-server \<br>  gconf-service \<br>  libasound2 \<br>  libatk1.0-0 \<br>  libc6 \<br>  libcairo2 \<br>  libcups2 \<br>  libdbus-1-3 \<br>  libexpat1 \<br>  libfontconfig1 \<br>  libgcc1 \<br>  libgconf-2-4 \<br>  libgdk-pixbuf2.0-0 \<br>  libglib2.0-0 \<br>  libgtk-3-0 \<br>  libnspr4 \<br>  libpango-1.0-0 \<br>  libpangocairo-1.0-0 \<br>  libstdc++6 \<br>  libx11-6 \<br>  libx11-xcb1 \<br>  libxcb1 \<br>  libxcomposite1 \<br>  libxcursor1 \<br>  libxdamage1 \<br>  libxext6 \<br>  libxfixes3 \<br>  libxi6 \<br>  libxrandr2 \<br>  libxrender1 \<br>  libxss1 \<br>  libxtst6 \<br>  ca-certificates \<br>  fonts-liberation \<br>  libappindicator1 \<br>  libnss3 \<br>  lsb-release \<br>  xdg-utils \<br>  wget \<br>  curl \<br>  libnss3-dev \<br>  libgbm-dev \<br>  libu2f-udev \<br>  udev \<br> &amp;&amp; (curl -fsSL https://deb.nodesource.com/setup_14.x | bash -) \<br> &amp;&amp; apt-get install -y nodejs \<br> &amp;&amp; wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb \<br> &amp;&amp; apt install ./google-chrome-stable_current_amd64.deb \<br> &amp;&amp; rm -rf ./google-chrome-stable_current_amd64.deb \<br> &amp;&amp; apt-get clean \<br> &amp;&amp; rm -rf /var/cache/apt/lists<br><br># Add new fonts<br>COPY ./fonts /root/.fonts<br>RUN fc-cache -fv<br><br># Build and run your node.js app<br>...<br><br># Run node<br>CMD [&quot;node&quot;, &quot;app.js&quot;]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cdcb9209d5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PM2 module to monitoring node.js application with export to Prometheus and Grafana]]></title>
            <link>https://vexell.medium.com/pm2-module-to-monitoring-node-js-application-with-export-to-prometheus-and-grafana-43d4b958c563?source=rss-d24150e7ad77------2</link>
            <guid isPermaLink="false">https://medium.com/p/43d4b958c563</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[monitoring]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[prometheus]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Viacheslav Volkov]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 15:17:26 GMT</pubDate>
            <atom:updated>2023-11-17T15:17:26.519Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*URW4db9IXFHTa1aXW5-sFw.jpeg" /></figure><p>Monitoring a node.js application is one of the crucial stages in analyzing the quality and proper functioning of the application. It allows you to identify ongoing issues and quickly make decisions to fix them.</p><p>PM2 provides internal tools for monitoring all your applications, but in the free version, they are only accessible through the console command pm2 monit. Alternatively, PM2 offers a subscription service called PM2 Plus with additional functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*aQLLgvAhM28o5PWJ.png" /></figure><p>Unfortunately, neither of the mentioned methods are suitable for monitoring because you need to see not only current performance metrics but also changes in values over time (for example, the growth of memory usage within the application or the number of its reloads). Also payment subscription does not integrated into your overall monitoring system and located on separated service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*O0rwNP-iZ4_c7Yrr.png" /></figure><p>In most cases, applications use the combination of <a href="https://prometheus.io/">Prometheus</a> + <a href="https://grafana.com/">Grafana</a>, which allows collect data and display it in the form of graphs and also to set up alerts for changes in any metrics.</p><p>Unfortunately, PM2 does not provide a convenient and simple way to export data to Prometheus, so it was a motivation to implement my own module that would allow doing this. In addition, this module should be able to export additional metrics which my another module <a href="https://www.npmjs.com/package/pm2-autoscale">pm2-autoscale</a>, relies.</p><p>Finally <a href="https://www.npmjs.com/package/pm2-prom-module">pm2-prom-module</a> has been released and available for everyone. You can install it just with command pm2 install:</p><pre>pm2 install pm2-prom-module</pre><p>After installation monitoring service will be available on port 9988 and you can reach it by url<a href="http://localhost:9988/">http://localhost:9988/</a>.</p><p>Of course you can configure module and change port and service name, for example:</p><pre>pm2 set pm2-prom-module:port 10801<br>pm2 set pm2-prom-module:service_name MyApp</pre><p>Specifying the service_name is very convenient when installing the module across different projects, while using a single dashboard in Grafana. This allows you to create a dropdown list with all the services and quick switch between them.</p><p>This module collect all available metrics provided by PM2 and a few additional ones. The complete list looks something like this:</p><ol><li>Available free memory</li><li>Number of CPUs</li><li>Number of running applications</li><li>Number of instances for each application</li><li>Average memory usage per application</li><li>Total memory used for each application</li><li>Average CPU load for each application</li><li>Current CPU load for each application</li><li>Number of restarts for each application</li><li>Uptime for each application</li></ol><p>As well as all the statistics within PM2:</p><ol><li>Used Heap Size</li><li>Heap Usage</li><li>Heap Size</li><li>Event Loop Latency p95</li><li>Event Loop Latency</li><li>Active handles</li><li>Active requests</li><li>HTTP req/min</li><li>HTTP P95 Latency</li><li>HTTP Mean Latency</li></ol><p>Sometimes, PM2 returns very peculiar data that requires double-checking, such as Active requests or HTTP req/min (in reality, it seems more like req/sec).</p><p>Here is example of module output:</p><pre># HELP pm2_free_memory Show available host free memory<br># TYPE pm2_free_memory gauge<br>pm2_free_memory{serviceName=&quot;my-app&quot;} 377147392<br><br># HELP pm2_cpu_count Show available CPUs count<br># TYPE pm2_cpu_count gauge<br>pm2_cpu_count{serviceName=&quot;my-app&quot;} 4<br><br># HELP pm2_available_apps Show available apps to monitor<br># TYPE pm2_available_apps gauge<br>pm2_available_apps{serviceName=&quot;my-app&quot;} 1<br><br># HELP pm2_app_instances Show app instances count<br># TYPE pm2_app_instances gauge<br>pm2_app_instances{app=&quot;app&quot;,serviceName=&quot;my-app&quot;} 2<br><br># HELP pm2_app_average_memory Show average using memory of an app<br># TYPE pm2_app_average_memory gauge<br>pm2_app_average_memory{app=&quot;app&quot;,serviceName=&quot;my-app&quot;} 60813927<br><br># HELP pm2_app_total_memory Show total using memory of an app<br># TYPE pm2_app_total_memory gauge<br>pm2_app_total_memory{app=&quot;app&quot;,serviceName=&quot;my-app&quot;} 121626624<br><br># HELP pm2_event_loop_latency_p95 Event Loop Latency p95. Unit &quot;ms&quot;<br># TYPE pm2_event_loop_latency_p95 gauge<br>pm2_event_loop_latency_p95{app=&quot;app&quot;,instance=&quot;1&quot;,serviceName=&quot;my-app&quot;} 2.55<br>pm2_event_loop_latency_p95{app=&quot;app&quot;,instance=&quot;2&quot;,serviceName=&quot;my-app&quot;} 2.48</pre><p>Finally you can have Grafana dashboard with detailed statistic of your application. If you like it you can <a href="https://vexell.ru/content/files/2023/09/grafana-model.json">download this dashboard from this link</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LtupLuydytEVVblc.png" /></figure><p>In our case, each node.js project is packaged into a Docker container, and inside, we install PM2 and additional modules. All parameters, such as the service name or port, are passed through arguments. As a result, the Docker container looks something like this:</p><pre>FROM node:18-bullseye-slim <br><br>#### Install PM2<br>RUN npm i -g pm2@5.2.2<br><br># ...<br># Build project<br>#...<br><br>ARG PROJECT_NAME<br>ARG ENV_METRICS_PORT<br><br>#### Install modules for PM2<br>RUN pm2 install pm2-autoscale &amp;&amp; pm2 install pm2-prom-module &amp;&amp; pm2 set pm2-prom-module:port $ENV_METRICS_PORT &amp;&amp; pm2 set pm2-prom-module:service_name $PROJECT_NAME<br><br>CMD [&quot;pm2-runtime&quot;, &quot;--json&quot;, &quot;.ecosystem.config.js&quot;]</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=43d4b958c563" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Autoscale node.js applications with PM2 and pm2-autoscale module]]></title>
            <link>https://vexell.medium.com/autoscale-node-js-applications-with-pm2-and-pm2-autoscale-module-3129582dc72c?source=rss-d24150e7ad77------2</link>
            <guid isPermaLink="false">https://medium.com/p/3129582dc72c</guid>
            <category><![CDATA[autoscale]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[pm2]]></category>
            <category><![CDATA[scaling]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Viacheslav Volkov]]></dc:creator>
            <pubDate>Thu, 23 Mar 2023 22:41:17 GMT</pubDate>
            <atom:updated>2023-03-23T22:55:40.071Z</atom:updated>
            <content:encoded><![CDATA[<h3>Auto scaling Node.js applications with PM2 and pm2-autoscale module</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Km5ROiDUGFZauzAT3pr_lg.png" /><figcaption>Autoscale PM2 apps with pm2-autoscale module</figcaption></figure><p>In this article, i would like to tell you how you can easily automatically scale your Node.js applications to handle increased traffic loads using PM2 and keep your server resources under control.</p><h4>PM2 Cluster Mode</h4><p>PM2 is a process manager for Node.js applications that allows users to easily manage their Node.js applications and keep them running smoothly. With <strong>cluster mode </strong>PM2<strong> </strong>allows networked Node.js applications to be scaled across all CPUs available, without any code modifications.</p><p>For example, if you have server with 8 CPUs you can run 8 instances of your application and increase the performance and reliability of your application.</p><p>To run application in cluster mode you can easily create <a href="https://pm2.keymetrics.io/docs/usage/application-declaration/">ecosystem configuration file</a> and start you application</p><pre>module.exports = {<br>    apps: [<br>        {<br>            name: &#39;app&#39;,<br>            script: &#39;build/app.js&#39;,<br>            instances: &#39;8&#39;,<br>            autorestart: true,<br>            watch: false,<br>            max_memory_restart: &#39;512M&#39;,<br>            vizion: false,<br>            exec_mode: &#39;cluster&#39;,<br>        },<br>    ],<br>};</pre><p>This configuration allows you run 8 workers on your server. And for most cases it would be enough (especially if you have only one application on your server).</p><p>But imagine you want to add one more application to your server. Of course you want split resources between your applications. Now you change configuration file for every app and set 4 workers for every application. It will work until any of your applications can handle increased traffic load. If one of the application uses 100% CPU of every worker you should add more workers. In that case you should connect to your server and use pm2 scale command to scale more workers for loaded app and decrease workers for another app.</p><pre>pm2 scale app +3 # Add 3 new additional instances for your app</pre><p>When application load has been decreased, you also should connect to the server and revert your changes back. Not comfortable and easy solution. Plus you have to have solution to monitor you applications to detect when you need scale one of your apps.</p><p>Another case, for example, you have server with 48 CPUs and you want to run multiple apps on it. If you run every application with instances=max PM2 will run 48 instances and imagine that every instance uses approximately 100Mb of RAM (~5GB for all instances). So if you have 10 application it means you will use about 50GB of the server memory without any server load. You are using your server resources ineffectively.</p><p>Unfortunately PM2 does not have any good and simple solutions how to dynamically increase workers and monitor your applications. And with free version you can see CPU utilization and Memory usage <a href="https://pm2.keymetrics.io/docs/usage/monitoring/">only in terminal</a>.</p><h4>PM2 Autoscale Module</h4><p>To solve this issue i wrote plugin <a href="https://www.npmjs.com/package/pm2-autoscale">pm2-autoscale</a> that helps to optimize application’s performance by automatically adjusting the number of instances running based on the CPU utilization of every application.</p><p>To use <a href="https://www.npmjs.com/package/pm2-autoscale">pm2-autoscale</a> module your should install it with command</p><pre>pm2 install pm2-autoscale</pre><p>Module supports few configuration options</p><ul><li>scale_cpu_threshold Maximum value of CPU utilization one of application instances when the module will try to increase application instances. (default to 30)</li><li>release_cpu_threshold Average value of all CPUs utilization of the application when the module will decrease application instances (default to 5)</li><li>debug Enable debug mode to show logs from the module (default to false)</li></ul><p>To modify the module config values you can use the following commands:</p><pre>pm2 set pm2-autoscale:debug true<br>pm2 set pm2-autoscale:scale_cpu_threshold 50</pre><p>Now you can modify your ecosystem configuration to run any application with minimum required instances. For example, if you have 8 CPUs and 2 applications, you can set instances=2 for every application and keep available resources of your server. When module detects that CPU utilisation is higher then scale_cpu_threshold it will start increasing instances to max CPUs-1 only if server has available free memory. When module detects CPU utilization is decreasing it will stop useless instances.</p><p>See example how it works. I tested it with Apache Benchmark.</p><pre>0|pm2-autoscale | App &quot;app&quot; has 1 worker(s). CPU: 0.<br>0|pm2-autoscale | App &quot;app&quot; has 1 worker(s). CPU: 17.<br>0|pm2-autoscale | App &quot;app&quot; has 1 worker(s). CPU: 29.<br>0|pm2-autoscale | INFO: Increase workers<br>0|pm2-autoscale | App &quot;app&quot; scaled with +1 worker<br>0|pm2-autoscale | App &quot;app&quot; has 2 worker(s). CPU: 26,34.<br>0|pm2-autoscale | App &quot;app&quot; has 2 worker(s). CPU: 29,43.<br>0|pm2-autoscale | App &quot;app&quot; has 2 worker(s). CPU: 28,38.<br>0|pm2-autoscale | INFO: Increase workers<br>0|pm2-autoscale | INFO: App &quot;app&quot; is busy<br>0|pm2-autoscale | App &quot;app&quot; scaled with +1 worker<br>0|pm2-autoscale | App &quot;app&quot; has 3 worker(s). CPU: 27,35,33.<br>0|pm2-autoscale | App &quot;app&quot; has 3 worker(s). CPU: 25,31,22.<br>0|pm2-autoscale | App &quot;app&quot; has 3 worker(s). CPU: 24,29,23.<br>0|pm2-autoscale | App &quot;app&quot; has 3 worker(s). CPU: 23,25,20.<br>0|pm2-autoscale | App &quot;app&quot; has 3 worker(s). CPU: 15,18,17.<br>0|pm2-autoscale | App &quot;app&quot; has 3 worker(s). CPU: 11,13,13.<br>0|pm2-autoscale | App &quot;app&quot; has 3 worker(s). CPU: 8,9,10.<br>0|pm2-autoscale | App &quot;app&quot; has 3 worker(s). CPU: 6,7,7.<br>0|pm2-autoscale | App &quot;app&quot; has 3 worker(s). CPU: 5,5,5.<br>0|pm2-autoscale | INFO: Decrease workers<br>0|pm2-autoscale | INFO: App &quot;app&quot; is busy<br>0|pm2-autoscale | App &quot;app&quot; decresed one worker<br>0|pm2-autoscale | App &quot;app&quot; has 2 worker(s). CPU: 4,4.<br>0|pm2-autoscale | App &quot;app&quot; has 2 worker(s). CPU: 3,3.<br>0|pm2-autoscale | App &quot;app&quot; has 2 worker(s). CPU: 2,2.<br>0|pm2-autoscale | INFO: Decrease workers<br>0|pm2-autoscale | INFO: App &quot;app&quot; is busy<br>0|pm2-autoscale | App &quot;app&quot; decresed one worker</pre><p>Thus, if the CPU usage of the application is high, the module can increase the number of instances running to handle the load. Similarly, if the CPU usage is low, the module can reduce the number of instances running to save resources.</p><p>Source code of the module is available on GitHub <a href="https://github.com/VeXell/pm2-autoscale">https://github.com/VeXell/pm2-autoscale</a> and if you want to add/change something — just create a pull request.</p><p>Thank you for reading this article. Hope you found this useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3129582dc72c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to write UK Rent Telegram Bot]]></title>
            <link>https://vexell.medium.com/how-to-write-uk-rent-telegram-bot-9be2ad2524b9?source=rss-d24150e7ad77------2</link>
            <guid isPermaLink="false">https://medium.com/p/9be2ad2524b9</guid>
            <category><![CDATA[telegram-bot]]></category>
            <category><![CDATA[nodejs-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[telegram]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Viacheslav Volkov]]></dc:creator>
            <pubDate>Fri, 16 Jul 2021 22:13:40 GMT</pubDate>
            <atom:updated>2021-07-16T22:13:40.427Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mAhhULv7tLwerAs8HDqQVQ.jpeg" /><figcaption>How to write UK Rent Telegram Bot</figcaption></figure><p>It is tricky time when you start looking for a new property to rent in the UK. You should spend a lot of time to monitor many different websites every day. Good flats might gone in the same day when new property has been published, especially if you are looking for a new flat in the busiest time of the year — summer.</p><p>I had the same problem<strong> </strong>and had decided to write a<strong> </strong>small Telegram bot which could help me stop wasting time on websites. I use Telegram every day and really like this platform because it is really fast and powerful. So, let me introduce <a href="https://t.me/UKRentBot">UKRentBot</a>. Follow <a href="https://t.me/UKRentBot">this link and try it</a>.</p><p>Telegram has <a href="https://core.telegram.org/">good api</a> to work with messenger and a lot of frameworks to simplify development. I prefer to use node.js and decided to start with <a href="https://telegraf.js.org/">telegraf.js</a> framework. This is widely using framework with good documentation, Typescript codebase and also it supports latest Telegram api with a lot of different features. As database I use free version of Google Firebase Database. It is the first time when I use it and this is a good product to create MVP versions of your app or for a simple, small application.</p><p>Before make requests to the Telegram api you need to create a new bot on Telegram platform and to get bot token. You just need to go to BotFather bot <a href="https://t.me/botfather">https://t.me/botfather</a> and use his commands to create you own bot, set description or about text. To be honest this bot is a good example how every bot should work.</p><p>Now I can start development. Have a look on my <em>index.ts</em> file. Bot initialization is not difficult. Also I use i18n middleware to support 2 languages.</p><pre>import &#39;./env&#39;;<br>import {Telegraf, session} from &#39;telegraf&#39;;<br>import TelegrafI18n from &#39;telegraf-i18n&#39;;<br>import {TelegrafContext} from &#39;types&#39;;<br>// Read ENV variables<br>import {DATABASE, FIREBASE_AUTH, BOT_TOKEN} from &#39;config&#39;;</pre><pre>import enLocale from &#39;./locales/en&#39;;<br>import ruLocale from &#39;./locales/ru&#39;;</pre><pre>import {initActions} from &#39;actions&#39;;<br>import {initWizards} from &#39;wizards&#39;;<br>import {initJobs} from &#39;jobs&#39;;<br>import {initDatabase} from &#39;services/db&#39;;</pre><pre>initDatabase(FIREBASE_AUTH, DATABASE);</pre><pre>const i18n = new TelegrafI18n({<br>    defaultLanguage: &#39;en&#39;,<br>    allowMissing: true,<br>    useSession: true,<br>    defaultLanguageOnMissing: true,<br>});</pre><pre>i18n.loadLocale(&#39;en&#39;, enLocale);<br>i18n.loadLocale(&#39;ru&#39;, ruLocale);</pre><pre>const bot = new Telegraf&lt;TelegrafContext&gt;(BOT_TOKEN);</pre><pre>bot.use(session());<br>bot.use(i18n.middleware());</pre><pre>initWizards(bot);<br>initActions(bot);</pre><pre>// Start bot<br>bot.launch();</pre><p>With Telegram api every bot can support different commands, actions, scenes or wizard actions. Have a look on <strong><em>initActions</em></strong> function.</p><pre>export function initActions(bot: Telegraf&lt;TelegrafContext&gt;) {</pre><pre>  // Two important commands for bot<br>  bot.start(actionStart);<br>  bot.help(actionHelp);</pre><pre>  // Set bot quick menu<br>  bot.settings(async (ctx) =&gt; {<br>    await ctx.setMyCommands([<br>      {<br>        command: GLOBAL_ACTIONS.search,<br>        description: ctx.i18n.t(`actions.${GLOBAL_ACTIONS.search}`),<br>      },<br>      {<br>        command: GLOBAL_ACTIONS.searches,<br>        description: ctx.i18n.t(`actions.${GLOBAL_ACTIONS.searches}`),<br>      },<br>      {<br>        command: GLOBAL_ACTIONS.share,<br>        description: ctx.i18n.t(`actions.${GLOBAL_ACTIONS.share}`),<br>      },<br>    ]);<br>  });</pre><pre>  bot.command(GLOBAL_ACTIONS.search, actionSearch);</pre><pre>  // ...Other commands and actions here</pre><pre>  // With actions you can have specials buttons with RegExp format<br>  // I use it when user wants to remove search from list<br>  bot.action(new RegExp(`${GLOBAL_ACTIONS.remove}_(?&lt;id&gt;.*)?$`), actionRemove);<br>}</pre><p>Let’s have a look on <strong><em>actionSearch.</em></strong> In this action I start wizard after few command validations. On this step I also try to save <strong>chatId </strong>because I use it later to send new updates. First time I save it on <strong><em>/start</em></strong> command (this is first comment when user start working with bot).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nydWfDrp54_bqLlXRpZCig.jpeg" /><figcaption>Greeting command in the telegram bot</figcaption></figure><pre>export default async function actionSearch(ctx: TelegrafContext) {<br>  const message = ctx.i18n.t(&quot;wizardSearch.intro&quot;);<br>  const chatId = ctx.from?.id;</pre><pre>  if (chatId) {<br>    // Save new chat to database<br>    updateChat(chatId, {<br>      firstName: ctx.from?.first_name || &quot;&quot;,<br>      lastName: ctx.from?.last_name || &quot;&quot;,<br>      username: ctx.from?.username || &quot;&quot;,<br>      language: ctx.from?.language_code || &quot;&quot;,<br>  });</pre><pre>  try {<br>      const activeSearches = await getSearches(chatId);<br>      ctx.session.activeSearches = activeSearches;</pre><pre>      if (<br>        activeSearches &amp;&amp;<br>        Object.keys(activeSearches).length &gt;= MAX_SEARCHES<br>      ) {<br>        // Do not allow more searches<br>        return ctx.replyWithMarkdown(<br>          ctx.i18n.t(&quot;error.maxSearchesReached&quot;, {<br>            maxSearches: MAX_SEARCHES,<br>          }),<br>          Markup.inlineKeyboard([<br>            Markup.button.callback(&quot;📝 My Searches&quot;, GLOBAL_ACTIONS.searches),<br>          ])<br>        );<br>      } else {<br>        await ctx.replyWithMarkdown(message, Markup.removeKeyboard());</pre><pre>        // Enter to wizard<br>        return ctx.scene.enter(SEARCH_WIZARD_TYPE);<br>      }<br>    } catch (error) {<br>      console.log(&quot;error&quot;);<br>    }<br>  } else {<br>    return ctx.replyWithMarkdown(<br>      ctx.i18n.t(&quot;error.emptyChatId&quot;),<br>      Markup.removeKeyboard()<br>    );<br>  }<br>}</pre><p>Wizard is step by step form which I use to ask a user about desired property. And from my point of view it is the most difficult part in the bot.</p><pre>export function initWizards(bot: Telegraf&lt;TelegrafContext&gt;) {</pre><pre>  // Initilization of all scenes in the bot <br>  const stage = new Scenes.Stage&lt;TelegrafContext&gt;([searchWizard]);</pre><pre>  // Global command and actions in wizard to exit from it<br>  stage.action(ACTIONS.CANCEL, (ctx) =&gt; {<br>    ctx.reply(ctx.i18n.t(&quot;operationCanceled&quot;));<br>    return ctx.scene.leave();<br>  });</pre><pre>  stage.command(ACTIONS.CANCEL, (ctx) =&gt; {<br>    ctx.reply(ctx.i18n.t(&quot;operationCanceled&quot;));<br>    return ctx.scene.leave();<br>  });</pre><pre>  bot.use(stage.middleware());<br>}</pre><p>For example, wizard code. In the wizard we should describe actions step by step to get data from user input.</p><pre>export default new Scenes.WizardScene&lt;TelegrafContext&gt;(<br>  WIZARD_TYPE,<br>  async (ctx) =&gt; {<br>    const chatId = ctx.chat?.id;</pre><pre>    ctx.scene.session.search = {<br>      chatId,<br>    };</pre><pre>    await ctx.replyWithMarkdown(<br>      ctx.i18n.t(&quot;wizardSearch.actions.location&quot;)<br>    );</pre><pre>    return ctx.wizard.next();<br>  },<br>  processLocation,|</pre><pre>  // Other actions...<br>);</pre><p>Every new step you should validate user input and then send a new message to chat with a new form question. For example, have a look on the function <strong><em>processLocation</em></strong> below. To go to the next step method <strong><em>wizard.next()</em></strong> should be executed.</p><pre>export default async function processLocation(ctx: TelegrafContext) {<br>  try {</pre><pre>    if (<br>      !ctx.message ||<br>      !(&quot;text&quot; in ctx.message) ||<br>      ctx.message.text.length &lt;= 2<br>    ) {<br>      throw new IncorrectMessageError(<br>        ctx.i18n.t(&quot;wizardSearch.errors.location&quot;)<br>      );<br>    }</pre><pre>    try {<br>      const location = await detectLocation(ctx.message.text);<br>      ctx.scene.session.search.area = location.locationName;<br>      ctx.scene.session.search.searchAreaId = location.locationId;<br>    } catch (error) {}</pre><pre>    if (!ctx.scene.session.search.area) {<br>      throw new NoLocationFoundError(<br>        ctx.i18n.t(&quot;wizardSearch.errors.locationNotFound&quot;)<br>      );<br>    }</pre><pre>    let locationAlreadyInSearch = false;</pre><pre>    if (ctx.session.activeSearches) {<br>      const searches = ctx.session.activeSearches;</pre><pre>      Object.keys(searches).forEach((key) =&gt; {<br>        const searchObject = searches[key];</pre><pre>        if (<br>          searchObject.searchAreaId === ctx.scene.session.search.searchAreaId<br>        ) {<br>          locationAlreadyInSearch = true;<br>        }<br>      });<br>    }</pre><pre>    if (locationAlreadyInSearch) {<br>      throw new LocationAlreadyInSearchError(<br>        ctx.i18n.t(&quot;wizardSearch.errors.locationAlreadyInSearch&quot;, {<br>          location: ctx.scene.session.search.area,<br>        })<br>      );<br>    }</pre><pre>    // When we finished with data validation and store required values we send new message to the chat.</pre><pre>    await askForDistance(ctx);<br>    return ctx.wizard.next();<br>  } catch (error) {<br>    return cancelSearchReply(ctx, error.message);<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n8Eh0-m_A14jSi5Pk3J4fQ.jpeg" /><figcaption>UKRent Telegram bot wizard actions</figcaption></figure><p>You can see the full wizard form on the image above. Always have possibility (command or action) to return from wizard. For example, you can have wizard command <strong><em>/cancel.</em></strong></p><p>It is really cool when for every question you can add special button actions or show specific keyboard when user can just click a button and a form would be completed. It is good UI experience especially for mobile users.</p><p>So, that is it. On the last step I save form data to Firebase. Have a look on few functions to operate with user data in database. When you work with Firebase you should a little bit change your mind, especially if before you worked only with SQL based databases because data structure would be different.</p><pre>export function saveSearch(<br>  searchRequest: ISearchRequestInput<br>): Promise&lt;ISearchRequestRecord&gt; {<br>  const searchesListRef = getDB().ref(`${PATH}/${searchRequest.chatId}`);<br>  const searchRef = searchesListRef.push();</pre><pre>  return searchRef.set({<br>    ...searchRequest,<br>    ...{<br>      createdAt: moment.utc().format(),<br>      expiredAt: moment.utc().add(30, &quot;days&quot;).format(),<br>      lastSearchAt: null,<br>    },<br>  });<br>}</pre><pre>export async function getSearches(<br>  chatId: number<br>): Promise&lt;ISearchRecords | null&gt; {<br>  const searchesList = await getDB().ref(`${PATH}/${chatId}`).get();</pre><pre>  if (searchesList.exists()) {<br>    return searchesList.toJSON() as ISearchRecords;<br>  }</pre><pre>  return null;<br>}</pre><pre>export async function removeSearch(<br>  chatId: number,<br>  index: string<br>): Promise&lt;boolean&gt; {<br>  await getDB().ref(`${PATH}/${chatId}/${index}`).remove();<br>  return true;<br>}</pre><pre>type IUpdateSearchRecord = Partial&lt;ISearchRequestRecord&gt;;<br>export function updateSearch(<br>  chatId: number,<br>  index: string,<br>  search: IUpdateSearchRecord<br>) {<br>  return getDB().ref(`${PATH}/${chatId}/${index}`).update(search);<br>}</pre><p>This is my database structure. I am not 100% sure if this structure is correct, but it is fast to access to important data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g620KXKxKqrKl6_jHew0Iw.jpeg" /><figcaption>UKRent Telegram bot Database structure</figcaption></figure><p>Now all data stored in database and user can have access to searches with <strong><em>/searches </em></strong>command. And job actions is going to start find new properties. I have 3 different jobs — search new properties (every 4 hours for every chat), send new properties to user chats (every 15 minutes) and remove expired chats. For all jobs i use <strong><em>setInterval</em></strong> function.</p><p>I like that Firebase has observer which reduce requests to database on every timer event. For example you can have only 2 subscribers for specific path and when new or updated data would be available you will get new event.</p><pre>function getAllSearchesRef() {<br>  return getDB().ref(`${PATH}`);<br>}</pre><pre>let searches: ISearchEntries | null = null;</pre><pre>getAllSearchesRef().on(&quot;value&quot;, (snapshot) =&gt; {<br>  if (snapshot.exists()) {<br>    searches = snapshot.val();<br>  }<br>});</pre><p>When new results would be found bot will send message to user chat. Instead of one message i should send 2 messaged because with <em>mediaGroup </em>message Telegram does not support Markdown and custom keyboard. That is sad.</p><pre>function formatTgMessage(<br>  area: string,<br>  searchResult: ISearchResult<br>): {<br>  media: { type: &quot;photo&quot;; media: string; caption?: string }[];<br>  text: string;<br>} {<br>  // const caption = `Property at ${area}.`;</pre><pre>const images = Array.isArray(searchResult.images) ? searchResult.images : [];</pre><pre>return {<br>    media: images.map((imageUrl) =&gt; {<br>      return {<br>        type: &quot;photo&quot;,<br>        media: imageUrl,<br>      };<br>    }),</pre><pre>text: `<br>🏠 ${searchResult.title} / 💷 *${searchResult.price}* <br>🗓 Available from *${searchResult.availableFrom}*<br>📍 *${searchResult.address}*</pre><pre>Search in ${area}`,<br>  };<br>}</pre><pre>// Other function ...</pre><pre>const message = formatTgMessage(area, searchResult);<br>const media = message.media.slice(0, 10);</pre><pre>let submitted = false;</pre><pre>try {<br>  if (media.length) {<br>    await telegramBot.telegram.sendMediaGroup(chatId, media);<br>  }</pre><pre>  await telegramBot.telegram.sendMessage(chatId, message.text, {<br>    parse_mode: &quot;Markdown&quot;,<br>    reply_markup: {<br>      inline_keyboard: [[Markup.button.url(https://medium.com/&quot;%E2%86%97%EF%B8%8F%20Open&quot;,%20searchResult.openUrl)]],<br>    },<br>  });<br>  submitted = true;<br>} catch (error) {<br>  if (error.response?.error_code === 400) {<br>    // Chat not found<br>  }</pre><pre>  if (error.response?.error_code === 403) {<br>    // Chat has been blocked. Remove search and data<br>    await removeSearch(chatId, searchId);<br>    await removeSearchResults(chatId, searchId);<br>  }</pre><pre>  break;<br>}</pre><p>And result you can see on this image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V-8uIiUmqW3Ge46C5CaRpw.jpeg" /><figcaption>Search results</figcaption></figure><p>Of course there are a lot of things which i can improve and add to this bot, but at this moment it covers most of my cases. If you interesting in writing telegrams bots, have an idea or feature request you can have a look on my code on github <a href="https://github.com/VeXell/UKRentHomeHunter">https://github.com/VeXell/UKRentHomeHunter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9be2ad2524b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to collect data from your leads with NodeJs and Google spreadsheet]]></title>
            <link>https://vexell.medium.com/how-to-collect-data-from-your-leads-with-nodejs-and-google-spreadsheet-53eb43d033de?source=rss-d24150e7ad77------2</link>
            <guid isPermaLink="false">https://medium.com/p/53eb43d033de</guid>
            <category><![CDATA[google-spreadsheets]]></category>
            <category><![CDATA[google-spreadsheet-api]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[google]]></category>
            <dc:creator><![CDATA[Viacheslav Volkov]]></dc:creator>
            <pubDate>Fri, 02 Jul 2021 16:11:07 GMT</pubDate>
            <atom:updated>2021-07-02T16:11:07.121Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pxsHVtOewpmw97ZnouJ1Gw.jpeg" /><figcaption>NodeJs and Google spreadsheet</figcaption></figure><p>Just imagine — you work on a new MVP project and decided to start it with a small landing page which describe main information, benefits of your products or service.</p><p>Landing page is ready (for example with next.js), but you want collect forms data from this page. How to do it? Of course, if you have CRM system the best way would be to use API of this system to collect form data. But if you do not have any CRM solution you can use free and simple tool — Google spreadsheet. It has simple API and amazing UI to operate with any data from your clients. So, let’s do simple and fast solution.</p><p>First of all you should have google account and create Service Account at this page <a href="https://console.cloud.google.com/">https://console.cloud.google.com/</a>. How to do it you can read at this support page <a href="https://developers.google.com/identity/protocols/oauth2/service-account?hl=en">https://developers.google.com/identity/protocols/oauth2/service-account?hl=en</a>. It is not difficult, but after all actions you will get JSON file with all credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RMxBNeKfPLW4-7F-bLrQKg.jpeg" /></figure><p>Second step — download and install nodejs library <a href="https://www.npmjs.com/package/google-spreadsheet">https://www.npmjs.com/package/google-spreadsheet</a>. This is good wrapper to work with spreadsheet and also it has well-formed documentation. If you use Typescript in your project do not forget to install `@types/google-spreadsheet`.</p><p>And finally we can write some code to collect form data from landing page. Have a look on example below from Next.js framework on Typescript.</p><pre>import { GoogleSpreadsheet } from &#39;google-spreadsheet&#39;;<br>import type { NextApiRequest, NextApiResponse } from &#39;next&#39;;<br>import { FieldSchemaValues } from &#39;../../blocks/index/form&#39;;<br>import creds from &#39;../../config/nodejs.json&#39;;</pre><pre>// You can get it from the address of document page<br>const doc = new GoogleSpreadsheet(&#39;&lt;ID of your Google spreadsheet document&gt;&#39;);</pre><pre>export default async function handler(<br>    req: NextApiRequest,<br>    res: NextApiResponse<br>) {<br>    if (req.method !== &#39;POST&#39;) {<br>        return res.status(405).json({<br>            error: &#39;Incorrect form request&#39;<br>        });<br>    }</pre><pre>    // Get data from the request<br>    const {<br>        name,<br>        email,<br>        instagram,<br>        tiktok,<br>        youtube<br>    }: FieldSchemaValues = req.body;</pre><pre>    // Validate data<br>    if (!name || !email) {<br>        return res.status(400).json({<br>            error: &#39;Please provide name &amp; email&#39;<br>        });<br>    }</pre><pre>    // Make authoziation of our client<br>    await doc.useServiceAccountAuth(creds);<br>    await doc.loadInfo();</pre><pre>    const date = new Date().toUTCString();<br>    const sheet = await doc.sheetsByIndex[0];</pre><pre>    // Add headers<br>    await sheet.setHeaderRow([<br>       &#39;Date&#39;,<br>       &#39;Name&#39;,<br>       &#39;Email&#39;,<br>       &#39;Instagram&#39;,<br>       &#39;TikTok&#39;,<br>       &#39;Youtube&#39;,<br>    ]);</pre><pre>    // Write data to file<br>    await sheet.addRow({<br>        Date: date,<br>        Name: name,<br>        Email: email,<br>        Instagram: String(instagram),<br>        TikTok: String(tiktok),<br>        Youtube: String(youtube),<br>    });</pre><pre>    return res.status(200).json({});<br>}</pre><p>Also do not forget to provide edit access to you created Service Account. In your JSON file you can find email. Use it when you provide access to your google document.</p><p>And that is it. You do not need to create any other Service Account for your new projects, you can use created one and with this account you can write to any Google spreadsheets documents (if someone provide access to you Service account).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53eb43d033de" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React native in app notification]]></title>
            <link>https://vexell.medium.com/react-native-in-app-notification-fe8d1e377075?source=rss-d24150e7ad77------2</link>
            <guid isPermaLink="false">https://medium.com/p/fe8d1e377075</guid>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Viacheslav Volkov]]></dc:creator>
            <pubDate>Thu, 20 May 2021 10:33:16 GMT</pubDate>
            <atom:updated>2021-05-20T10:33:57.125Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dGcuM91R6eHWQFQUnCukJQ.jpeg" /></figure><p>Sometimes you want to show something to users in your app with small notification. For example i use it to show information how many coins user earn in the game or any other helpful information about purchases. I tried to find small simple library on Typescript and did not find and decided to write and publish my own library.</p><p>Have a look on my <a href="https://www.npmjs.com/package/react-native-internal-notification">Typescript component</a> to show internal notifications for react native application. To add it to your project you can just run this command.</p><pre>yarn add react-native-internal-notification</pre><p>Then wrap your app or root component with Notification provider. It should be root container because my component uses react context to provide access to child components.</p><pre>import { NotificationProvider } from &#39;react-native-internal-notification&#39;;<br>import App from &#39;./App&#39;;<br><br>const Application = function () {<br>    return (<br>        &lt;NotificationProvider&gt;<br>            &lt;App /&gt;<br>        &lt;/NotificationProvider&gt;<br>    );<br>};</pre><p>After that you can show notification from any of your components</p><pre>import React, { useCallback } from &#39;react&#39;;<br>import { TouchableOpacity, Text } from &#39;react-native&#39;;<br>import { FontAwesome } from &#39;@expo/vector-icons&#39;;<br><br>import { useNotification } from &#39;react-native-internal-notification&#39;;<br><br>export default function DevScreen() {<br>    const notification = useNotification();<br><br>    const handleNotificationTestClick = useCallback(() =&gt; {<br>        notification.showNotification({<br>            title: &#39;My first notification&#39;,<br>            message: &#39;Hello from my first message&#39;,<br>            icon: &lt;FontAwesome name=&quot;check-circle&quot; size={45} /&gt;,<br>            onPress: () =&gt; {<br>                alert(&#39;Pressed&#39;);<br>            },<br>        });<br>    }, [notification]);<br><br>    return (<br>        &lt;&gt;<br>            &lt;TouchableOpacity onPress={handleNotificationTestClick}&gt;<br>                &lt;Text&gt;Show notification&lt;/Text&gt;<br>            &lt;/TouchableOpacity&gt;<br>        &lt;/&gt;<br>    );<br>}</pre><p>I prefer to use SVG icons from expo because it library has a lot of them for any purposes.</p><p>Result you can see on this gif image</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*3366jrg3gKsRJ9tIOPYEEQ.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fe8d1e377075" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React native facebook auth]]></title>
            <link>https://vexell.medium.com/react-native-facebook-auth-82b156357a8a?source=rss-d24150e7ad77------2</link>
            <guid isPermaLink="false">https://medium.com/p/82b156357a8a</guid>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[facebook-auth]]></category>
            <category><![CDATA[facebook]]></category>
            <dc:creator><![CDATA[Viacheslav Volkov]]></dc:creator>
            <pubDate>Sat, 15 May 2021 15:21:09 GMT</pubDate>
            <atom:updated>2021-05-15T15:21:09.122Z</atom:updated>
            <content:encoded><![CDATA[<p>If you want to use Facebook authorization in your react native application you have to configure your facebook application at <a href="https://developers.facebook.com/">https://developers.facebook.com</a> . You should add Android sign in and 2 important parameters. First one — Google Play Package Name and second — Key Hashes. There are no any questions with first one. But how to find second one? Let me describe it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6LEZktgvNsnPv7UGTASBgg.jpeg" /></figure><p>First of all you should go to your Google play developer console and open <strong>Setup-App Integrity </strong>and copy SHA-1 certificate fingerprint for <strong>App signing key certificate </strong>and after that convert this hex value to base64. For example you can do it <a href="http://tomeko.net/online_tools/hex_to_base64.php">with this link</a>. And that is it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zzTdMPk1z9AxiHxAxLKTBg.jpeg" /></figure><p>I prefer to use expo facebook library to simplify integration. For exaple this is my react hook.</p><pre>const handleFacebookClick = useCallback(async () =&gt; {<br>  setIsLoading(true);</pre><pre>try {<br>    await Facebook.initializeAsync({<br>      appId: FACEBOOK_APP_ID,<br>    });</pre><pre>    const result = await Facebook.logInWithReadPermissionsAsync({<br>      permissions: [&#39;public_profile&#39;],<br>    });</pre><pre>    if (result.type === &#39;success&#39;) {<br>      const authData: IAuthData = {<br>        externalId: result.userId,<br>        identityToken: result.token,<br>      };</pre><pre>      processJoin(EXTERNAL_TYPE.FACEBOOK, authData);<br>    } else {<br>      setIsLoading(false);<br>    }<br>  } catch ({ message }) {<br>    setIsLoading(false);<br>  }<br>}, [processJoin]);</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=82b156357a8a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>