<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Rajan Prasad</title>
    <description>The latest articles on DEV Community by Rajan Prasad (@rajandmr).</description>
    <link>https://dev.to/rajandmr</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F387353%2F4f95b7c2-c016-483b-be8a-9f7ffb148ccd.jpeg</url>
      <title>DEV Community: Rajan Prasad</title>
      <link>https://dev.to/rajandmr</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rajandmr"/>
    <language>en</language>
    <item>
      <title>Creating APIs with NodeJS, DynamoDB and AWS Lambda: A better workflow with dynamoose</title>
      <dc:creator>Rajan Prasad</dc:creator>
      <pubDate>Fri, 22 Jan 2021 05:40:46 +0000</pubDate>
      <link>https://dev.to/rajandmr/creating-apis-with-nodejs-dynamodb-and-aws-lambda-a-better-workflow-with-dynamoose-1l1o</link>
      <guid>https://dev.to/rajandmr/creating-apis-with-nodejs-dynamodb-and-aws-lambda-a-better-workflow-with-dynamoose-1l1o</guid>
      <description>&lt;p&gt;In this article, we'll create CRUD APIs with AWS Lambda and NodeJS and we'll be using &lt;br&gt;
 &lt;a href="https://dynamoosejs.com/getting_started/Introduction" rel="noopener noreferrer"&gt;Dynamoose&lt;/a&gt; to get better understanding of our DB model and to have a better workflow since Dynamoose takes away the pain of writing CloudFormation code for the DynamoDB table and other hassles. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Prerequisite&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;I assume you've AWS account&lt;/li&gt;
&lt;li&gt;You also should've node, npm and serverless installed. If you don't have serverless installed, you can install it through npm using

&lt;code&gt;npm i -g serverless&lt;/code&gt;
&lt;/li&gt;
&lt;/ul&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Since we'll be using Serverless Framework for deploying our stack, you've set-up the credentials with AWS. If not, Head towards the  &lt;a href="https://www.serverless.com/framework/docs/providers/aws/guide/installation/" rel="noopener noreferrer"&gt;Serverless Documentation&lt;/a&gt; do the quick set-up.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Here's the file structure we'll be using:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1611287802611%2Ft8Grxw3hT.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1611287802611%2Ft8Grxw3hT.jpeg" alt="filestruct.JPG"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Getting Started&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We need to generate a simple template serverless CLI. In order to do so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;sls create -t aws-nodejs
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, Navigate into the directory and delete the &lt;em&gt;handler.js&lt;/em&gt; file since we'll be creating our own handler.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Folder structure set-up&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;First create 3 new directories namely &lt;strong&gt;functions&lt;/strong&gt;, &lt;strong&gt;helper&lt;/strong&gt;, and &lt;strong&gt;Model&lt;/strong&gt;
&lt;/li&gt;
&lt;li&gt;Inside the the functions directory, create another directory namely users&lt;/li&gt;
&lt;li&gt;Inside the helper directory, create two files, &lt;em&gt;error.js&lt;/em&gt; and &lt;em&gt;success.js&lt;/em&gt;
&lt;/li&gt;
&lt;li&gt;Inside Model directory, create a new file called &lt;em&gt;UserModel.js&lt;/em&gt;
&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;APIs List&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We'll be creating following 5 APIs related to users.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;createUser&lt;/li&gt;
&lt;li&gt;getAllUsers&lt;/li&gt;
&lt;li&gt;getUserById&lt;/li&gt;
&lt;li&gt;updateUser&lt;/li&gt;
&lt;li&gt;deleteUser&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Installing required packages:&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We need some npm packages in order to get our code working. so run the following command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i dynamoose uuid
npm i aws-sdk -D
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Setting up CloudFormation code:&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Open the Serverless.yml file and paste the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;service: dynamo-tut

provider:
  name: aws
  runtime: nodejs12.x
  region: us-east-1
  profile: personal #Replace it with your own profile name


  iamRoleStatements:
    - Effect: Allow
      Action:
        - dynamodb:DescribeTable
        - dynamodb:Query
        - dynamodb:Scan
        - dynamodb:GetItem
        - dynamodb:PutItem
        - dynamodb:UpdateItem
        - dynamodb:DeleteItem
        - dynamodb:CreateTable
      Resource: '*'

functions:
  writeToDB:
    handler: functions/users/createUser.main
    events:
      - http:
          path: addUser
          method: post
          cors: true

  getAllUsers:
    handler: functions/users/getAllUsers.main
    events:
      - http:
          path: getAll
          method: get
          cors: true

  getUserById:
    handler: functions/users/getUserById.main
    events:
      - http:
          path: getOne
          method: get
          cors: true

  updateUser:
    handler: functions/users/updateUser.main
    events:
      - http:
          path: update
          method: put
          cors: true

  deleteUser:
    handler: functions/users/deleteUser.main
    events:
      - http:
          path: delete
          method: delete
          cors: true
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We're doing just basic stuffs, setting up provider details, AWS IAM Permissions for our lamba functions and then defining the handler for our functions with API Gateway attached.&lt;/p&gt;

&lt;p&gt;Now, paste the following code in &lt;em&gt;error.js&lt;/em&gt; and &lt;em&gt;success.js&lt;/em&gt; inside &lt;strong&gt;helper&lt;/strong&gt; directory&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// success.js
const getSuccessResponse = (info) =&amp;gt; {
  return {
    statusCode: 200,
    headers: {
      'Content-Type': 'application/json',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Credentials': true,
    },
    body: JSON.stringify({
      message: 'Request approved for performing operation',
      data: info,
      success: true,
    }),
  };
};

module.exports = { getSuccessResponse };

// error.js
const getErrorResponse = (info) =&amp;gt; {
  console.log(info);
  return {
    statusCode: info.statusCode || 500,
    headers: {
      'Content-Type': 'text/plain',
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Credentials': true,
    },
    body: JSON.stringify(info),
  };
};

module.exports = { getErrorResponse };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;These functions ensures that our functions contains the response headers and cors policy so that our front-end will not have any issues. We'll use these helper functions to throw out responses.&lt;/p&gt;

&lt;p&gt;Now, we need to define the Model which will be then used by Dynamoose to create DDB tables under the hood.&lt;/p&gt;

&lt;p&gt;Create a file &lt;em&gt;Models/UserModel.js&lt;/em&gt; and paste the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const dynamoose = require('dynamoose');

const schema = new dynamoose.Schema(
  {
    id: {
      type: String,
      hashKey: true,
    },
    name: String,
    age: Number,
  },
  {
    timestamps: true,
  }
);

const UsersModel = dynamoose.model('userstable', schema, {
  create: true,
  throughput: {
    read: 5,
    write: 5,
  },
});
module.exports = { UsersModel };
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, for the handler part, create 5 files inside &lt;strong&gt;functions/users&lt;/strong&gt; and paste the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// createUser.js

'use strict';

const { getSuccessResponse } = require('../../helper/success');
const { getErrorResponse } = require('../../helper/error');

const { v4: uuidv4 } = require('uuid');
const { UsersModel } = require('../../Models/UserModel');

module.exports.main = async (event) =&amp;gt; {
  try {
    const request = JSON.parse(event.body);
    const { name, email } = request;

    const result = await UsersModel.create({
      id: uuidv4(),
      name,
      email,
    });

    return getSuccessResponse(result);
  } catch (error) {
    console.log(error);
    return getErrorResponse(error);
  }
};

// getAllUsers.js

'use strict';

const { getSuccessResponse } = require('../../helper/success');
const { getErrorResponse } = require('../../helper/error');

const { UsersModel } = require('../../Models/UserModel');

module.exports.main = async (event) =&amp;gt; {
  try {
    const result = await UsersModel.scan().exec();
    return getSuccessResponse(result);
  } catch (error) {
    return getErrorResponse(error);
  }
};

// getUserById.js

'use strict';
const { getSuccessResponse } = require('../../helper/success');
const { getErrorResponse } = require('../../helper/error');

const { UsersModel } = require('../../Models/UserModel');

module.exports.main = async (event) =&amp;gt; {
  try {
    const queryStringParameters = event.queryStringParameters;
    const { id } = queryStringParameters;

    const result = await UsersModel.get({ id });
    return getSuccessResponse(result);
  } catch (error) {
    return getErrorResponse(error);
  }
};

// updateUser.js

'use strict';

const { getSuccessResponse } = require('../../helper/success');
const { getErrorResponse } = require('../../helper/error');

const { UsersModel } = require('../../Models/UserModel');

module.exports.main = async (event) =&amp;gt; {
  try {
    const request = JSON.parse(event.body);
    const { id, ...data } = request;

    const result = await UsersModel.update({ id }, { ...data });
    return getSuccessResponse(result);
  } catch (error) {
    return getErrorResponse(error);
  }
};

// deleteUser.js

'use strict';

const { getSuccessResponse } = require('../../helper/success');
const { getErrorResponse } = require('../../helper/error');

const { UsersModel } = require('../../Models/UserModel');

