<?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 Mahesh Samudra on Medium]]></title>
        <description><![CDATA[Stories by Mahesh Samudra on Medium]]></description>
        <link>https://medium.com/@maheshsamudra?source=rss-49dba213ad46------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*0IgnMR2B60wj9rUU.jpeg</url>
            <title>Stories by Mahesh Samudra on Medium</title>
            <link>https://medium.com/@maheshsamudra?source=rss-49dba213ad46------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 22:21:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@maheshsamudra/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[Creating a Simple PHP MVC Framework from Scratch]]></title>
            <link>https://maheshsamudra.medium.com/creating-a-simple-php-mvc-framework-from-scratch-7158f12340a0?source=rss-49dba213ad46------2</link>
            <guid isPermaLink="false">https://medium.com/p/7158f12340a0</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[php]]></category>
            <dc:creator><![CDATA[Mahesh Samudra]]></dc:creator>
            <pubDate>Mon, 06 Nov 2023 19:07:57 GMT</pubDate>
            <atom:updated>2025-01-25T03:54:24.876Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OlWFWnBF6aLP_FGk_EAJmQ.png" /></figure><p>MVC stands for Model-View-Controller, and it is a design pattern commonly used in software development, especially in web application development. As mentioned in the name, the application is separated into three interconnected components to promote modularity, maintainability, and ease of development.</p><p><strong>Model (M)</strong> represents the application’s data and business logic. Which means it’s responsible for retrieving, manipulating, and storing data.</p><p><strong>View (V)</strong> acts as the presentation layer, which is responsible for presenting the data to the end user.</p><p><strong>Controller (C)</strong> is an intermediary between the Model and the View. It receives user input and determines which Model or Models to invoke and which View to present.</p><p>Based on these clarifications, the MVC pattern enforces a clear separation of concerns between data management — Model, user interface — View, and application logic — Controller. This separation makes it easier to understand, maintain and extend an application.</p><h3>Prerequisites</h3><p>In this tutorial, you will learn how to build a simple PHP MVC Framework from scratch. To follow along, you should have a basic understanding of the following:</p><ul><li>PHP OOP concepts</li><li>Composer — the PHP package manager</li><li>HTML/CSS — not required for the framework, but to build the pages after</li></ul><h3>Setting up the Project</h3><p>Create a new directory for your project and open it in your favorite editor. Then, in the terminal, run composer init to initialize a new Composer project.</p><pre>composer init</pre><p>You can press enter, leaving all the questions empty except for the dev dependencies. When you are asked to add the dependencies and dev dependencies, type “no” and press enter for now.</p><p>Once completed, you will see a message like this:</p><p>“PSR-4 autoloading configured. Use “namespace Maheshsamudra\SimplePhpMvcStarter;” in src/”</p><p>For simplicity, we’ll change the namespace to something shorter, such as App. To do that, change the key of the “psr-4” in composer.json file:</p><pre>&quot;Maheshsamudra\\SimplePhpMvcStarter\\&quot; -&gt; &quot;App\\&quot;</pre><p>Then, run composer dump-autoload to which will update the classes that must be included in the project.</p><h3>Directory Structure</h3><pre>public/ # this is where the domain is pointed<br>src/<br>   Controllers/<br>   Models/<br>   Routes/<br>   Views/<br>vendor/ # automatically created by composer<br></pre><h3>Building the Core Components</h3><h4>Setting up the public folder</h4><p>Create a new file called index.php in the public/ folder. This file will serve as the entry point of the application.</p><pre>&lt;?php<br><br>require &#39;../vendor/autoload.php&#39;;<br><br>$router = require &#39;../src/Routes/index.php&#39;;</pre><h4>Handling the Routes</h4><p>Create a Router.php file inside src/ folder. This will map the routes to the correct controller.</p><pre>&lt;?php<br><br>namespace App;<br><br>class Router<br>{<br>    protected $routes = [];<br><br>    private function addRoute($route, $controller, $action, $method)<br>    {<br><br>        $this-&gt;routes[$method][$route] = [&#39;controller&#39; =&gt; $controller, &#39;action&#39; =&gt; $action];<br>    }<br><br>    public function get($route, $controller, $action)<br>    {<br>        $this-&gt;addRoute($route, $controller, $action, &quot;GET&quot;);<br>    }<br><br>    public function post($route, $controller, $action)<br>    {<br>        $this-&gt;addRoute($route, $controller, $action, &quot;POST&quot;);<br>    }<br><br>    public function dispatch()<br>    {<br>        $uri = strtok($_SERVER[&#39;REQUEST_URI&#39;], &#39;?&#39;);<br>        $method =  $_SERVER[&#39;REQUEST_METHOD&#39;];<br><br>        if (array_key_exists($uri, $this-&gt;routes[$method])) {<br>            $controller = $this-&gt;routes[$method][$uri][&#39;controller&#39;];<br>            $action = $this-&gt;routes[$method][$uri][&#39;action&#39;];<br><br>            $controller = new $controller();<br>            $controller-&gt;$action();<br>        } else {<br>            throw new \Exception(&quot;No route found for URI: $uri&quot;);<br>        }<br>    }<br>}</pre><p>Now, to set the initial route, create aindex.php file inside src/Routes/ folder. You can map the routes for POST and GET requests here separately.</p><pre>&lt;?php<br><br>use App\Controllers\HomeController;<br>use App\Router;<br><br>$router = new Router();<br><br>$router-&gt;get(&#39;/&#39;, HomeController::class, &#39;index&#39;);<br><br>$router-&gt;dispatch();</pre><h4>Controllers — Handling the home page</h4><p>First, create a Controller.php inside the src/ folder.</p><pre>&lt;?php<br><br>namespace App;<br><br>class Controller<br>{<br>    protected function render($view, $data = [])<br>    {<br>        extract($data);<br><br>        include &quot;Views/$view.php&quot;;<br>    }<br>}</pre><p>Now, we need to add a HomeController to handle the request. Inside thesrc/Controllers/ folder, create HomeController.php with an index method to handle the home page.</p><pre>&lt;?php<br><br>namespace App\Controllers;<br><br>use App\Controller;<br><br>class HomeController extends Controller<br>{<br>    public function index()<br>    {<br><br>        $this-&gt;render(&#39;index&#39;);<br>    }<br>}</pre><h4>Adding the Views</h4><p>Finally, to serve the home page, create index.php file inside thesrc/Views/ folder.</p><pre>&lt;h1&gt;Welcome to Simple PHP MVC Starter!&lt;/h1&gt;</pre><h4>Testing the progress</h4><p>Now, the app is ready to serve the home page. Navigate to the public folder and run the built-in PHP web server to test it.</p><pre>cd simple-php-mvc-starter/public<br><br>php -S localhost:9999</pre><p>If everything works, you should see this in the browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a68KpJZXYRrZtL1dKZVjCA.png" /></figure><h4>Creating a Model</h4><p>Create a new file Journal.php inside the Models/ directory. This represents the Journals in the application.</p><pre>&lt;?php<br><br>namespace App\Models;<br><br>class Journal<br>{<br>    public $name;<br>    public $publishedYear;<br><br>    public function __construct($name, $publishedYear)<br>    {<br>        $this-&gt;name = $name;<br>        $this-&gt;publishedYear = $publishedYear;<br>    }<br>}</pre><p>Now, let’s add some Journals to the Home page. Update the HomeController.php to load come Journals.</p><pre>&lt;?php<br><br>namespace App\Controllers;<br><br>use App\Controller;<br>use App\Models\Journal;<br><br>class HomeController extends Controller<br>{<br>    public function index()<br>    {<br>        $journals = [<br>            new Journal(&#39;My Third Journal Entry&#39;, &#39;2023&#39;),<br>            new Journal(&#39;My Second Journal Entry&#39;, &#39;2022&#39;),<br>            new Journal(&#39;My First Journal Entry&#39;, &#39;2021&#39;)<br>        ];<br>        $this-&gt;render(&#39;index&#39;, [&#39;journals&#39; =&gt; $journals]);<br>    }<br>}</pre><p>Finally, update the index.php inside the Views/ folder.</p><pre>&lt;h1&gt;Welcome to Simple PHP MVC Starter!&lt;/h1&gt;<br><br>&lt;ul&gt;<br>    &lt;?php foreach ($journals as $journal) : ?&gt;<br>        &lt;li&gt;&lt;?= $journal-&gt;name ?&gt; (&lt;?= $journal-&gt;publishedYear ?&gt;)&lt;/li&gt;<br>    &lt;?php endforeach; ?&gt;<br>&lt;/ul&gt;</pre><p>That’s it. You have successfully built your first PHP MVC framework from scratch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eaGU2TIYZHYwKWZL2EOCPQ.png" /></figure><p>Eventhough this is a simple start, creating a PHP MVC framework from scratch is a significant undertaking, and it’s a big project that can take a considerable amount of time and effort. Having that exposure is an excellent addition to your resume.</p><p>The example code is available on <a href="https://github.com/maheshsamudra/simple-php-mvc-starter">GitHub</a>. Thanks for reading &amp; happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7158f12340a0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Started with Mobile Apps — React Native with Expo]]></title>
            <link>https://maheshsamudra.medium.com/getting-started-with-mobile-apps-react-native-with-expo-c1344a738439?source=rss-49dba213ad46------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1344a738439</guid>
            <category><![CDATA[expo]]></category>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Mahesh Samudra]]></dc:creator>
            <pubDate>Sun, 09 Jul 2023 07:15:11 GMT</pubDate>
            <atom:updated>2023-07-09T07:20:18.617Z</atom:updated>
            <content:encoded><![CDATA[<h3>Getting Started with Mobile Apps — React Native with Expo</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HJrflZ9CgEBq6ccBrMsw6g.png" /></figure><p>TL;DR: This is a quick walk-through of an opinionated <a href="https://github.com/maheshsamudra/expo-starter">starter template</a> for Expo projects.</p><p>This includes:</p><ul><li>Environments — 3 to get started</li><li>Navigation — with Expo router</li><li>State Management — with React Context</li><li>Authentication — with Firebase</li><li>Push Notifications</li><li>App Previews — both Expo Go and Expo Dev Client</li><li>Code Formatting — with Prettier</li></ul><h3>Why another starter?</h3><p>I started developing mobile apps recently, and I’ve been going through setting up the same thing (almost) over and over again. So wanted to set up a starter to skip the initial setup.</p><h3>What’s Included?</h3><p><strong>Environments</strong></p><p>I’ve set up three environments to start with — local , staging , and production.</p><p><strong>Navigation</strong></p><p>I started using React Navigation for my early-stage projects. When they introduced the expo-router which uses the filesystem to create the pages, I jumped in quickly. Why? I do Gatsby and NextJS, and I find file-based routing very comfortable.</p><p><strong>State Management</strong></p><p>This starter uses useContext to manage the state, and it serves smaller projects pretty well. If you are looking for something advanced, there are many other options.</p><p><strong>Authentication</strong></p><p>Firebase authentication included. Simply because that’s my go-to auth platform.</p><p><strong>Push Notifications</strong></p><p>I’ve created a helper function to send the ExpoPushToken to an external endpoint. You can set this up in multiple ways; however, if the app doesn’t have a lot of endpoints, a simpler way is to link this endpoint to the environment. (* I’m still fine-tuning push notifications.)</p><p><strong>App Previews</strong></p><p>This starter supports both Expo Go and Expo Dev Client. Once the project is setup, you can simply run npm run android or npm run ios to start the project. Development build can be started by running npm run build-dev-i or npm run build-dev-a. Once the Dev client is installed, you can run npm run dev to start the server.</p><p><strong>Code Formatting</strong></p><p>Only Prettier for now. Everyone has different tastes, so feel free to build this from the ground up.</p><h3>Getting Started</h3><p>You can get started by cloning the GitHub repo:</p><pre>https://github.com/maheshsamudra/expo-starter</pre><p>Note: This starter doesn’t focus on the Web; however, you can get started by uncommenting line #34 in `app.config.js`:</p><pre>// bundler: &quot;metro&quot;, // Enable this if you want to support web</pre><p>Once the project is cloned, you must add the Firebase config to the /config/env.js file for authentication. And now you are ready to start the development.</p><h3><strong>Project Structure</strong></h3><p>I tried to keep this as minimal as possible so we don’t have to delete much before starting.</p><ul><li>components/ — a place to store your components</li><li>app/ — keep all the pages here</li><li>assets/ — the default place by Expo to keep the assets</li><li>hooks/ — to store the hooks. The user data, notifications, and ExpoPushToken are linked here by default.</li><li>config/ — includes the config for Firebase, style variables, and environments</li></ul><p>That’s it. Let me know if you like it.</p><p>Cheers,</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1344a738439" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going Serverless: Invoking Lambda Functions Locally with Serverless Offline]]></title>
            <link>https://awstip.com/going-serverless-invoking-lambda-functions-locally-with-serverless-offline-165b676131f7?source=rss-49dba213ad46------2</link>
            <guid isPermaLink="false">https://medium.com/p/165b676131f7</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless-offline]]></category>
            <dc:creator><![CDATA[Mahesh Samudra]]></dc:creator>
            <pubDate>Sat, 17 Sep 2022 10:19:31 GMT</pubDate>
            <atom:updated>2022-09-18T08:28:33.532Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently started building a Slack Application linked to a booking API. The API is deployed in AWS Lambda, and it’s developed locally using Serverless Offline.</p><p>When handling user interactions, Slack requires an acknowledgment within 3 seconds, but with the booking API, it’s not possible to complete the request within 3 seconds, especially when creating a booking.</p><p>Therefore, I used one function for the acknowledgment, and another function to handle the request and return data. In AWS docs, this was quite simple. Using <a href="https://docs.aws.amazon.com/lambda/latest/dg/API_Invoke.html">aws-sdk</a>, we can trigger another function.</p><pre>const {Lambda} = require(&quot;aws-sdk&quot;);</pre><pre>const lambda = new Lambda();</pre><pre>const payload = {...}</pre><pre>const params = {<br>  FunctionName: `my-api-${process.env.STAGE}-handleProcessA`,<br>  InvocationType: &quot;Event&quot;,<br>  LogType: &quot;None&quot;,<br>  Payload: JSON.stringify(payload),<br>};</pre><pre>await lambda.invoke(params).promise();</pre><p>This code works perfectly fine when deployed to AWS, but not locally with serverless offline. To use this with serverless offline, we need to pass the endpoint variable, which is also mentioned in the docs from Serverless Offline.</p><pre>const {Lambda} = require(&quot;aws-sdk&quot;);</pre><pre>const lambda = new Lambda({<br>  endpoint: process.env.IS_OFFLINE<br>    ? &#39;http://localhost:3002&#39;<br>    : &#39;https://lambda.us-east-1.amazonaws.com&#39;,<br>});</pre><pre>const payload = {...}</pre><pre>const params = {<br>  FunctionName: `my-api-${process.env.STAGE}-handleProcessA`,<br>  InvocationType: &quot;Event&quot;,<br>  LogType: &quot;None&quot;,<br>  Payload: JSON.stringify(payload),<br>};</pre><pre>await lambda.invoke(params).promise();</pre><p>For the API’s local development, I was using the port 8002, and when using the above code, I changed the port 3002 to be 8002. And running this returned an error: &quot;Unsupported Media Type&quot;</p><p>I searched in SO and found these two questions, but still, it didn’t solve the issue.</p><ul><li><a href="https://stackoverflow.com/questions/58735411/unable-to-invoke-a-lambda-from-another-lambda-using-aws-serverless-offline?noredirect=1&amp;lq=1">Unable to invoke a lambda from another lambda using aws serverless offline</a></li><li><a href="https://stackoverflow.com/questions/62232233/unsupported-media-type-using-serverless-offline?noredirect=1&amp;lq=1">“Unsupported Media Type” using serverless offline</a></li></ul><p>The answers to those two questions didn’t work for me, so I posted <a href="https://stackoverflow.com/questions/73718753/how-to-invoke-a-lambda-function-from-another-lambda-in-serverless-offline">a new question in SO.</a></p><p>After all that, I got a direction and started looking at the <a href="https://www.serverless.com/plugins/serverless-offline#usage-with-invoke">CLI options</a> of Serverless Offline again. That’s when I realized that there were two ports: --httpPort and --lambdaPort.</p><p>When invoking lambda functions, the --lambdaPort should be used. I was using the --httpPort and that&#39;s what gave me the error.</p><p>They have mentioned setting the serverless-offline endpoint. But I think it would be better understood in this way:</p><p><em>“To use Lambda.invoke you need to set the lambda endpoint to the serverless-offline endpoint with the </em><em>--lambdaPort.</em>&quot;</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=165b676131f7" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/going-serverless-invoking-lambda-functions-locally-with-serverless-offline-165b676131f7">Going Serverless: Invoking Lambda Functions Locally with Serverless Offline</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[QuickStart with Gatsby & Prismic]]></title>
            <link>https://maheshsamudra.medium.com/quickstart-with-gatsby-prismic-45ba02865fda?source=rss-49dba213ad46------2</link>
            <guid isPermaLink="false">https://medium.com/p/45ba02865fda</guid>
            <category><![CDATA[gatsbyjs]]></category>
            <category><![CDATA[prismic]]></category>
            <category><![CDATA[headless-cms]]></category>
            <category><![CDATA[boilerplate]]></category>
            <dc:creator><![CDATA[Mahesh Samudra]]></dc:creator>
            <pubDate>Thu, 04 Aug 2022 17:56:16 GMT</pubDate>
            <atom:updated>2023-05-19T18:08:12.541Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="GatsbyJS" src="https://cdn-images-1.medium.com/max/1024/1*OYrtH7Yni4iaas_wULs-uw.png" /><figcaption>Photo credits: <a href="https://status.gatsbyjs.com/">GatsbyJS</a></figcaption></figure><blockquote>This article is about the official Gatsby Starter theme linked to Prismic. The starter theme is available on the <a href="https://www.gatsbyjs.com/starters/maheshsamudra/gatsby-starter-prismic-blog/">Gatsby Starter Library</a> and the preview is available at <a href="https://gatsbystarterprismicblog.gatsbyjs.io/">Gatsby Cloud</a>.</blockquote><p>I’ve been using Gatsby for my projects since 2019 and recently started using Prismic as the CMS. Gatsby has boilerplates to kick-start projects with some other headless CMSs, but not with Prismic. This led me to build a barebones boilerplate with a simple home page and a blog, also included in Gatsby Official <a href="https://www.gatsbyjs.com/starters/maheshsamudra/gatsby-starter-prismic-blog">Starter Templates</a>.</p><p>You can see the preview at <a href="https://gatsbystarterprismicblog.gatsbyjs.io/">https://gatsbystarterprismicblog.gatsbyjs.io</a></p><p>Setting up the project will not take you more than just 10 minutes. This boilerplate includes a simple home page with a bio of the author and blog posts. This doesn’t include any styles other than /src/normalize.css and /src/styles.css. The main idea was to eliminate repetitive configuration when creating a new project.</p><p>Once you complete these simple steps, you have created a Gatsby project linked with Prismic.</p><ol><li>Clone the repo from <a href="https://github.com/maheshsamudra/gatsby-starter-prismic-blog">GitHub</a> and install the dependencies.</li><li>Create a repository in <a href="https://prismic.io/">Pricmic</a>.</li><li>Create the two custom types using the schema from /config/prismic/schemaand add some content. Of course, this is to get the starter up and running, and you can add more content types later.</li><li>Create access tokens for content and custom types from the Settings →API &amp; Security page in Prismic.</li><li>Create .env using .env.example and populate the values from Prismic.</li><li>Add your local domain to the “Previews” section in Prismic Settings.</li><li>That’s it. You can run npm run develop and see the project in action!</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45ba02865fda" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going Serverless — Part 3]]></title>
            <link>https://awstip.com/going-serverless-part-3-416a714a91f8?source=rss-49dba213ad46------2</link>
            <guid isPermaLink="false">https://medium.com/p/416a714a91f8</guid>
            <category><![CDATA[mysql]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Mahesh Samudra]]></dc:creator>
            <pubDate>Wed, 13 Jul 2022 12:13:48 GMT</pubDate>
            <atom:updated>2022-07-26T14:02:04.394Z</atom:updated>
            <content:encoded><![CDATA[<h3>Going Serverless — Part 3</h3><p>This is the third article in this series and I’m going to walk you through the easiest way to connect serverless functions to a Database. In this case, I’m using MySQL, but if you prefer, you can use this same method to connect to a PostgreSQL database as well.</p><p>I’m assuming that you already have a serverless project that is deployed to AWS. If not you can read these articles to get up to speed:</p><p><a href="https://maheshsamudra.medium.com/going-serverless-part-1-f3b2ea778d1d">Going Serverless — Part 1</a>: Setting up the serverless project in your local machine</p><p><a href="https://medium.com/p/cdb6acb0ebef">Going Serverless — Part 2</a>: Deploying the project to AWS</p><p>Update: After the last article, I’ve made some minor refactoring to the project available on <a href="https://github.com/maheshsamudra/sample-aws-serverless-project">GitHub </a>so make the code look nice :).</p><p>In this tutorial, I’m connecting to the DB using the username and password.</p><p><strong>Step 1: Create the database and get the credentials</strong></p><p>You can use any service you like to create the DB. Once the DB is ready, create a .env file and add the credentials there.</p><pre>DB_PORT=3306<br>DB_NAME=test_db<br>DB_HOST=localhost<br>DB_USER=root<br>DB_PASS=password</pre><p>Add the following line to the serverless.yml file to load the env variables. Also, note that I’ve changed the frameworkVersion to be “3” in line #2.</p><pre>useDotenv: true</pre><p><strong>Step 2: Install the dependencies for the DB connection.</strong></p><p>In this step, I’m going to install knex, objection and mysql2 from npm library.</p><pre>npm i knex objection mysql2 dotenv</pre><p><strong>Step 3: Connecting to the DB</strong></p><p>To connect to the DB, create the following files:</p><p>Create a file in /db/knex.js and add the following content:</p><pre>const <strong><em>config </em></strong>= require(&#39;../knexfile&#39;);<br><br>module.exports = require(&#39;knex&#39;)(<strong><em>config</em></strong>);</pre><p>Create a file in /db/connection.js and add following content:</p><pre>require(&#39;dotenv&#39;).config();<br><br>const <strong><em>connection </em></strong>= {<br>  port: <strong><em>process</em></strong>.env.DB_PORT,<br>  host: <strong><em>process</em></strong>.env.DB_HOST,<br>  user: <strong><em>process</em></strong>.env.DB_USER,<br>  password: <strong><em>process</em></strong>.env.DB_PASS,<br>  database: <strong><em>process</em></strong>.env.DB_NAME,<br>};<br>module.exports = <strong><em>connection</em></strong>;</pre><p>Create a /db/migrations folder to save out migrations.</p><p>Create a knexfile.js in the root folder and add the following content:</p><pre>const <strong><em>connection </em></strong>= require(&#39;./db/connection&#39;);<br><br><em>/**<br> * </em><strong><em>@type </em></strong><em>{ Object.&lt;string, import(&quot;knex&quot;).Knex.Config&gt; }<br> */<br></em>module.exports = {<br>  client: &#39;mysql2&#39;,<br>  pool: {<br>    min: 1,<br>    max: 1,<br>  },<br>  <strong><em>connection</em></strong>,<br>  migrations: {<br>    directory: `${__dirname}/db/migrations`,<br>    tableName: &#39;knex_migrations&#39;,<br>  },<br><br>};</pre><p>That’s it. The application is connected to the Database now.</p><p><strong>Step 4: Creating the migrations</strong></p><p>Add following lines to the “scripts” section in package.json to create migrations using knex:</p><pre>&quot;scripts&quot;: {<br>  &quot;dev&quot;: &quot;serverless offline --httpPort 2999&quot;,<br>  <strong>&quot;knex&quot;: &quot;knex&quot;,<br>  &quot;migrate&quot;: &quot;knex migrate:latest&quot;,<br>  &quot;db-rollback&quot;: &quot;knex migrate:rollback&quot;,</strong><br>  &quot;test&quot;: &quot;echo <strong>\&quot;</strong>Error: no test specified<strong>\&quot;</strong> &amp;&amp; exit 1&quot;<br>},</pre><p>Create the migration file by running the following command:</p><pre>knex migrate:make creating-test-table</pre><p>This will create the migration file in /db/migrations folder. Modify the content of the file as below to create a test table:</p><pre>exports.up = function (knex) {<br>  return knex.schema.createTable(&quot;vehicles&quot;, (table) =&gt; {<br>    table.increments(&quot;id&quot;);<br>    table.string(&quot;name&quot;).notNullable();<br>    table.timestamp(&quot;createdAt&quot;).defaultTo(knex.fn.now());<br>  });<br>};<br><em><br></em>exports.down = function (knex) {<br>  return knex.schema.dropTable(&quot;vehicles&quot;);<br>};</pre><p>Finally, run the following command to run the migrations:</p><pre>npm run migrate</pre><p><strong>Step 5: Create the models</strong></p><p>Create a folder in the root directory and rename it to “models”. This is where we save our models.</p><p>Create /models/Test.js file and add the following content:</p><pre>const { <strong>Model </strong>} = require(&quot;objection&quot;);<br><br>module.exports = class <strong>TestTable </strong>extends <strong>Model </strong>{<br>  static get <em>tableName</em>() {<br>    return &quot;test_table&quot;;<br>  }<br>};</pre><p>Create /models/index.js and add the following content:</p><pre>const <strong>TestTable </strong>= require(&quot;./TestTable&quot;);<br><br>module.exports = {<br>  <strong>TestTable</strong>,<br>};</pre><p>Create a file in /middlewares/useModels.js to load the Models to the functions:</p><pre>const { <strong>Model </strong>} = require(&#39;objection&#39;);<br>const Knex = require(&#39;knex&#39;);<br>const <strong><em>models </em></strong>= require(&#39;../models&#39;);<br>const <strong><em>connection </em></strong>= require(&#39;../db/connection&#39;);<br><br>module.exports = () =&gt; {<br>  const customMiddlewareBefore = async (handler) =&gt; {<br>    const knexConfig = Knex({<br>      client: &#39;mysql2&#39;,<br>      <strong><em>connection</em></strong>,<br>    });<br>    await <strong>Model</strong>.<em>knex</em>(knexConfig);<br>    handler.event.models = <strong><em>models</em></strong>;<br>  };<br>  const customMiddlewareAfter = async () =&gt; {<br>    await <strong>Model</strong>.<em>knex</em>().destroy();<br>  };<br>  const customMiddlewareOnError = async () =&gt; {<br>     // on error<br>  };<br><br>  return {<br>    before: customMiddlewareBefore,<br>    after: customMiddlewareAfter,<br>    onError: customMiddlewareOnError,<br>  };<br>};</pre><p><strong>Step 6: Access the data using the model in the handler</strong></p><p>Import the middleware, wrap with middy and fetch data:</p><pre>const <strong><em>middy </em></strong>= require(&quot;middy&quot;);<br>const { jsonBodyParser, httpErrorHandler } = require(&quot;middy/middlewares&quot;);<br><strong><em>const useModels = require(&quot;../../middlewares/useModels&quot;);</em></strong><br><br>const handler = async (event, context) =&gt; {<br>  <strong><em>const { TestTable } = event.models;<br>  const testData = await TestTable.query();</em></strong><br><br>  return { statusCode: 200, body: JSON.stringify(testData) };<br>};<br><br>// Adding middlewares from middy.<br>module.exports.endpoint = middy(handler)<br>  .use(jsonBodyParser())<br><strong><em>  .use(useModels())</em></strong><br>  .use(httpErrorHandler()); //</pre><p>This is the minimum setup to connect to a DB using Models. You can refer to the documentation of <a href="https://vincit.github.io/objection.js/guide/getting-started.html">objection </a>to extend the functionality of your service.</p><p>When you deploy, make sure to add the DB credentials to the env variables of the CodeBuild project in AWS.</p><p>The final code is available on <a href="https://github.com/maheshsamudra/sample-aws-serverless-project/tree/going-serverless-part-3">GitHub</a>. Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=416a714a91f8" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/going-serverless-part-3-416a714a91f8">Going Serverless — Part 3</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going Serverless — Part 2]]></title>
            <link>https://awstip.com/going-serverless-part-2-cdb6acb0ebef?source=rss-49dba213ad46------2</link>
            <guid isPermaLink="false">https://medium.com/p/cdb6acb0ebef</guid>
            <category><![CDATA[getting-started]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Mahesh Samudra]]></dc:creator>
            <pubDate>Sat, 02 Oct 2021 12:22:20 GMT</pubDate>
            <atom:updated>2022-07-26T14:01:53.598Z</atom:updated>
            <content:encoded><![CDATA[<h3>Going Serverless — Part 2</h3><p>This is the second article in this series. The first article explains how to set up a serverless project locally. If you haven’t already, <a href="https://medium.com/@maheshsamudra/going-serverless-part-1-f3b2ea778d1d">please read it first</a>.</p><p>In this article, I’m going to explain how to deploy the API that we built to AWS with CI.</p><figure><img alt="Deploying serverless API to AWS" src="https://cdn-images-1.medium.com/max/800/1*Ta8YW88D_WiL7c6eLHldjQ.png" /><figcaption>image: <a href="https://www.serverless.com/blog/serverless-framework-v2">https://www.serverless.com/blog/serverless-framework-v2</a></figcaption></figure><p>Before start, you need to make sure that</p><ol><li>You have an AWS account. If you don’t have one, please create an <a href="https://aws.amazon.com/">account in AWS</a>.</li><li>You have your code in a remote repository. For this example, I’m using <a href="https://github.com/maheshsamudra/sample-aws-serverless-project/tree/going-serverless-part-1">this code</a> from GitHub.</li></ol><p>Before getting started with AWS settings, we will create a file that instructs AWS on how to build the project. Create a file named “buildspec.yml” in the project’s root folder and paste the following:</p><pre>version: 0.2<br><br>phases:<br>  install:<br>    runtime-versions:<br>      nodejs: 14<br>    commands:<br>      - npm install -g serverless<br>  pre_build:<br>    commands:<br>      - npm install<br>  build:<br>    commands:<br>      - serverless deploy</pre><p>This file tells AWS to install NodeJS 14, then install serverless globally, and then deploy it.</p><p>Now that we are ready, log in to AWS account. Before setting up our CodeBuild project, we need to create a role. Search “iam” from the top search bar. From the left menu, select “Roles” and click “Create role”</p><p>The first step is to add the type. Select “AWS service” and select Lambda.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/987/1*dbChvRw0YfKGF1jykDdqqw.png" /></figure><p>Next step is to set permissions — search and select AdministratorAccess</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/988/1*VaeqfaQSqml9qzdZ_motpw.png" /></figure><p>Tags section — you can skip this section</p><p>Review section — you need to add a name to the role and click on “Create role”. Now you are ready to create the CI with CodeBuild. Search “CodeBuild.” from the top search bar and go there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*Kcjx89m1r4XqertT34p1Xg.png" /></figure><p>Click on the orange button that reads “Create Build Project”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*bOLoRNNstW8iQMBCTpFJsg.png" /></figure><p>The next page has a couple of sections:</p><p><strong>Project Configuration</strong> — This is basically to identify the project. Add a name and a description.</p><p><strong>Source </strong>— This is where you link your remote repository. For my project, I’m selecting GitHub. Then, make sure you have Connect using Oauth selected and click on “Connect to GitHub” to grant read-only access. Once connected, You can search and select the repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*nHPA-TA3QIVdaAKs6KzK5Q.png" /></figure><p><strong>Primary source webhook events</strong> — This is the section where you enable CI. For this project, I’m setting it up so that this will build and deploy the project for each push made to the “main” branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*kMverTGt2pLy6lpYOHTj-Q.png" /></figure><p>Environment — This is the section to select the environment that builds and deploys the code. In the role name, make sure to select the role that we created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*UJA1-XM9nztiGjdAPfyYfA.png" /></figure><p><strong>Buildspec </strong>— Select “Use a buildspec file” and keep others as they are. This will tell CodeBuild to use the buildspec.yml file that we created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*N06VS9RP71_lhM2BnACocQ.png" /></figure><p>Batch Configuration — No need to change anything for now.</p><p>Artifacts — No need to change anything for now.</p><p>Logs — Keep the “CloudWatch logs ” checkbox checked.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/812/1*1U7HMrsADUf1qYQoPQyrGw.png" /></figure><p>That’s it. You have successfully created your CI build for the serverless project. On the next page, click on “Start Build” and it will deploy your project.</p><p>Once the build is complete, go to Build Logs and scroll all the way to the bottom. There, you will see the endpoints for your two functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*-w1oO1fLQGP52q0EwXImrw.png" /></figure><p>That’s it. You have successfully deployed the project. Every time you push new changes to the “main” branch, AWS CodeBuild will build the project and update these endpoints.</p><p>The code related to this article is available on <a href="https://github.com/maheshsamudra/sample-aws-serverless-project/tree/going-serverless-part-2">GitHub</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cdb6acb0ebef" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/going-serverless-part-2-cdb6acb0ebef">Going Serverless — Part 2</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going Serverless — Part 1]]></title>
            <link>https://awstip.com/going-serverless-part-1-f3b2ea778d1d?source=rss-49dba213ad46------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3b2ea778d1d</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[getting-started]]></category>
            <dc:creator><![CDATA[Mahesh Samudra]]></dc:creator>
            <pubDate>Fri, 01 Oct 2021 18:16:15 GMT</pubDate>
            <atom:updated>2022-07-26T14:01:48.637Z</atom:updated>
            <content:encoded><![CDATA[<h3>Going Serverless — Part 1</h3><p>The goal of this article series is to get started with Serverless. During the series, you will learn how to build an application locally and deploy it to AWS with CI.</p><figure><img alt="Going Serverless" src="https://cdn-images-1.medium.com/max/800/1*Ta8YW88D_WiL7c6eLHldjQ.png" /><figcaption>image: <a href="https://www.serverless.com/blog/serverless-framework-v2">https://www.serverless.com/blog/serverless-framework-v2</a></figcaption></figure><p>For this example, I’m using NodeJS to create an HTTP API. I assume that you already have NodeJS installed. If not, you can download the LTS version of Node for the <a href="https://nodejs.org/en/download/">downloads page</a>.</p><p><em>Note: I’m using NodeJS 14.17.6 and serverless V2 for this project.</em></p><p><strong>Step 1: Install Serverless globally</strong></p><pre>npm install -g serverless</pre><p>Once installed, you are ready to get started.</p><p><strong>Step 2: Create the serverless project</strong></p><pre>serverless</pre><p>Once you run the above command, it will ask you some questions to get started. For this example, I’m using below:</p><ol><li>What do you want to make?<br>AWS — Node.js — HTTP API</li><li>What do you want to call this project?<br>sample-aws-serverless-project (This is the name of the project. You can use any name you like.)</li><li>Do you want to login/register to Serverless Dashboard?<br>No</li><li>Do you want to deploy your project?<br>No (We will set this up with AWS)</li></ol><p>Great. You have now set up the serverless framework. You will see 4 files inside your new project, and let’s focus on two files.</p><ul><li><strong>serverless.yml — </strong>This file contains all functions and infrastructure resources of the project.</li></ul><pre>service: sample-aws-serverless-project<br>frameworkVersion: &#39;2&#39;<br><br>provider:<br>  name: aws<br>  runtime: nodejs12.x<br>  lambdaHashingVersion: &#39;20201221&#39;<br><br>functions:<br>  hello:<br>    handler: handler.hello<br>    events:<br>      - httpApi:<br>          path: /<br>          method: get</pre><p>All the endpoints are listed under functions:. When the project is set up, it has one function included as an example.</p><ul><li>hello: — this is the example function, which will be the first endpoint in our app. You can change this to whatever you like.</li><li>handler: — This indicates the location of the function to be executed when a request is made to the endpoint. The file path is related to the root directory.</li><li>events: — This indicates how this function can be triggered. In this case, the endpoint named “hello” can be called by a GET request to /</li></ul><p><em>Note: In the provider section, the runtime is indicated as nodejs12.x. You can change it to nodejs14.x which is the LTS at the time of writing.</em></p><ul><li><strong>handler.js — </strong>This is the file that includes function that executes when you make a GETrequest to /</li></ul><p><strong>Step 3: Add offline support for development</strong></p><p>After setting up serverless, we need to get it up and running locally for development. To do that, we will create a package.json file and install serverless-offline.</p><pre>npm init -y</pre><pre>npm i -D serverless-offline</pre><p>Now, we need to add the following lines to your serverless.yml file.</p><pre>plugins:<br>  - serverless-offline</pre><p>Now, your serverless.yml should look like this:</p><pre>service: sample-aws-serverless-project<br>frameworkVersion: &#39;2&#39;<br><br>provider:<br>  name: aws<br>  runtime: nodejs14.x<br>  lambdaHashingVersion: &#39;20201221&#39;<br><br>plugins:<br>  - serverless-offline<br><br>functions:<br>  hello:<br>    handler: handler.hello<br>    events:<br>      - httpApi:<br>          path: /<br>          method: get</pre><p><strong>Step 4: See it in action</strong></p><p>Now the project is ready for local development. Run the following command to start serverless locally.</p><pre>serverless offline</pre><p>Open your browser and go to <a href="http://localhost:3000/">http://localhost:3000</a> and you will see the output from your first serverless function.</p><p><strong>Step 5: Adding one more endpoint</strong></p><p>First, we will add some new lines to the serverless.yml file. The new code starts with mySecondFunction:.</p><pre>service: sample-aws-serverless-project<br>frameworkVersion: &#39;2&#39;<br><br>provider:<br>  name: aws<br>  runtime: nodejs14.x<br>  lambdaHashingVersion: &#39;20201221&#39;<br><br>plugins:<br>  - serverless-offline<br><br>functions:<br>  hello:<br>    handler: handler.hello<br>    events:<br>      - httpApi:<br>          path: /<br>          method: get<br><strong>  </strong>mySecondFunction: <em># function/endpoint name<br>    </em>handler: mySecondFunction.hello <em># where the function is located<br>    </em>events:<br>      - httpApi:<br>          path: /my-second-function <em># what is the endpoint<br>          </em>method: get</pre><p>Now create a file named mySecondFunction.js and add the following lines: (Basically, the content is the same as hello.js. I just changed the message and removed the input: event line.)</p><pre>&quot;use strict&quot;;<br><br>module.exports.hello = async (event) =&gt; {<br>    return {<br>        statusCode: 200,<br>        body: JSON.stringify(<br>            {<br>                message: &quot;My second function&quot;,<br>            },<br>            null,<br>            2<br>        ),<br>    };<br>};</pre><p><strong>Step 6: Test it.</strong></p><p>Stop the server and restart it by running serverless offline</p><p>Open your browser and go to <a href="http://localhost:3000/my-second-function">http://localhost:3000/my-second-function</a> and you will see the output from your second serverless function.</p><p><em>Note that whenever you make a change to the serverless.yml file, you need to restart the server.</em></p><p><strong>What’s next?</strong></p><p>Now that you have successfully set up the project locally, you can continue to develop it. In the <a href="https://maheshsamudra.medium.com/going-serverless-part-2-cdb6acb0ebef">next article</a>, I will guide you to deploy this application to AWS using CodeBuild.</p><p>Things to do before the next article:</p><ol><li>Refactor the code. The refactored code example is available in <a href="https://github.com/maheshsamudra/sample-aws-serverless-project/tree/going-serverless-part-1">GitHub</a>.</li><li>Upload the code to a remote repository.</li></ol><p><a href="https://maheshsamudra.medium.com/going-serverless-part-2-cdb6acb0ebef">Next: Going Serverless — Part 2: Deploy the serverless application to AWS</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3b2ea778d1d" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/going-serverless-part-1-f3b2ea778d1d">Going Serverless — Part 1</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>