module.exports.main = async (event) =&amp;gt; {
  try {
    const request = JSON.parse(event.body);
    const { id } = request;

    const result = await UsersModel.delete({ id });
    return getSuccessResponse(result);
  } catch (error) {
    return getErrorResponse(error);
  }
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Deployment&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;For deployment, the following command will deploy the stack on AWS and return the endpoints for all the functions:&lt;br&gt;
&lt;/p&gt;

&lt;p&gt;&lt;code&gt;sls deploy -v&lt;/code&gt;&lt;br&gt;
&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Testing&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Once the deployment is complete, you'll find the endpoints in the output section of your terminal. Copy and paste those endpoints on Postman and hit with appropriate params and payload. If you've followed everything correctly, it will return you with results.&lt;/p&gt;

&lt;p&gt;Here's the  &lt;a href="https://github.com/rajandmr/dynamodb-dynamoose-node" rel="noopener noreferrer"&gt;Repo&lt;/a&gt;  with complete code written and tested.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Subscribe&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If you like reading what i write, consider subscribing to the newsletter so you won't miss any stories.&lt;/p&gt;

</description>
      <category>node</category>
      <category>aws</category>
      <category>dynamodb</category>
    </item>
    <item>
      <title>Publishing private NPM package for free</title>
      <dc:creator>Rajan Prasad</dc:creator>
      <pubDate>Sun, 27 Dec 2020 05:26:56 +0000</pubDate>
      <link>https://dev.to/rajandmr/publishing-private-npm-package-for-free-nd7</link>
      <guid>https://dev.to/rajandmr/publishing-private-npm-package-for-free-nd7</guid>
      <description>&lt;p&gt;If you're avid JS developer then You must be using &lt;em&gt;npm&lt;/em&gt; daily to daily basis. NPM has become a home for millions of packages. In today's article, we're going to publish a private NPM package to GitHub. If we were to publish private package to NPM directly, we'll have to upgrade to one of the  &lt;a href="https://www.npmjs.com/products"&gt;Paid Plans&lt;/a&gt; of NPM but GitHub allows us to do the same thing for &lt;strong&gt;free&lt;/strong&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Prerequisite&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I assume you have basic working knowledge of Git and NodeJS and a GitHub Account Of course.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Getting Started&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We'll start by creating a folder for our package and initializing npm in the directory. To do so:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir gh-package
cd gh-package
npm init -y
touch index.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can rename the directory anything you want, in my case it's a github package so i'm naming it gh-package. Now, you should go to &lt;strong&gt;package.json&lt;/strong&gt; file and edit it as follow:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
  "name": "@userName/gh-package",
  "version": "1.0.0",
  "description": "Package for trying out GITHUB Package Registry",
  "main": "index.js",
  "publishConfig": {
    "registry": "https://npm.pkg.github.com/@userName"
  },
  "scripts": {
    "start": "node index.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can customize it in anyway you like but make sure to replace the &lt;strong&gt;userName&lt;/strong&gt; with your valid github username. If i've my github username &lt;strong&gt;dmr&lt;/strong&gt; i'll edit it as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;...
"name": "@dmr/gh-package"
...
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Also, instead of &lt;strong&gt;gh-package&lt;/strong&gt;, it should be same as your package name.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Writing Sample package code&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, let's write some code. In order to keep things simple, i'm going to write a very simple function which will take a string as parameter and will return &lt;strong&gt;Hello *String&lt;/strong&gt;*&lt;/p&gt;

&lt;p&gt;Replace the index.js with the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const sayHello = (name) =&amp;gt; {
  console.log('Hello ' + name + '!');
};

module.exports = {
  sayHello,
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Creating repo &amp;amp; Setting up GitHub Access Token&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now in order to publish our package we'll need a github repo and  have to run GitHub Actions. So head to the  &lt;a href="https://github.com/"&gt;GitHub&lt;/a&gt;  and create a repo and name it as the same name you want to name your package. You can make it public however I suggest to make it private. Now once repo is created you should be able to commit the current code and push it to the repo. I'm not going to guide you through that part.&lt;/p&gt;

&lt;p&gt;Now as I already mentioned, we need to run github actions and in order to do so, we need to create Access Token. In order to do so, head over to your github page go to Settings -&amp;gt; Developer Settings -&amp;gt; Personal Access Tokens -&amp;gt; Generate new token&lt;/p&gt;

&lt;p&gt;You should tick the following permissions:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;workflow&lt;/li&gt;
&lt;li&gt;write: packages&lt;/li&gt;
&lt;li&gt;delete: packages&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Once done, it will provide you with a token. You need to keep the token safe as we will need that token in order to install the package as well since it's going to be private package.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Adding Secret to GitHub Repo&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, the generated token should be considered as critical entity and should be kept safe. Hence we need to create a secret to our repository. Repository Secrets allows us to use variables without exposing it to the code, just like environment variables in Heroku. So head over to the repo created for this project -&amp;gt; Settings -&amp;gt; Secrets -&amp;gt; New repository secret.&lt;/p&gt;

&lt;p&gt;You can name the secret anything but make sure to use it the same name as in our workflow. In my case i'll be naming it &lt;strong&gt;MY_GITHUB_TOKEN&lt;/strong&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Creating GH Actions workflow&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;We're almost done, the last thing we need to do is add github actions workflow to our repo. In order to do so, we need to create a folder called &lt;em&gt;.github&lt;/em&gt; in our root folder and inside that another folder called &lt;em&gt;workflows&lt;/em&gt; and lastly a file called &lt;strong&gt;action.yml&lt;/strong&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir .github
mkdir .github/workflows
touch .github/workflows/action.yml
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now add the following code to &lt;strong&gt;action.yml&lt;/strong&gt; file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;name: Build and Deploy

on:
  push:
    branches:
      - main

jobs:
  publish-gpr:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-node@v1
        with:
          node-version: 12
          registry-url: https://npm.pkg.github.com/
          scope: '@userName'
      - run: npm install
      - run: npm publish
        env:
          NODE_AUTH_TOKEN: ${{secrets.MY_GITHUB_TOKEN}}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replace the &lt;em&gt;userName&lt;/em&gt; in scope with your own github userName and *MY_GITHUB_TOKEN with the secret you named while adding secret to the repo&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Pushing and Publising the package&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now the final step is to commit all the changes and push it to the github. Once we do so, you can go to the package repo -&amp;gt; Actions and see the build process kicking off. Once the build is completed you'll be able to see your package by going to your Profile -&amp;gt; Packages. &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Testing the published package&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now we need to see our published package in action, i mean that's the whole point of publishing an package. In order to do so, You have to create a folder let's call it &lt;em&gt;package-test&lt;/em&gt; and navigate into that folder and init npm. Now we need to create a file called .npmrc and paste the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@YOUR_USERNAME:registry=https://npm.pkg.github.com/
//npm.pkg.github.com/:_authToken=YOUR_TOKEN
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Replace the YOUR_USERNAME and YOUR_TOKEN with your github username and the generated token. Now you can install the package by running:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm i @YOUR_USERNAME/PACKAGENAME
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;now create a file called &lt;em&gt;index.js&lt;/em&gt; and replace it with following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let demoPackage = require('@username/gh-package');

demoPackage.sayHello('World');
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And run it, and the package will return &lt;em&gt;Hello World&lt;/em&gt;&lt;br&gt;
The package code can be found on my  &lt;a href="https://github.com/rajandmr/gh-package"&gt;Github Repo&lt;/a&gt; &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Thanks for Reading.&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>npm</category>
      <category>node</category>
      <category>github</category>
    </item>
    <item>
      <title>Setting up Redux store in Your React application</title>
      <dc:creator>Rajan Prasad</dc:creator>
      <pubDate>Sat, 14 Nov 2020 11:04:32 +0000</pubDate>
      <link>https://dev.to/rajandmr/setting-up-redux-store-in-your-react-application-1mfe</link>
      <guid>https://dev.to/rajandmr/setting-up-redux-store-in-your-react-application-1mfe</guid>
      <description>&lt;p&gt;State management is one of the most important portion of any Front end development framework. Almost every FE framework offers one or many state management libraries. For example,  &lt;a href="https://github.com/reduxjs/redux" rel="noopener noreferrer"&gt;Redux&lt;/a&gt; &amp;amp;  &lt;a href="https://recoiljs.org/docs/introduction/installation" rel="noopener noreferrer"&gt;Recoil&lt;/a&gt;  for React,  &lt;a href="https://github.com/vuejs/vuex" rel="noopener noreferrer"&gt;Vuex&lt;/a&gt; for VueJS and  &lt;a href="https://ngrx.io/guide/store" rel="noopener noreferrer"&gt;NgRx&lt;/a&gt; for Angular. In this article, we're going to create a very simple Reading List application which will have a redux store set up and we will be using  &lt;a href="https://fakerapi.it/en" rel="noopener noreferrer"&gt;FakerAPI&lt;/a&gt; for the mock response. &lt;/p&gt;

&lt;p&gt;You can checkout the demo application  &lt;a href="https://reading-list-redux.vercel.app" rel="noopener noreferrer"&gt;Here&lt;/a&gt; .&lt;br&gt;
Also, the source-code can be found  &lt;a href="https://github.com/rajandmr/Reading-List-Redux" rel="noopener noreferrer"&gt;Here&lt;/a&gt; on my GitHub. It is very basic application which fetches books from FakerAPI and you'll also be able to add Books.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Prerequisite&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;I assume that you already have a good understanding of React Components, Props &amp;amp; states(in general). &lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Getting Started&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;So we start simple by creating a React application using CRA and installing required dependencies afterwards.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;create-react-app reading-list
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will generate the react application. Now, navigate into the newly created application and install the dependencies using&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd reading-list
npm install redux react-redux redux-thunk redux-devtools-extension axios
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, few things to note here, redux alone is independent of any frameworks. &lt;em&gt;react-redux&lt;/em&gt; is what let us use redux for react application. Also, we need some kind of middleware, &lt;em&gt;redux-thunk&lt;/em&gt; in our case for basic Redux side effects logic, including complex synchronous logic that needs access to the store, and simple async logic like AJAX requests since With a plain basic Redux store, you can only do simple synchronous updates by dispatching an action. Middleware extends the store's abilities, and lets you write async logic that interacts with the store.&lt;/p&gt;

&lt;p&gt;Also, &lt;em&gt;redux-devtools-extension&lt;/em&gt; makes it easy to integrate &lt;em&gt;Redux DevTools&lt;/em&gt; which speeds up our app debugging process. &lt;em&gt;Axios&lt;/em&gt; works great for fetching data from the apis.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Folder Structure&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, let's take a look at our folder structure&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1605350225381%2FQ0tA1Wdgm.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1605350225381%2FQ0tA1Wdgm.jpeg" alt="folder-structure.JPG"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;We'll create 3 folders &lt;em&gt;actions&lt;/em&gt; , &lt;em&gt;components&lt;/em&gt; &amp;amp; &lt;em&gt;reducers&lt;/em&gt; inside our &lt;em&gt;src&lt;/em&gt; folder. Inside the components folder, we'll create 3 components, &lt;em&gt;BookList&lt;/em&gt; for looping through the List of Books, &lt;em&gt;BookForm&lt;/em&gt; for adding a new Book &amp;amp; &lt;em&gt;BookDetail&lt;/em&gt; for displaying each book's Detail.&lt;/p&gt;

&lt;p&gt;Inside &lt;em&gt;reducers&lt;/em&gt; folder, we'll have 2 files, &lt;em&gt;index.js&lt;/em&gt; which will be our rootReducer &amp;amp; &lt;em&gt;bookReducer&lt;/em&gt;.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Setting up the store&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In order to set up the store, replace the &lt;em&gt;src/index.js&lt;/em&gt; file with&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

// Imports for Redux
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';

// root reducer import
import rootReducer from './reducers';

const store = createStore(
  rootReducer,
  composeWithDevTools(applyMiddleware(thunk))
);

ReactDOM.render(
  &amp;lt;Provider store={store}&amp;gt;
    &amp;lt;App /&amp;gt;
  &amp;lt;/Provider&amp;gt;,
  document.getElementById('root')
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Creating components&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Since the store has been set up, we can start writing our components. Add the following code to build up our components:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/components/BookDetail.js
import React from 'react';

const BookDetails = ({ book }) =&amp;gt; {
  return (
    &amp;lt;li&amp;gt;
      &amp;lt;div className="title"&amp;gt;{book.title}&amp;lt;/div&amp;gt;
      &amp;lt;div className="author"&amp;gt;{book.author}&amp;lt;/div&amp;gt;
    &amp;lt;/li&amp;gt;
  );
};

export default BookDetails;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/components/BookForm.js
import React, { useState } from 'react';
import { connect } from 'react-redux';
import { addBook } from '../actions/bookActions';

const BookForm = ({ dispatch }) =&amp;gt; {
  const [title, setTitle] = useState('');
  const [author, setAuthor] = useState('');

  const handleSubmit = (e) =&amp;gt; {
    e.preventDefault();
    const newBook = {
      title,
      author,
      id: 5,
    };
    dispatch(addBook(newBook));
    setTitle('');
    setAuthor('');
  };
  return (
    &amp;lt;form onSubmit={handleSubmit}&amp;gt;
      &amp;lt;input
        type="text"
        placeholder="book title"
        value={title}
        onChange={(e) =&amp;gt; setTitle(e.target.value)}
        required
      /&amp;gt;
      &amp;lt;input
        type="text"
        placeholder="author"
        value={author}
        onChange={(e) =&amp;gt; setAuthor(e.target.value)}
        required
      /&amp;gt;

      &amp;lt;input type="submit" value="add book" /&amp;gt;
    &amp;lt;/form&amp;gt;
  );
};

export default connect(null)(BookForm);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// src/components/BookList.js

import React, { useEffect } from 'react';
import { connect } from 'react-redux';
import BookDetails from './BookDetails';

import { fetchBooks } from '../actions/bookActions';

const BookList = ({ dispatch, books }) =&amp;gt; {
  useEffect(() =&amp;gt; {
    dispatch(fetchBooks());
  }, [dispatch]);
  return books.length ? (
    &amp;lt;div className="book-list"&amp;gt;
      &amp;lt;ul&amp;gt;
        {books.map((book) =&amp;gt; {
          return &amp;lt;BookDetails book={book} key={book.id} /&amp;gt;;
        })}
      &amp;lt;/ul&amp;gt;
    &amp;lt;/div&amp;gt;
  ) : (
    &amp;lt;div className="empty"&amp;gt;No books to read&amp;lt;/div&amp;gt;
  );
};

const mapStateToProps = (state) =&amp;gt; ({
  books: state.books.books,
});

export default connect(mapStateToProps)(BookList);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Setting up Reducers&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Reducers are what responsible for mutating states. It reads the dispatched action type and mutates the state accordingly. There is one main reducer generally called rootReducer which keeps track of all the other reducers. If you look at &lt;em&gt;src/index.js&lt;/em&gt;, in &lt;strong&gt;createStore&lt;/strong&gt; method, we only passed on Reducer which is root Reducer. The rootReducer contains all the other reducers.&lt;/p&gt;

&lt;p&gt;Add the following code in &lt;em&gt;src/reducers/index.js&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { combineReducers } from 'redux';

import booksReducer from './booksReducer';

const rootReducer = combineReducers({
  books: booksReducer,
});

export default rootReducer;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We see that it is calling &lt;em&gt;combineReducers&lt;/em&gt; method from redux and taking all the other reducers.&lt;/p&gt;

&lt;p&gt;Add the following code to &lt;em&gt;src/reducers/bookReducer.js&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { GET_BOOKS, ADD_BOOK } from '../actions/bookActions';

export const initialState = {
  books: [],
};

export default function bookReducer(state = initialState, action) {
  switch (action.type) {
    case GET_BOOKS:
      return {
        ...state,
        books: action.payload,
      };

    case ADD_BOOK:
      return {
        ...state,
        books: [...state.books, action.payload],
      };

    default:
      return state;
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Setting up actions&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Add the following code to &lt;em&gt;src/actions/bookActions.js&lt;/em&gt;&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import Axios from 'axios';
export const GET_BOOKS = 'GET_BOOKS';
export const ADD_BOOK = 'ADD_BOOk';

export const fetchBooks = () =&amp;gt; async (dispatch) =&amp;gt; {
  const data = await fetchData();
  dispatch({
    type: GET_BOOKS,
    payload: data,
  });
};

export const addBook = (newBook) =&amp;gt; async (dispatch) =&amp;gt; {
  dispatch({
    type: ADD_BOOK,
    payload: newBook,
  });
};

// fetch data from the API
const fetchData = async () =&amp;gt; {
  try {
    const res = await Axios.get(
      'https://fakerapi.it/api/v1/custom?_quantity=5&amp;amp;author=name&amp;amp;id=counter&amp;amp;title=city'
    );

    return res.data.data;
  } catch (error) {
    console.log(error);
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Styling&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Since we're mainly focused on setting up redux, it doesn't mean our application has to look ugly. That's why i've already written some basic styling which will make our app look decent.&lt;/p&gt;

&lt;p&gt;Replace all the codes in &lt;em&gt;src/index.css&lt;/em&gt; with following&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  background: #553055;
}
.App {
  background: #4c2a4c;
  margin: 20px auto;
  width: 90%;
  max-width: 700px;
  color: #eee;
}
.navbar {
  padding: 10px 20px;
  text-align: center;
  background: #6d3d6d;
}
.navbar h1 {
  margin: 10px 0;
}

.book-list {
  margin: 20px;
}
.book-list ul {
  padding: 0;
  list-style-type: none;
}
.book-list li {
  background: #6d3d6d;
  border-radius: 4px;
  padding: 10px;
  cursor: pointer;
  margin: 10px 0;
}
.book-list li:hover {
  opacity: 0.7;
  text-decoration: line-through;
}
.book-list .title {
  font-weight: bold;
  color: #fff;
  font-size: 1.2em;
}
.book-list .author {
  font-size: 0.9em;
  color: #ddd;
}
.empty {
  margin: 20px;
  text-align: center;
}

form {
  padding: 20px;
}
input[type='text'] {
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
  margin: 6px 0;
  background: #3c1f3c;
  color: #fff;
  border: 0;
}
input[type='submit'] {
  margin: 10px auto;
  background: #eee;
  border: 0;
  padding: 6px 20px;
  display: block;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, finally, let's add our components to &lt;em&gt;src/App.js&lt;/em&gt; . Replace all the codes in &lt;em&gt;src/App.js&lt;/em&gt; with following&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import BookForm from './components/BookForm';
import BookList from './components/BookList';

function App() {
  return (
    &amp;lt;div className="App"&amp;gt;
      &amp;lt;BookList /&amp;gt;
      &amp;lt;BookForm /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}

export default App;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, if you've followed everything accordingly, once you start the server, you can see the application running. Also if you look at &lt;em&gt;Redux DevTools&lt;/em&gt; you'll be able to see how the states changed, what actions were launched.&lt;/p&gt;

&lt;p&gt;If you run in any problem, you can always use the code from  &lt;a href="https://github.com/rajandmr/Reading-List-Redux" rel="noopener noreferrer"&gt;Here&lt;/a&gt; as a reference.&lt;/p&gt;

</description>
      <category>react</category>
      <category>redux</category>
      <category>webdev</category>
    </item>
    <item>
      <title>Intelligence Explosion: possibility that future of computing holds</title>
      <dc:creator>Rajan Prasad</dc:creator>
      <pubDate>Sat, 24 Oct 2020 10:10:36 +0000</pubDate>
      <link>https://dev.to/rajandmr/intelligence-explosion-possibility-that-future-of-computing-holds-31</link>
      <guid>https://dev.to/rajandmr/intelligence-explosion-possibility-that-future-of-computing-holds-31</guid>
      <description>&lt;p&gt;Comparing most powerful computers from 1956 to that of 2015, there's 1 trillion-fold increase in processing power.Although the technological progress has been accelerating, the human brain has not changed significantly in millenia and so some great minds have speculated that machines will surpass human levels of intelligence and ability at some point of time.&lt;/p&gt;

&lt;p&gt;Machines have become really intelligent, fast, accurate and unbeatable for performing some task like playing chess, or DOTA2(the Open AI), doing complex calculations, weather forecasting and more. But the one thing that makes human special is their &lt;em&gt;Natural Intelligence&lt;/em&gt;. But what if humans were able to design such intelligent system which in turn designs a new system more intelligent than itself and this cycle repeats ?&lt;/p&gt;

&lt;p&gt;This will result in such an intelligence called "UltraIntelligence". There would then unquestionably be an ‘intelligence explosion’, and the intelligence of men would be left far behind. Thus the first ultraintelligent machine is the last invention that man need ever make.&lt;/p&gt;

&lt;p&gt;But to be clear, nobody knows when is it going to happen, might be never or around 2500 or maybe around 2100. Maybe those prognosticators are right, and it will happen in the next thirty to eighty years.&lt;/p&gt;

&lt;p&gt;Get yourself ready&lt;/p&gt;

&lt;p&gt;There are another speculations however on How far along the intelligence explosion go.&lt;br&gt;
Some believe that it will stop at the point that it reaches the full equivalent of human intelligence.&lt;/p&gt;

&lt;p&gt;Why so? Because it is asserted that perhaps mankind exhibits the highest possible intelligence, and therefore there isn’t anything beyond it. In contrast, another viewpoint is that the AI intelligence explosion is going to zip right past human intelligence and land somewhere around so-called super-intelligence, also referred to as ultra-intelligence.&lt;/p&gt;

&lt;p&gt;How high is up? Can’t say. Don’t know.&lt;/p&gt;

&lt;p&gt;One belief is that this super-intelligence will undoubtedly be beyond our level of intelligence, and yet it will itself also have a boundary or final edge to it. It won’t be some amorphous intelligence that is all-consuming. Meanwhile, there are those though that suggest the AI intelligence explosion might be a never-ending chain reaction. AI intelligence might keep going and going, getting smarter and smarter, doing so for the rest of eternity.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;What would it mean for mankind if the AI intelligence explosion was something that once started was ever-expanding?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;This could be really good or ...really...really...bad&lt;/p&gt;

&lt;p&gt;A machine superintelligence, if programmed with the right motivations, could potentially solve all the problems that humans are trying to solve but haven’t had the ingenuity or processing speed to solve yet. A superintelligence might cure disabilities and diseases, achieve world peace, give humans vastly longer and healthier lives, eliminate food and energy shortages, boost scientific discovery and space exploration, and so on.&lt;/p&gt;

&lt;p&gt;Furthermore, humanity faces several existential risks in the 21st century, including global nuclear war, bioweapons, superviruses, and more.[56] A superintelligent machine would be more capable of solving those problems than humans are.&lt;/p&gt;

&lt;p&gt;Sounds really cool so far right ? Now let's look at the downside&lt;/p&gt;

&lt;p&gt;If programmed with the wrong motivations, a machine could be malevolent toward humans, and intentionally exterminate our species. More likely, it could be designed with motivations that initially appeared safe (and easy to program) to its designers, but that turn out to be best fulfilled (given sufficient power) by reallocating resources from sustaining human life to other projects.&lt;br&gt;
 “the AI does not hate you, nor does it love you, but you are made out of atoms which it can use for something else.”, No strings attached.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Can we add friendliness to any artificial intelligence design?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Many AI designs that would generate an intelligence explosion would not have a ‘slot’ in which a goal (such as ‘be friendly to human interests’) could be placed. For example, if AI is made via whole brain emulation, or evolutionary algorithms, or neural nets, or reinforcement learning, the AI will end up with some goal as it self-improves, but that stable eventual goal may be very difficult to predict in advance.&lt;/p&gt;

&lt;p&gt;Thus, in order to design a friendly AI, it is not sufficient to determine what ‘friendliness’ is (and to specify it clearly enough that even a superintelligence will interpret it the way we want it to). We must also figure out how to build a general intelligence that satisfies a goal at all, and that stably retains that goal as it edits its own code to make itself smarter. This task is perhaps the primary difficulty in designing friendly AI.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Can we teach a superintelligence a moral code with machine learning?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Some have proposed that  we teach machines a moral code with case-based machine learning. The basic idea is this: Human judges would rate thousands of actions, character traits, desires, laws, or institutions as having varying degrees of moral acceptability. The machine would then find the connections between these cases and learn the principles behind morality, such that it could apply those principles to determine the morality of new cases not encountered during its training. This kind of machine learning has already been used to design machines that can, for example, detect underwater mines after feeding the machine hundreds of cases of mines and not-mines.&lt;/p&gt;

&lt;p&gt;There are several reasons machine learning does not present an easy solution for Friendly AI. The first is that, of course, humans themselves hold deep disagreements about what is moral and immoral. But even if humans could be made to agree on all the training cases, at least two problems remain.&lt;/p&gt;

&lt;p&gt;The first problem is that training on cases from our present reality may not result in a machine that will make correct ethical decisions in a world radically reshaped by superintelligence.&lt;/p&gt;

&lt;p&gt;The second problem is that a superintelligence may generalize the wrong principles due to coincidental patterns in the training data.Consider the parable of the machine trained to recognize camouflaged tanks in a forest. Researchers take 100 photos of camouflaged tanks and 100 photos of trees. They then train the machine on 50 photos of each, so that it learns to distinguish camouflaged tanks from trees. As a test, they show the machine the remaining 50 photos of each, and it classifies each one correctly. Success! However, later tests show that the machine classifies additional photos of camouflaged tanks and trees poorly. The problem turns out to be that the researchers’ photos of camouflaged tanks had been taken on cloudy days, while their photos of trees had been taken on sunny days. The machine had learned to distinguish cloudy days from sunny days, not camouflaged tanks from trees.&lt;/p&gt;

&lt;p&gt;Thus, it seems that trustworthy Friendly AI design must involve detailed models of the underlying processes generating human moral judgments, not only surface similarities of cases.&lt;/p&gt;

</description>
      <category>superintelligence</category>
      <category>machinelearning</category>
      <category>computerscience</category>
    </item>
    <item>
      <title>Setting up Routing in Svelte</title>
      <dc:creator>Rajan Prasad</dc:creator>
      <pubDate>Thu, 15 Oct 2020 16:31:36 +0000</pubDate>
      <link>https://dev.to/rajandmr/setting-up-routing-in-svelte-2pfb</link>
      <guid>https://dev.to/rajandmr/setting-up-routing-in-svelte-2pfb</guid>
      <description>&lt;p&gt;In this article, i'll provide a quick overview of Svelte then we'll create a very basic Svelte app and add routing to it. Now for those who don't know what svelte app is, Svelte is Front-end JavaScript UI Library. It is not actually a framework, instead Svelte is a compiler that generates minimal and highly optimized JavaScript code.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Introduction&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Svelte is a new approach to building UIs. Instead of using Virtual DOM, it compiles the code and ships framework-less vanilla JavaScript which makes it faster and lighter than other frameworks or Libraries like React or Vue. It is gaining very much popularity due to its easy learning curve and a very easy state management.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Setting Up&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, in order to create an svelte app, we just basically have to clone the template from github. In order to do so, navigate into the directory in which you want to create the project and run&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx degit sveltejs/template my-svelte-project
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You can change 'my-svelte-project' to any name you want. Now, next you have to navigate into the recently created template folder and run the package installations&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd my-svelte-project
npm install
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will install all the required dependencies and then we can run the project by using the command&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm run dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will fire-up the server and the project will be running on port 5000 by default. Visit &lt;em&gt;&lt;a href="http://localhost:5000/"&gt;http://localhost:5000/&lt;/a&gt;&lt;/em&gt; in your browser and you will see our app running.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Creating components&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, the next step is to create components. We'll create &lt;strong&gt;component&lt;/strong&gt; folder inside &lt;em&gt;src&lt;/em&gt; and place all our components there. Also we'll be needing a folder called &lt;strong&gt;routes&lt;/strong&gt; to place our router file. So let's create all the Files and folders necessary. You can use GUI or simply enter the following commands&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir src/component
mkdir src/routes
touch src/component/About.svelte src/component/Home.svelte src/component/Blog.svelte

touch src/routes/index.svelte
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will create all the files and folders required. We also need a package called &lt;em&gt;svelte-routing&lt;/em&gt; in order to implement routing. In order to install the package, run&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm install svelte-routing
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now since all our files and folders are set up and &lt;em&gt;svelte-routing&lt;/em&gt; has been installed, we can head towards configuring &lt;em&gt;routes/index.svelte&lt;/em&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Configuring Routing&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Add the following code in &lt;em&gt;routes/index.svelte&lt;/em&gt; file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script&amp;gt;
  import { Router, Route } from 'svelte-routing';
  import Home from '../components/Home.svelte';
  import About from '../components/About.svelte';
  import Blog from '../components/Blog.svelte';

  export let url = '';
&amp;lt;/script&amp;gt;

&amp;lt;Router {url}&amp;gt;
  &amp;lt;div&amp;gt;
    &amp;lt;Route path="blog" component={Blog} /&amp;gt;
    &amp;lt;Route path="about" component={About} /&amp;gt;
    &amp;lt;Route path="/" component={Home} /&amp;gt;
  &amp;lt;/div&amp;gt;
&amp;lt;/Router&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;What we're doing here is, We're importing all our created components and also the bringing in &lt;em&gt;Router&lt;/em&gt; and &lt;em&gt;Route&lt;/em&gt; from &lt;em&gt;svelte-routing&lt;/em&gt; which are necessary classes in order to configure routing. Then we're setting up path for each component and pointing to load the respective component in their respective path.&lt;/p&gt;

&lt;p&gt;Now, it's time configure the Components.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Configuring Components&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;First we've to configure the &lt;em&gt;App.svelte&lt;/em&gt; since it's the root component. Replace all the code of &lt;em&gt;App.svelte&lt;/em&gt; with&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script&amp;gt;
  import Router from './routes/index.svelte';
&amp;lt;/script&amp;gt;

&amp;lt;style&amp;gt;
  main {
    text-align: center;
    padding: 1em;
    max-width: 240px;
    margin: 0 auto;
  }
&amp;lt;/style&amp;gt;

&amp;lt;main&amp;gt;
  &amp;lt;Router /&amp;gt;
&amp;lt;/main&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Basically, we're just bringing in the router we created and loading Router as root component. Now, let's configure other components.&lt;/p&gt;

&lt;p&gt;Almost all the components will be of same structure since its just a demo application. So let's configure our &lt;em&gt;Home.svelte&lt;/em&gt;. Add the following codes to this file&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;script&amp;gt;
  import { Link } from 'svelte-routing';
&amp;lt;/script&amp;gt;

&amp;lt;div&amp;gt;
  &amp;lt;h3&amp;gt;This is HomePage&amp;lt;/h3&amp;gt;
  &amp;lt;Link to="blog"&amp;gt;Blog&amp;lt;/Link&amp;gt;&amp;lt;br /&amp;gt;
  &amp;lt;Link to="about"&amp;gt;About&amp;lt;/Link&amp;gt;
&amp;lt;/div&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So in order to go to another Route, we need something called &lt;em&gt;Link&lt;/em&gt; then we points to which component it should redirect. That's all we're basically doing here.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Blog&lt;/em&gt; and &lt;em&gt;About&lt;/em&gt; component also will have similar structure.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Blog.svelte
&amp;lt;script&amp;gt;
  import { Link } from 'svelte-routing';
&amp;lt;/script&amp;gt;

&amp;lt;div&amp;gt;
  &amp;lt;h3&amp;gt;This is Blog Page&amp;lt;/h3&amp;gt;
  &amp;lt;Link to="/"&amp;gt;Home&amp;lt;/Link&amp;gt;&amp;lt;br /&amp;gt;
  &amp;lt;Link to="about"&amp;gt;About&amp;lt;/Link&amp;gt;
&amp;lt;/div&amp;gt;

// About.svelte

&amp;lt;script&amp;gt;
  import { Link } from 'svelte-routing';
&amp;lt;/script&amp;gt;

&amp;lt;div&amp;gt;
  &amp;lt;h3&amp;gt;This is About Page.&amp;lt;/h3&amp;gt;
  &amp;lt;Link to="/"&amp;gt;Home&amp;lt;/Link&amp;gt;&amp;lt;br /&amp;gt;
  &amp;lt;Link to="blog"&amp;gt;Blog&amp;lt;/Link&amp;gt;
&amp;lt;/div&amp;gt;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, we're all set. save all the files and test it. All the links should be working and you should be able to switch between apps. You can demo the project  &lt;a href="https://svelte-routing-red.vercel.app/"&gt;Here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/rajandmr/Svelte-Routing"&gt;Here's&lt;/a&gt;  the source code for the project&lt;/p&gt;

</description>
      <category>svelte</category>
      <category>javascript</category>
      <category>routing</category>
    </item>
    <item>
      <title>5 Pillars of Well-Architected Framework</title>
      <dc:creator>Rajan Prasad</dc:creator>
      <pubDate>Mon, 05 Oct 2020 13:24:03 +0000</pubDate>
      <link>https://dev.to/rajandmr/5-pillars-of-well-architected-framework-3595</link>
      <guid>https://dev.to/rajandmr/5-pillars-of-well-architected-framework-3595</guid>
      <description>&lt;p&gt;Creating a software system is a lot like constructing a building. If the foundation is not solid, structural problems can undermine the integrity and function of the building.&lt;br&gt;
In this article, we're going to talk about the design principles we can follow to build a future proof large scale software. The concepts are from *&lt;em&gt;AWS Well-Architected framework *&lt;/em&gt; whitepaper. This whitepaper inspires to learn architectural best practices for designing and operating reliable, secure, efficient, and cost-effective systems in the cloud. It provides a way to consistently measure your architectures against best practices and identify areas for improvement. I'll be trying to summarize the  &lt;a href="https://d1.awsstatic.com/whitepapers/architecture/AWS_Well-Architected_Framework.pdf"&gt;Whitepaper&lt;/a&gt; &lt;/p&gt;

&lt;p&gt;So let's first quickly sum up the &lt;strong&gt;Guiding Design Principles&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;
&lt;strong&gt;Stop guessing capacity needs&lt;/strong&gt;: Scale up &amp;amp; Down as required&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Automate everything&lt;/strong&gt;: Automated systems ensure consistency &amp;amp; reliability&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Test at scale&lt;/strong&gt;: Test an accurate replica of production on-demand&lt;/li&gt;
&lt;li&gt;
&lt;strong&gt;Adapt &amp;amp; Evolve&lt;/strong&gt;: Adapt the architecture as needed to meet new challenges&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;The framework is based on 5 pillars:&lt;/p&gt;

&lt;p&gt;1). Operational Excellence&lt;br&gt;
2). Cost optimization&lt;br&gt;
3). Reliability&lt;br&gt;
4). Performance Efficiency&lt;br&gt;
5). Security&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Operational Excellence&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;The main emphasis of this pillar is: &lt;strong&gt;Does your architecture work ? Will it continue to ?&lt;/strong&gt;&lt;br&gt;
Let's look at this pillar specific principles:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;All operations are code&lt;/li&gt;
&lt;li&gt;Document is updated automatically&lt;/li&gt;
&lt;li&gt;Make smaller changes you can roll back&lt;/li&gt;
&lt;li&gt;Iterate...a lot&lt;/li&gt;
&lt;li&gt;Expect things to go sideways&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Cost Optimization&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Emphasis: &lt;strong&gt;Spend only what you have to&lt;/strong&gt;&lt;br&gt;
Pillar specific principles:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Consumption based pricing&lt;/li&gt;
&lt;li&gt;Measure efficiency constantly&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Reliability:&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Emphasis: ** Will this system work consistently &amp;amp; recover quickly ?**&lt;br&gt;
Pillar specific principles:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Recover from issues automatically&lt;/li&gt;
&lt;li&gt;Scale horizontally first for resilience&lt;/li&gt;
&lt;li&gt;Reduce idle resources&lt;/li&gt;
&lt;li&gt;Manage change through automation&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Performance Efficiency&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Emphasis: &lt;strong&gt;Remove bottlenecks, reduce waste&lt;/strong&gt;&lt;br&gt;
Pillar specific principles:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Reduce latency&lt;/li&gt;
&lt;li&gt;Serverless&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Security&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Emphasis: *&lt;em&gt;Does this system work only as intended? *&lt;/em&gt;&lt;br&gt;
Pillar specific principles:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Automate security tasks&lt;/li&gt;
&lt;li&gt;Encrypt data in transit and at rest&lt;/li&gt;
&lt;li&gt;Know who did what when&lt;/li&gt;
&lt;li&gt;Identities have the least privileges required&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Operational Excellence In Depth&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Operational excellence is the ability to run systems and gain insights into their operations in order to deliver business value, and to continuously improve supporting processes and procedures. &lt;strong&gt;The 3 Phases&lt;/strong&gt; of Operational Excellence&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Prepare-Prioritize: Prioritize to align with business priorities&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;What is the business goal ?&lt;/li&gt;
&lt;li&gt;What are the critical pieces need to meet that goal ?&lt;/li&gt;
&lt;li&gt;Any compliance restrictions/requirements ?&lt;/li&gt;
&lt;li&gt;Dependencies between services ?&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Design your architecture to support business Priorities&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Is the design observable ?&lt;/li&gt;
&lt;li&gt;Are your logs &amp;amp; observations actionable ?&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Is your workload ready to go live ?&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Are your processes consistent ?&lt;/li&gt;
&lt;li&gt;Is operational code properly managed ?&lt;/li&gt;
&lt;li&gt;Are tests in place ?&lt;/li&gt;
&lt;li&gt;Anticipate failure ?&lt;/li&gt;
&lt;li&gt;Ensure your workload is actually working&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Shit happens. Be ready.&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Anticipate planned &amp;amp; unplanned events&lt;/li&gt;
&lt;li&gt;Respond in code&lt;/li&gt;
&lt;li&gt;Connect observations with 3rd party tools as needed&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Evolve&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Learn from success &amp;amp; failure&lt;/li&gt;
&lt;li&gt;Post-event, have runbooks changed ?&lt;/li&gt;
&lt;li&gt;Test assumptions&lt;/li&gt;
&lt;li&gt;Experiment early and often find better solutions&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Cost&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Use the appropriate resources &amp;amp; configurations&lt;/li&gt;
&lt;li&gt;Provision to current needs with an eye to future&lt;/li&gt;
&lt;li&gt;Right size to lowest resource that meets needs&lt;/li&gt;
&lt;li&gt;Use data to choose purchase options&lt;/li&gt;
&lt;li&gt;Optimize by geography&lt;/li&gt;
&lt;li&gt;Optimize data transfer&lt;/li&gt;
&lt;li&gt;Know how much you're spending and where&lt;/li&gt;
&lt;li&gt;Continuously work to maximize value delivered&lt;/li&gt;
&lt;li&gt;Align utilization with requirements&lt;/li&gt;
&lt;li&gt;Report and validate findings&lt;/li&gt;
&lt;li&gt;Evaluate new services for value&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;** Awareness of spend is key to maximizing value **&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Reliability&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Reliability is the ability of a system to recover from infrastructure or service disruptions, dynamically acquire computing resources to meet demand, and mitigate disruptions.&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Scale horizontally first for resilience&lt;/li&gt;
&lt;li&gt;Reduce idle resources&lt;/li&gt;
&lt;li&gt;Manage change through automation&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Limit&lt;/strong&gt;: Understand default &amp;amp; requested resources limit&lt;br&gt;
&lt;strong&gt;Networking&lt;/strong&gt;: Understand topology, bandwidth &amp;amp; latency&lt;br&gt;
&lt;strong&gt;Availability&lt;/strong&gt;: Ensure your application is ready for business use&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Ensure your application is ready for business use&lt;/p&gt;
&lt;/blockquote&gt;

&lt;ul&gt;
&lt;li&gt;Can users access your application&lt;/li&gt;
&lt;li&gt;Deploy without issue&lt;/li&gt;
&lt;li&gt;Can you push issue to planned downtime&lt;/li&gt;
&lt;li&gt;Can your application withstand portal outages ?&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Performance Efficiency&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Selection&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Is this the optimal solution for this workload ?&lt;/li&gt;
&lt;li&gt;What type of compute best suits ?&lt;/li&gt;
&lt;li&gt;Which data store is ideal for this workload ?&lt;/li&gt;
&lt;li&gt;Does your network design complement compute &amp;amp; data store choices ?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Review&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Continuously ensure choices work for your workload&lt;/li&gt;
&lt;li&gt;Is infrastructure stored as code ?&lt;/li&gt;
&lt;li&gt;Are deployments simple &amp;amp; automated ?&lt;/li&gt;
&lt;li&gt;Can benchmarks be taken automatically ?&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;&lt;strong&gt;Monitoring&lt;/strong&gt;:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Use active &amp;amp; passive monitoring where appropriate&lt;/li&gt;
&lt;li&gt;Understand the five phases of monitoring (Generation, Aggregation, Real-time Processing, Storage, Analysis)&lt;/li&gt;
&lt;li&gt;Create actionable metrics&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Trade of -&amp;gt; You can't have it all&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>aws</category>
      <category>bestpractises</category>
      <category>architecture</category>
    </item>
    <item>
      <title>NodeJS CRUD API with MongoDB</title>
      <dc:creator>Rajan Prasad</dc:creator>
      <pubDate>Sun, 04 Oct 2020 06:13:51 +0000</pubDate>
      <link>https://dev.to/rajandmr/nodejs-crud-api-with-mongodb-4mn1</link>
      <guid>https://dev.to/rajandmr/nodejs-crud-api-with-mongodb-4mn1</guid>
      <description>&lt;p&gt;If you've been in the web development world, the chances are: you already have heard about NodeJS and MongoDB. The NodeJS official page defines it as &lt;strong&gt;Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.&lt;/strong&gt; Also, MongoDB is one of the most popular NoSQL database. In this article we're going to perform CRUD operation on MongoDB using NodeJS along with tools express &amp;amp; mongoose.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Prerequisite&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;If you're to get started i assume you already have set-up a MongoDB cluster and have the connection URI. If not so then you can find how to set it up in my  &lt;a href="https://blogs.rajankalwar.com.np/getting-started-with-mongodb" rel="noopener noreferrer"&gt;previous article&lt;/a&gt; , it will guide you step-by-step on setting up Free MongoDB cluster. I also assume you've some working knowledge with NodeJS and express.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Setting Up&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In order to get started, first thing we'll do is create the file structure. I suggest you to create a root folder and then inside the root folder, create the following sub-folders:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1601790296782%2FZ644Dswdl.jpeg" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1601790296782%2FZ644Dswdl.jpeg" alt="mongonode.JPG"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Installing Dependencies&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, to get started, we first need to create a file &lt;em&gt;server.js&lt;/em&gt; and then install few required dependencies. In order to do so,&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm init -y


touch server.js
touch .env
mkdir controllers
mkdir models
mkdir routes

npm install express mongoose dotenv cors body-parser

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will complete our folder structure and dependencies installation. Now the next step will be to get our mongoDB connection URI and place it in a &lt;em&gt;.env&lt;/em&gt; file. In order to do so, open your .env file and edit it as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;DB = "YOUR_CONNECTION_STRING_HERE"

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Setting up Server and Routes&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, let's edit our &lt;em&gt;server.js&lt;/em&gt; file in order to set up the routes. Copy and paste the following code in your server.js file:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const mongoose = require("mongoose");

require("dotenv").config();

const app = express();

const routes = require("./app/routes");

var corsOptions = {
  origin: "http://localhost:8081",
};

app.use(cors(corsOptions));

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));

let DB = process.env.DB;

mongoose
  .connect(DB, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() =&amp;gt; console.log("mongoDB connected Successfully"))
  .catch((err) =&amp;gt; console.log(err));

app.use("/api/notes", routes);

const PORT = process.env.PORT || 8080;

app.listen(PORT, () =&amp;gt; {
  console.log(`Server is running on port ${PORT}`);
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So basically what we're doing here is&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Bringing in required dependencies&lt;/li&gt;
&lt;li&gt;Bringing in &lt;em&gt;Routes&lt;/em&gt;(which we haven't created yet but will shortly) &lt;/li&gt;
&lt;li&gt;Connecting to mongoDB&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Creating Models&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Since we're using MongoDB and Mongoose, we must have to have models. In this app, we'll have only one model &lt;strong&gt;NotesModel&lt;/strong&gt; which will contain the fields for our notes.&lt;br&gt;
So let's create a file &lt;em&gt;NotesModel.js&lt;/em&gt; file inside &lt;strong&gt;models&lt;/strong&gt; folder and paste the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const mongoose = require("mongoose");

const NotesSchema = new mongoose.Schema(
  {
    title: String,
    description: String,
  },
  { timestamps: true }
);

const Note = mongoose.model("Note", NotesSchema);
module.exports = Note;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So essentially, we just have 2 fields &lt;em&gt;title&lt;/em&gt; and &lt;em&gt;description&lt;/em&gt; of string types to keep things simple. Also the &lt;em&gt;timestamps&lt;/em&gt; has been set to true which will record the creation and modification date.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Creating Router and Controller&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, the &lt;em&gt;server.js&lt;/em&gt; is all setup, we can start setting up our controller and Router.&lt;br&gt;
Inside controller folder, create a file &lt;em&gt;index.js&lt;/em&gt; and paste the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const NotesModel = require("../models/NotesModel");

exports.findAll = async (req, res) =&amp;gt; {
  try {
    const notes = await NotesModel.find({});
    res.send(notes);
  } catch (error) {
    res.status(500).send({
      message: error.message || "Some error occured while retrieving Notes",
    });
  }
};

exports.create = async (req, res) =&amp;gt; {
  const Note = req.body;

  try {
    let NoteDoc = new NotesModel(Note);
    await NoteDoc.save();
    res.send(Note);
  } catch (error) {
    res.status(500).send(error);
  }
};

exports.findOne = async (req, res) =&amp;gt; {
  const id = req.params.id;

  try {
    let Note = await NotesModel.findById(id);
    res.send(Note);
  } catch (error) {
    res.status(500).send(error);
  }
};

exports.update = async (req, res) =&amp;gt; {
  let { ...data } = req.body;
  const result = await NotesModel.findOneAndUpdate(
    { _id: req.params.id },
    data,
    {
      new: true,
    }
  );

  res.send(result);
};

exports.delete = async (req, res) =&amp;gt; {
  try {
    let id = req.params.id;

    await NotesModel.findByIdAndDelete(req.params.id);

    res.status(200).send();
  } catch (error) {
    res.status(500).send(error);
  }
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This part contains the logic for Creating, Reading, Updating and Deleting data from/to our database. Now in order for it to work, we've to bring it in routes file and map it to proper methods/paths. In order to do so, create a file called &lt;em&gt;index.js&lt;/em&gt; inside &lt;strong&gt;routes&lt;/strong&gt; folder and paste the following code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Bring in the express server
const express = require("express");

// Bring in the Express Router
const router = express.Router();

// Import the Controller
const controller = require("../controllers");

// Create a new Note
router.post("/", controller.create);

// Get all Notes
router.get("/", controller.findAll);

// Get Note by Id
router.get("/:id", controller.findOne);

// Modify existing Note
router.put("/:id", controller.update);

// Delete Note by Id
router.delete("/:id", controller.delete);

module.exports = router;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now that all has been set-up, you can just run:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;node server.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The server will start and will listen to port:8080. You can use postman to test the APIs.&lt;/p&gt;

&lt;p&gt;The complete project can be found on my  &lt;a href="https://github.com/rajandmr/mongodb-nodejs-mongoose" rel="noopener noreferrer"&gt;Github&lt;/a&gt; &lt;/p&gt;

</description>
      <category>node</category>
      <category>mongodb</category>
      <category>mongoose</category>
      <category>restapi</category>
    </item>
    <item>
      <title>Adding authentication to React App using AWS Amplify and Cognito</title>
      <dc:creator>Rajan Prasad</dc:creator>
      <pubDate>Tue, 01 Sep 2020 14:13:59 +0000</pubDate>
      <link>https://dev.to/rajandmr/adding-authentication-to-react-app-using-aws-amplify-and-cognito-ebf</link>
      <guid>https://dev.to/rajandmr/adding-authentication-to-react-app-using-aws-amplify-and-cognito-ebf</guid>
      <description>&lt;p&gt;AWS Amplify enables front-end developers to build secure, scalable full stack applications, powered by AWS while Amazon Cognito lets you add user sign-up, sign-in, and access control to your web and mobile apps quickly and easily. In this article, we will be using AWS amplify to add authentication to our React application.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Prerequisite&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;In order to follow along, you must have&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;npm installed&lt;/li&gt;
&lt;li&gt;AWS Account&lt;/li&gt;
&lt;li&gt;AWS profile set up
If you don't have any of these i suggest you to set it up since i will not be going to talk about any of those in this article.&lt;/li&gt;
&lt;/ul&gt;

&lt;blockquote&gt;
&lt;p&gt;Creating React application&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, to get started, we first have to create a React Application. we'll use CRA to make things easier. If you've CRA installed you can simply use&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;create-react-app my-auth-app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you don't have CRA installed and don't want to do so then simply use&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npx create-react-app my-auth-app
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;blockquote&gt;
&lt;p&gt;Installing and initializing Amplify&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;Now, we need to install aws-amplify. We also be installing pre-built React UI for authentication so that we don't have to code the SignIn/SignUp UI by ourselves. Once installed, we can then initialize amplify.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd my-auth-app
npm i aws-amplify @aws-amplify/ui-react
amplify init
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So, we just navigated into our directory and hit install command for aws-amplify and ui-react. Then, we initialized Amplify. Once initialized, you'll be prompted with few questions:&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Enter the name for the project (my-auth-app)&lt;/li&gt;
&lt;li&gt;Enter name for the environment&lt;/li&gt;
&lt;li&gt;Choose your default editor&lt;/li&gt;
&lt;li&gt;Choose the type of app you're building&lt;/li&gt;
&lt;li&gt;What javascript framework are you using&lt;/li&gt;
&lt;li&gt;Source directory Path (src)&lt;/li&gt;
&lt;li&gt;Distribution directory Path (build)&lt;/li&gt;
&lt;li&gt;Build Command&lt;/li&gt;
&lt;li&gt;Start Command&lt;/li&gt;
&lt;li&gt;Do you want to use an aws-profile (Y/n)&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;You can just hit enter for all other questions except 2 and 10. For the environment name, you can enter either 'test' or 'dev'. i prefer 'dev'.&lt;br&gt;
For question 10, once hit enter, your aws-profiles will be prompted, you have to select the profile on which you want to deploy the cognito user-pool.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Adding authentication&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;It's time we finally add authentication to our project. To do so, use&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;amplify add auth
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, again you'll be prompted with set of questions.&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Do you want to use the default authentication and security configuration?&lt;/li&gt;
&lt;li&gt; How do you want users to be able to sign in?&lt;/li&gt;
&lt;li&gt;Do you want to configure advanced settings?&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Default options are good enough for our simple app, so just hit enter for all the above questions. Authentication has been. Now, to set-up cognito userpool in the cloud, we just have to push it. To do so use&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;amplify push
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;You'll be prompted with "Are You sure" question, hit enter as we DO want to deploy the userpool in the cloud. It will start the deployment process and deploy the cloudformation stack. Might take 4-5 minutes. Once done, we can set up our react application to use Cognito and add Authentication UI from react-ui package.&lt;br&gt;
Now, we need to configure our react application. To do so, open the project in any code-editor. I'll be using vs-code in my case however feel free to use any text editor, whichever suits you best.&lt;br&gt;
Edit Your &lt;em&gt;src/index.js&lt;/em&gt; file to&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";

import config from "./aws-exports";
import Amplify from "aws-amplify";
Amplify.configure(config);

ReactDOM.render(
  &amp;lt;React.StrictMode&amp;gt;
    &amp;lt;App /&amp;gt;
  &amp;lt;/React.StrictMode&amp;gt;,
  document.getElementById("root")
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, edit your &lt;em&gt;src/App.js&lt;/em&gt; file to&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import React from "react";
import { withAuthenticator, AmplifySignOut } from "@aws-amplify/ui-react";

const App = () =&amp;gt; (
  &amp;lt;div&amp;gt;
    &amp;lt;AmplifySignOut /&amp;gt;
    My App
  &amp;lt;/div&amp;gt;
);

export default withAuthenticator(App);

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Save the project and run te app using&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;npm start
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If there's not any issue, You'll see the following screen&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--emckuHwd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1598969220375/8ypo3-zjE.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--emckuHwd--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1598969220375/8ypo3-zjE.png" alt="ss-auth.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can try out by creating a user. When creating a new user, you'll be provided with a verification code to the email you enter in order to complete the verification process. Once verified you can Sign In by providing the credentials.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Thanks for reading. You can find the complete project on  &lt;a href="https://github.com/rajandmr/React-amplify-auth"&gt;GitHub&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>react</category>
      <category>aws</category>
      <category>amplify</category>
      <category>authentication</category>
    </item>
    <item>
      <title>Discord Servers to join as a Developer</title>
      <dc:creator>Rajan Prasad</dc:creator>
      <pubDate>Tue, 01 Sep 2020 03:21:01 +0000</pubDate>
      <link>https://dev.to/rajandmr/discord-servers-to-join-as-a-developer-lm9</link>
      <guid>https://dev.to/rajandmr/discord-servers-to-join-as-a-developer-lm9</guid>
      <description>&lt;p&gt;Whether You're new to development or an experienced developer seeking to connect with like minded people then this article is for you. Discord is a platform which allows to connect with other people and there are dedicated servers only for developers.&lt;/p&gt;

&lt;p&gt;Here's a list of recommended Dev Servers to join as a developer:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt; &lt;a href="https://discord.com/channels/102860784329052160/377580704722190347"&gt;Reactiflux&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt; &lt;a href="https://disboard.org/server/425824580918181889"&gt;Nodeiflux&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt; &lt;a href="https://discord.com/channels/267624335836053506/267631170882240512"&gt;Python&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt; &lt;a href="https://discord.com/channels/508357248330760243/508358407346978834"&gt;TypeScript Community&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt; &lt;a href="https://discord.com/channels/325477692906536972/325654285255704578"&gt;Vue Land&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt; &lt;a href="https://discord.com/channels/486935104384532500/572385218510716949"&gt;Tailwind CSS&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt; &lt;a href="https://discord.com/channels/244230771232079873/244230771232079873"&gt;The Programmer's Hangout&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt; &lt;a href="https://discord.com/channels/172018499005317120/443166941809737728"&gt;The Coding Den&lt;/a&gt;
&lt;/li&gt;
&lt;li&gt;&lt;a href="https://discord.com/channels/174075418410876928/613611625827794944"&gt;DevCord&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://discord.com/channels/238666723824238602/308772291863642112"&gt;Programming Discussions&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://discord.com/channels/494558898880118785/505003431837171723"&gt;Programming Humour&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Did i miss any ?? Feel free to comment i'll be happy to checkout.&lt;/p&gt;

</description>
      <category>productivity</category>
      <category>discord</category>
      <category>community</category>
      <category>social</category>
    </item>
    <item>
      <title>DynamoDB CRUD with NodeJS and Lambda</title>
      <dc:creator>Rajan Prasad</dc:creator>
      <pubDate>Sun, 30 Aug 2020 11:54:25 +0000</pubDate>
      <link>https://dev.to/rajandmr/dynamodb-crud-with-nodejs-and-lambda-inn</link>
      <guid>https://dev.to/rajandmr/dynamodb-crud-with-nodejs-and-lambda-inn</guid>
      <description>&lt;p&gt;AWS defines DynamoDB as "Amazon DynamoDB is a key-value and document database that delivers single-digit millisecond performance at any scale. It's a fully managed, multiregion, multimaster, durable database with built-in security, backup and restore, and in-memory caching for internet-scale applications". So from the definition, it is clear that DynamoDB is a serverless, fully-managed millisecond performance and highly scalable NoSQL database which was announced in Early 2012.&lt;/p&gt;

&lt;p&gt;In this article, we'll perform basic CRUD operations using AWS Lambda and NodeJS. To kick off, we first have to define the following file structure:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1597676042852%2FY8KEZD7Jc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fcdn.hashnode.com%2Fres%2Fhashnode%2Fimage%2Fupload%2Fv1597676042852%2FY8KEZD7Jc.png" alt="dynamocrud.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;we'll call our root-folder DynamoCRUD, however feel free to call it anything you like. Under our root folder, we'll create a folder called resources which will contain a file called dynamo-table.yml containing our code for creating DynamoDB table. Also since we'll be using Serverless Framework to deploy our cloudformation stack, i assume that you already have installed and set up the programmatic access to your AWS account with Serverless. If not you can refer to the  &lt;a href="https://www.serverless.com/framework/docs/providers/aws/guide/installation/" rel="noopener noreferrer"&gt;Serverless Documentation&lt;/a&gt; .&lt;br&gt;
After creating a folder called resources, we'll generate a template using serverless framework with the command:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

sls create -t aws-nodejs


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This will generate the serverless.yml file, handler.js file and .gitignore file and finally our file structure will be completed.&lt;/p&gt;

&lt;p&gt;Now, lets get started with our serverless.yml file. Our serverless.yml file will look like this:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

service: DynamoCRUD

provider:
  name: aws
  runtime: nodejs12.x
  profile: default
  timeout: 30

  iamRoleStatements:
    - Effect: "Allow"
      Action:
        - "dynamodb:*"
      Resource: "*"

functions:
  addItem:
    handler: handler.addItem

  getAllItem:
    handler: handler.getAllItem

  updateItem:
    handler: handler.updateItem

  deleteItem:
    handler: handler.deleteItem

resources:
  - ${file(resources/dynamo-table.yml)}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;So basically what we're doing is we're creating a dynamoDB table using resources section and creating 4 basic functions to perform the CRUD operation and giving DynamoDB permission to our Lambda functions.&lt;/p&gt;

&lt;p&gt;Now, we'll create a DynamoDB table i.e. our dynamo-table.yml under resources folder. It will look something like :&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

Resources:
  myDynamoDBTable:    # Logical Id of the resource
    Type: AWS::DynamoDB::Table

    Properties:
      AttributeDefinitions:
        - 
          AttributeName: "year"
          AttributeType: "N"
        - 
          AttributeName: "title"
          AttributeType: "S"

      KeySchema:
        - AttributeName: "year"    # Partition Key
          KeyType: "HASH"
        - AttributeName: "title"    # Sort Key
          KeyType: "RANGE"

      TableName: "Movies"     

      ProvisionedThroughput:   # Optional, can be skipped
        ReadCapacityUnits: 10
        WriteCapacityUnits: 10



&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;So basically we're creating a table with the above attribute definitions.&lt;/p&gt;

&lt;p&gt;Now, lets write our handler.js file. This will have the code for all the CRUD operation defined on serverless.yml file.&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

"use strict";
const AWS = require('aws-sdk');

const docClient = new AWS.DynamoDB.DocumentClient();

// Function to Create an Item to DB
module.exports.addItem = async (event) =&amp;gt; {
  try {

    let table = "Movies";
    let year = 2015;
    let title = "The Big New Movie";

    let params = {
      TableName: table,
      Item: {
        "year": year,
        "title": title,
        "info": {
          "plot": "Nothing happens at all",
          "rating": 0
        }
      }
    }

    let result = await docClient.put(params).promise();
    if (result) {
      console.log("&amp;gt;&amp;gt;&amp;gt;&amp;gt;&amp;gt;&amp;gt;&amp;gt;&amp;gt;&amp;gt;", result);
    }

    console.log("hello world")
    return {
      statusCode: 200,
      body: JSON.stringify({
        message: "Go Serverless v1.0! Your function executed successfully!",
        data: result
      }),
    };
  } catch (error) {
    console.log(error);
    return error;
  }
};

// Function to getAllItems from DB
module.exports.getAllItem = async () =&amp;gt; {
  let table = "Movies";
  let year = 2015;

  let title = "The Big New Movie";

  let params = {
    TableName: table,
    Key: {
      "year": year,
      "title": title
    }
  }

  try {
    let result = await docClient.get(params).promise();

    console.log(result);

    return {
      body: JSON.stringify({
        message: "Executed succesfully",
        data: result
      })
    }
  } catch (error) {
    console.log(error);
  }
}

// Function to update an Item in DB
module.exports.updateItem = async () =&amp;gt; {
  let table = "Movies";
  let year = 2015;

  let title = "The Big New Movie";

  let params = {
    TableName: table,
    Key: {
      "year": year,
      "title": title
    },
    UpdateExpression: "set info.rating = info.rating + :val",
    ExpressionAttributeValues: {
      ":val": 1
    },
    ReturnValues: "UPDATED_NEW"
  };

  try {
    let result = await docClient.update(params).promise();
    return {
      body: JSON.stringify({
        message: "updated succesfully",
        data: result
      })
    }
  } catch (error) {
    console.log(error);
  }
}

// Function to Delete an item
module.exports.deleteItem = async () =&amp;gt; {

  let table = "Movies";
  let year = 2015;

  let title = "The Big New Movie";

  let params = {
    TableName: table,
    Key: {
      "year": year,
      "title": title
    }
  }

  let result = await docClient.delete(params).promise();

  return {
    body: JSON.stringify({
      message: "deleted succesfully",
      data: result
    })
  }

}


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;One thing to note here, I'm hard-coding the Data to be created in DB for the sake of simplicity. Feel free to change the AddItem method into POST and parse the body from event.body, you can totally do that. Same goes for update and delete method. I'm just trying to keep the things as simple as possible.&lt;/p&gt;

&lt;p&gt;Now, the last thing to do is deploy our stack to AWS and we'll be ready to test our functions worked or not. To deploy the stack simply just enter the following command:&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;

sls deploy -v


&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;

&lt;p&gt;This will return all the functions end-point. You can use POSTMAN to to hit the end-points and check the responses.&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Thanks for Reading&lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>node</category>
      <category>devops</category>
      <category>dynamodb</category>
      <category>restapi</category>
    </item>
    <item>
      <title>Node.js Rest CRUD API with Postgres</title>
      <dc:creator>Rajan Prasad</dc:creator>
      <pubDate>Sat, 29 Aug 2020 06:10:28 +0000</pubDate>
      <link>https://dev.to/rajandmr/node-js-rest-crud-api-with-postgres-213p</link>
      <guid>https://dev.to/rajandmr/node-js-rest-crud-api-with-postgres-213p</guid>
      <description>&lt;p&gt;PostgreSQL is a powerful, open source object-relational database system  that has earned it a strong reputation for reliability, feature robustness, and performance. In this article, We will build Rest Apis that can create, retrieve, update and delete Notes.&lt;/p&gt;

&lt;p&gt;First we will start setting up express server and routes with express router. Next we add configuration for PostgreSQL database and create Note Model with sequelize. Our File structure at the end will be &lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--jznJP2tQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1598679371188/P1DBpvBiA.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--jznJP2tQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1598679371188/P1DBpvBiA.png" alt="folderstructure.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;To create express server and install required dependencies, in your terminal type&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir postgres-crud
cd postgres-crud
npm init -y
touch server.js
mkdir app
npm i express cors body-parser pg pg-hstore sequelize@5.21.13
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;This will create a folder called postgres-crud, initialize a node project and install the required dependencies. Now, we need to set-up our express server code and configure the route. To set up the server, Edit the &lt;strong&gt;server.js&lt;/strong&gt; file as&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Bring in required Modules
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");

const app = express();

// Bring in the route
const routes = require("./app/routes");

var corsOptions = {
  origin: "http://localhost:8081",
};

app.use(cors(corsOptions));

app.use(bodyParser.json());

app.use(bodyParser.urlencoded({ extended: true }));

const db = require("./app/models");
db.sequelize.sync();

app.use("/api/notes", routes);

// Define PORT
const PORT = process.env.PORT || 8080;

// Listen to the defined PORT
app.listen(PORT, () =&amp;gt; {
  console.log(`Server is running on port ${PORT}`);
});

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, to set up the routes, we will create a folder called &lt;em&gt;routes&lt;/em&gt; in our &lt;em&gt;app&lt;/em&gt; folder and under &lt;em&gt;routes&lt;/em&gt; folder, we will create a file called &lt;strong&gt;index.js&lt;/strong&gt;. You can do these all through the editor or type the following command in your terminal&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir app/routes
touch app/routes/index.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, edit the &lt;em&gt;app/routes/index.js&lt;/em&gt; file as&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;// Bring in the express server
const express = require("express");

// Bring in the Express Router
const router = express.Router();

// Import the Controller
const controller = require("../controllers");


// Create a new Note
router.post("/", controller.create);

// Get all Notes
router.get("/", controller.findAll);

// Get Note by Id
router.get("/:id", controller.findOne);

// Modify existing Note
router.put("/:id", controller.update);

// Delete Note by Id
router.delete("/:id", controller.delete);

module.exports = router;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, the next step is to configure the Database. In order to do so, we create &lt;em&gt;config&lt;/em&gt; folder inside our &lt;em&gt;app&lt;/em&gt; folder then create a file &lt;strong&gt;db.config.js&lt;/strong&gt; file under the config folder. To do these through command line&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir app/config
touch app/config/db.config.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, edit the &lt;strong&gt;db.config.js&lt;/strong&gt; file as below. You have to replace the HOST, USER, PASSWORD values with your own db values.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;module.exports = {
  HOST: "localhost", // Replace it with your own host address
  USER: "user123", // Replace with your own username
  PASSWORD: "12345", // Replace with your own password
  DB: "testdb",
  dialect: "postgres",
  pool: {
    max: 5,
    min: 0,
    acquire: 30000,
    idle: 10000,
  },
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, the setting up db configuration part is done. Next is to define the db model. To do so, create a folder called &lt;em&gt;models&lt;/em&gt; inside &lt;em&gt;app&lt;/em&gt; folder and initialize two files namely &lt;em&gt;index.js&lt;/em&gt; and &lt;em&gt;notes.model.js&lt;/em&gt;. Now, edit the index.js file as&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const dbConfig = require("../config/db.config");

const Sequelize = require("sequelize");
const sequelize = new Sequelize(dbConfig.DB, dbConfig.USER, dbConfig.PASSWORD, {
  host: dbConfig.HOST,
  dialect: dbConfig.dialect,
  operatorAliases: 0,

  pool: {
    max: dbConfig.pool.max,
    min: dbConfig.pool.min,
    acquire: dbConfig.pool.acquire,
    idle: dbConfig.pool.idle,
  },
});

const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;

db.notes = require("./notes.model.js")(sequelize, Sequelize);
module.exports = db;

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Also, edit the notes.model.js file as&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const { sequelize, Sequelize } = require(".");

module.exports = (sequelize, Sequelize) =&amp;gt; {
  const Note = sequelize.define("note", {
    title: {
      type: Sequelize.STRING,
    },
    description: {
      type: Sequelize.STRING,
    },
    published: {
      type: Sequelize.BOOLEAN,
    },
  });
  return Note;
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, the model is all set. Last thing remaining to do is defining controller. To do so, create a folder called &lt;em&gt;controllers&lt;/em&gt; inside &lt;em&gt;app&lt;/em&gt; folder and initialize a file namely &lt;strong&gt;index.js&lt;/strong&gt; inside &lt;em&gt;controllers&lt;/em&gt; folder. Edit the &lt;strong&gt;index.js&lt;/strong&gt; file as&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const db = require("../models");
const Notes = db.notes;
const Op = db.Sequelize.Op;

exports.create = (req, res) =&amp;gt; {
  if (!req.body.title) {
    res.status(400).send({
      message: "Content can not be empty !",
    });
    return;
  }

  const note = {
    title: req.body.title,
    description: req.body.description,
    published: req.body.published ? req.body.published : false,
  };

  Notes.create(note)
    .then((data) =&amp;gt; {
      res.send(data);
    })
    .catch((err) =&amp;gt; {
      res.status(500).send({
        message: err.message || "Some error occurred while create the Notes",
      });
    });
};

exports.findAll = (req, res) =&amp;gt; {
  const title = req.query.title;

  Notes.findAll()
    .then((data) =&amp;gt; {
      res.send(data);
    })
    .catch((err) =&amp;gt; {
      res.status(500).send({
        message: err.message || "Some error occured while retrieving Notes",
      });
    });
};

exports.findOne = (req, res) =&amp;gt; {
  const id = req.params.id;
  Notes.findByPk(id)
    .then((data) =&amp;gt; {
      res.send(data);
    })
    .catch((err) =&amp;gt; {
      res.status(500).send({
        message: "Error retrieving Notes with id=" + id,
      });
    });
};

exports.update = (req, res) =&amp;gt; {
  const id = req.params.id;

  Notes.update(req.body, {
    where: { id: id },
  }).then((data) =&amp;gt; {
    if (data) {
      res.send({
        message: "Note was updated successfully",
      });
    } else {
      res.send({
        message: `Cannot update Note with id=${id}`,
      });
    }
  });
};

exports.delete = (req, res) =&amp;gt; {
  const id = req.params.id;

  Notes.destroy({
    where: { id: id },
  }).then((data) =&amp;gt; {
    if (data) {
      res.send({
        message: "Note was delete successfully!",
      });
    } else {
      res.send({
        message: `Cannot delete Note with id=${id}`,
      });
    }
  });
};

&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, we can finally run the application. To do so run&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;node server.js
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you've provided valid credentials for db and followed the steps correctly, you'll see the message &lt;em&gt;Server is running on port 8080&lt;/em&gt; and we'll be able to test the endpoints on Postman. The test result will be similar to mine for create and getAll methods&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--kcteT1yC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1598681245519/5qGmH8jh8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--kcteT1yC--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1598681245519/5qGmH8jh8.png" alt="create.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--JchIHBDQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1598681253574/iryPrzK1a.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--JchIHBDQ--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1598681253574/iryPrzK1a.png" alt="getall.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Thanks for reading. You can find the code for the tutorial on  &lt;a href="https://github.com/rajandmr/postgres-node-sequelize"&gt;Github&lt;/a&gt; &lt;/p&gt;
&lt;/blockquote&gt;

</description>
      <category>node</category>
      <category>restapi</category>
      <category>postgres</category>
    </item>
    <item>
      <title>Managing Secrets with AWS SSM</title>
      <dc:creator>Rajan Prasad</dc:creator>
      <pubDate>Wed, 26 Aug 2020 02:26:34 +0000</pubDate>
      <link>https://dev.to/rajandmr/managing-secrets-with-aws-ssm-44e1</link>
      <guid>https://dev.to/rajandmr/managing-secrets-with-aws-ssm-44e1</guid>
      <description>&lt;p&gt;One of the most burning question i've come across while working in Serverless Architecture is "What's the right way to manage secrets in serverless applications?". The question might have many answers like hard-coding into the application, storing them as .env variables or using dedicated secret files.&lt;/p&gt;

&lt;p&gt;But all of them requires you to write the secrets in the file you're working with, the files you might unknowingly push to GitHub. So is there no any better way ? The answer is: There is !! Using Parameter Store provided under AWS SSM. We will be using aws-cli/aws-console, aws-sdk with NodeJS to store and retrieve a MongoDB connection String.&lt;/p&gt;

&lt;p&gt;Parameter store allows us to create different type of secrets like String type Key-Value Pair, StringList type Key-value pair. We will be using simple String type in our case as mongoDB connection string is just a normal String in the below format so just a simple key-value pair will do the trick.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mongodb+srv://user:password@mycluster-nqdzq.mongodb.net/dbname
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, its to time create our Secret. In order to create the Secret, we will be using AWS Console. So Go to AWS Console, and search for SSM,&lt;br&gt;
There will be a pop-up with &lt;strong&gt;Systems Manager&lt;/strong&gt; , click on that and you'll be forwarded to SSM main page. Now on the left side, you'll find the &lt;strong&gt;Parameter Store&lt;/strong&gt;. After clicking on that, there will be an option called Create parameter if you don't have any Secrets stored YET,  if you already have any Secretes created, you'll be presented with the list along with Create Parameter Option, click on &lt;strong&gt;Create Parameter&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;After clicking on Create Parameter, you'll be presented with a screen similar to :&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--k4o6f_Qo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1597227447683/yBAEixQoy.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--k4o6f_Qo--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://cdn.hashnode.com/res/hashnode/image/upload/v1597227447683/yBAEixQoy.png" alt="aws-ssm.png"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now, its time to fill up the values. Give it a suitable name, in my case i'll write NOTEAPP_CONN_STRING. Descriptions are optional, you can leave that blank, Choose Standard Tier and String in Type and paste the Mongo Connection String. You can also give it some tags which is totally optional, so you can just hit Create Parameter.&lt;/p&gt;

&lt;p&gt;Now, its time to Access it through our Lamda Function. In order to access the Parameter Store, we first have to provide some IAM permissions.&lt;br&gt;
Inside you .yml file under Provider Section in iamRoleStatements Section, copy/paste the following policies:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;iamRoleStatements:
    - Effect: Allow
      Action:
        - "ssm:GetParameter*"
      Resource: "*"
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, inside our handler function, what we will do is, we will simple console log the secret however you can do anything you want once you have the access. So our handler file will look something like this :&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const AWS = require("aws-sdk");
const ssm = new AWS.SSM();

let param = {
  Name: "NOTEAPP_CONN_STRING", // Our Secret Name
  WithDecryption: true,
};

module.exports.handler = async (event) =&amp;gt; {
    let request = await ssm.getParameter(param).promise();
    let conn_string = request.Parameter.Value;

   console.log(conn_string);
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;So we see that there is no trace of our Secret in our Code but it is stored in AWS. This is how you manage the secrets in Serverless applications&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
