<?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: Dev Kadiem</title>
    <description>The latest articles on DEV Community by Dev Kadiem (@kadiemq).</description>
    <link>https://dev.to/kadiemq</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%2F1009275%2F971cf1af-aa72-4e7b-9bff-9183b39952f1.png</url>
      <title>DEV Community: Dev Kadiem</title>
      <link>https://dev.to/kadiemq</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/kadiemq"/>
    <language>en</language>
    <item>
      <title>Advanced ReactJS Tutorial: Master Context In A Few Simple Examples</title>
      <dc:creator>Dev Kadiem</dc:creator>
      <pubDate>Fri, 31 Mar 2023 12:30:09 +0000</pubDate>
      <link>https://dev.to/kadiemq/advanced-reactjs-tutorial-master-context-in-a-few-simple-examples-4olb</link>
      <guid>https://dev.to/kadiemq/advanced-reactjs-tutorial-master-context-in-a-few-simple-examples-4olb</guid>
      <description>&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-images-1.medium.com%2Fmax%2F1024%2F1%2A3bqdJagRzZCQeOjf79_BAA.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-images-1.medium.com%2Fmax%2F1024%2F1%2A3bqdJagRzZCQeOjf79_BAA.jpeg"&gt;&lt;/a&gt;&lt;br&gt;
&lt;em&gt;ReactJS logo&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;React Context transfers data between different levels of your application without "Prop Drilling." It provides a way to pass data through the components tree.&lt;/p&gt;
&lt;h3&gt;
  
  
  Prop &lt;strong&gt;Drilling&lt;/strong&gt;
&lt;/h3&gt;

&lt;p&gt;To further understand react Context, we must first understand the problem it solves. Prop drilling occurs when we continue passing data to child components in an endless way, even though some of those components don't use it; they receive it to pass it to their children.&lt;/p&gt;

&lt;p&gt;Let's take a typical example, a counter app.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function App() {
  const [counter, setCounter] = useState(0);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;AddOneButton setCounter={setCounter} /&amp;gt;
      &amp;lt;Counter counter={counter} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;It has two children components, one to increase the count and another to show the current count.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const AddOneButton = ({setCounter}) =&amp;gt; {
  return (
    &amp;lt;button onClick={() =&amp;gt; setCounter((value) =&amp;gt; value + 1)}&amp;gt;Add One&amp;lt;/button&amp;gt;
  )
}

const Counter = ({counter}) =&amp;gt; {
  return (
    &amp;lt;p&amp;gt;Count: {counter}&amp;lt;/p&amp;gt;
  )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let us say we have a new component called &lt;code&gt;Container&lt;/code&gt; that wraps the &lt;code&gt;AddOneButton&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Container = ({setCounter}) =&amp;gt; {
  return &amp;lt;AddOneButton setCounter={setCounter} /&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And now, inside the App we render the new &lt;code&gt;Container&lt;/code&gt; component.&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;Container setCounter={setCounter} /&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now it's clear that &lt;code&gt;Container&lt;/code&gt; acutely does not need the &lt;code&gt;setCounter&lt;/code&gt; function, we passed it just because &lt;code&gt;AddOneButton&lt;/code&gt; needs it, and this what known as "Prop Drilling" this is why we need the Context Api.&lt;/p&gt;

&lt;h3&gt;
  
  
  NOTE
&lt;/h3&gt;

&lt;p&gt;In this case, we can mitigate the use of prop drilling by making the &lt;code&gt;Container&lt;/code&gt; component a generic component and passing &lt;code&gt;AddOneButton&lt;/code&gt; as a child.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Container = ({children}) =&amp;gt; {
  return (
    {children}
  )
}

export default function App() {
  const [counter, setCounter] = useState(0);

  return (
    &amp;lt;div&amp;gt;
      &amp;lt;Container&amp;gt;
        &amp;lt;AddOneButton setCounter={setCounter} /&amp;gt;
      &amp;lt;/Container&amp;gt;

      &amp;lt;Counter counter={counter} /&amp;gt;
    &amp;lt;/div&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Context with useState
&lt;/h3&gt;

&lt;p&gt;now that we understand prop drilling, we can start using Context Api, but before that, we need to decide what way we will implement Context; there are mainly two ways either with &lt;code&gt;useState&lt;/code&gt; or &lt;code&gt;useReducer&lt;/code&gt; in this section, we will do it using &lt;code&gt;useState&lt;/code&gt;, let us start by importing the required modules.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {createContext, useContext} from "react";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Then we create the Context and its provider.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const CounterContext = createContext(null);

export const CounterContextProvider = ({ children }) =&amp;gt; (
  &amp;lt;CounterContext.Provider value={useState(0)}&amp;gt;
    {children}
  &amp;lt;/CounterContext.Provider&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;the &lt;code&gt;createContext&lt;/code&gt; function initializes the Context, the provider will wrap our application (only the components inside the provider will have access to data), and because we are using context API we don't need to pass anything to &lt;code&gt;Container&lt;/code&gt; or &lt;code&gt;Counter&lt;/code&gt; components.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export default function App() {
  return (
    &amp;lt;CounterContextProvider&amp;gt;
      &amp;lt;Container /&amp;gt;
      &amp;lt;Counter /&amp;gt;
    &amp;lt;/CounterContextProvider&amp;gt;
  );
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now to access the data, we shall use &lt;code&gt;useContext&lt;/code&gt; hook.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Container = () =&amp;gt; {
  return &amp;lt;AddOneButton /&amp;gt;;
};

const AddOneButton = () =&amp;gt; {
  const [, setCounter] = useContext(CounterContext);
  return (
    &amp;lt;button onClick={() =&amp;gt; setCounter((value) =&amp;gt; value + 1)}&amp;gt;Add One&amp;lt;/button&amp;gt;
  );
};

const Counter = () =&amp;gt; {
  const [counter] = useContext(CounterContext);
  return &amp;lt;p&amp;gt;Count: {counter}&amp;lt;/p&amp;gt;;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h3&gt;
  
  
  Context with useReducer
&lt;/h3&gt;

&lt;p&gt;Note: It's recommended to use &lt;code&gt;useReducer&lt;/code&gt; if our state is more complex.&lt;/p&gt;

&lt;p&gt;Let us start by importing the required modules.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import { createContext, useContext, useReducer } from "react";
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's create a reducer and plug it into our context data.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const reducer = (state, action) =&amp;gt; {
  switch(action.type) {
    case "increment":
      return state + 1;
    default:
      return state
  }
}

export const CounterContext = createContext(null);

export const CounterContextProvider = ({ children }) =&amp;gt; (
  &amp;lt;CounterContext.Provider value={useReducer(reducer, 0)}&amp;gt;
    {children}
  &amp;lt;/CounterContext.Provider&amp;gt;
);
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The hook returns a tuple, the first element is the value, and the second is the dispatch function.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Container = () =&amp;gt; {
  return &amp;lt;AddOneButton /&amp;gt;;
};

const AddOneButton = () =&amp;gt; {
  const [, dispatch] = useContext(CounterContext);
  return (
    &amp;lt;button onClick={() =&amp;gt; dispatch({type: "increment"})}&amp;gt;Add One&amp;lt;/button&amp;gt;
  );
};

const Counter = () =&amp;gt; {
  const [counter] = useContext(CounterContext);
  return &amp;lt;p&amp;gt;Count: {counter}&amp;lt;/p&amp;gt;;
};
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And basically, that's how context Api works.&lt;/p&gt;

</description>
      <category>webdev</category>
      <category>javascript</category>
      <category>react</category>
      <category>learnwebdevelopment</category>
    </item>
    <item>
      <title>Typescript, NextJS, Strapi, and GraphQL: An Overview Of How I Created My Blog</title>
      <dc:creator>Dev Kadiem</dc:creator>
      <pubDate>Fri, 03 Feb 2023 04:48:18 +0000</pubDate>
      <link>https://dev.to/kadiemq/typescript-nextjs-strapi-and-graphql-an-overview-of-how-i-created-my-blog-61g</link>
      <guid>https://dev.to/kadiemq/typescript-nextjs-strapi-and-graphql-an-overview-of-how-i-created-my-blog-61g</guid>
      <description>&lt;p&gt;First things first, let's introduce the stack we are going to use. Typescript is "Is a strongly typed programming language that builds on JavaScript, giving you better tooling at any scale." in simple words, Typescript enhances coding safety and enables more OOP for the web.&lt;/p&gt;

&lt;p&gt;NextJS is a framework that "Enables you to create full-stack web applications by extending the latest React features" in simple words, NextJS is an upgrade over the widely used ReactJS library.&lt;/p&gt;

&lt;p&gt;Strapi is an open-source headless CMS. CMS stands for "content management system," allowing us to create, manage, modify, and publish content in a user-friendly interface without programming knowledge. Headless means there is no built-in end-user UI; we can use whatever frontend technology we want.&lt;/p&gt;

&lt;p&gt;GraphQL is "A query language for APIs and a runtime for fulfilling those queries with your existing data" in simple words, it's a language used to query data and get the fields you want.&lt;/p&gt;

&lt;p&gt;Note: this is an overview, which means there are aspects I will not go over, such as styling and best HTML tags; this blog is meant to showcase the functionality of creating a Blog using the technologies mentioned above.&lt;/p&gt;

&lt;h3&gt;
  
  
  Initializing The Project
&lt;/h3&gt;

&lt;p&gt;Now, let's create the folders using the command line (because it's cooler), so the first command is to create a folder containing all our files.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;mkdir my-personal-website
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now, let's create folders for both NextJS and Strapi.&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-personal-website
mkdir frontend, strapi
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Initialize Strapi
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd strapi
npx create-strapi-app@latest . --ts --quickstart
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Parameter &lt;code&gt;@latest&lt;/code&gt; means it will install the latest version, &lt;code&gt;.&lt;/code&gt; means we want to create the project in the current folder, then &lt;code&gt;— ts&lt;/code&gt; means it will use TypeScript, and lastly &lt;code&gt;— quickstart&lt;/code&gt; it will install with default settings; when the installation finishes, it will open a new window on the address &lt;code&gt;/admin/auth/register-admin&lt;/code&gt;, asking you to create a new admin account; go ahead and create a new account. Note: using &lt;code&gt;— ts&lt;/code&gt; is optional since I won't change the source code in this post.&lt;/p&gt;

&lt;h4&gt;
  
  
  Initialize NextJS
&lt;/h4&gt;



&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;cd frontend
npx create-next-app@latest . --ts
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And lastly, remember to init a Github repo, but I'll not cover it in this post.&lt;/p&gt;

&lt;h3&gt;
  
  
  Starting with Strapi
&lt;/h3&gt;

&lt;p&gt;I like to start with the backend in my projects, so I will start with Strapi as it's considered a backend.&lt;/p&gt;

&lt;h4&gt;
  
  
  Installing Graphql
&lt;/h4&gt;

&lt;p&gt;One advantage of using Strapi is its easy integration with Graphql. To install the Graphql plugin, we need the 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 run strapi install graphql
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If you encounter the &lt;code&gt;_Duplicate "graphql" modules&lt;/code&gt; error, don't worry; it's easy to fix; all you need to do is to delete the &lt;strong&gt;&lt;em&gt;node_modules&lt;/em&gt;&lt;/strong&gt; folder and &lt;strong&gt;&lt;em&gt;package-lock.json&lt;/em&gt;&lt;/strong&gt; , then we need to reinstall packages.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;rm node_modules
rm package-lock.json
npm install
npm run strapi dev
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;After successful installation, we can now visit the URL &lt;code&gt;/graphql&lt;/code&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  Creating The Blog Post Collection
&lt;/h4&gt;

&lt;p&gt;Open the Strapi homepage on URL &lt;code&gt;http://localhost:1337/admin/&lt;/code&gt;, and after you sign in, go to the &lt;strong&gt;&lt;em&gt;Content-Type Builder&lt;/em&gt;&lt;/strong&gt; page, click on &lt;strong&gt;&lt;em&gt;Create new collection type&lt;/em&gt;&lt;/strong&gt; button, then in the &lt;strong&gt;&lt;em&gt;Display name&lt;/em&gt;&lt;/strong&gt; field, fill it in with an appropriate name; I will choose &lt;strong&gt;&lt;em&gt;Blog Post&lt;/em&gt;&lt;/strong&gt; , then click continue.&lt;/p&gt;

&lt;p&gt;Now, we are in fields selection for our new collection; you can customize it however you want; for the sake of simplicity, I will add three fields, a &lt;strong&gt;&lt;em&gt;Text&lt;/em&gt;&lt;/strong&gt; field for the title, another &lt;strong&gt;&lt;em&gt;Text&lt;/em&gt;&lt;/strong&gt; field for the description, and lastly, a &lt;strong&gt;&lt;em&gt;Rich Text&lt;/em&gt;&lt;/strong&gt; field for the body, next click save.&lt;/p&gt;

&lt;p&gt;Now that we have a collection, we need to populate it with data, go to &lt;strong&gt;&lt;em&gt;Content Manager&lt;/em&gt;&lt;/strong&gt; , and now we can see the newly created collection, click on it, then &lt;strong&gt;&lt;em&gt;Create new entry&lt;/em&gt;&lt;/strong&gt; button, and fill it with any data you want, then click save and publish.&lt;/p&gt;

&lt;h4&gt;
  
  
  Accessibility Option 1: Publicly Accessible
&lt;/h4&gt;

&lt;p&gt;Before we can access our data through Graphql, we need to make it accessible; you can make it publicly accessible or only for authenticated users. I will choose a publicly accessible collection since I'm not storing sensitive data.&lt;/p&gt;

&lt;p&gt;To access it publicly, go to &lt;strong&gt;&lt;em&gt;Settings,&lt;/em&gt;&lt;/strong&gt; then roles, click on &lt;strong&gt;&lt;em&gt;Public&lt;/em&gt;&lt;/strong&gt; , scroll down to the collection you created (in my case, it's Blog-post), click it, then tick &lt;strong&gt;&lt;em&gt;find&lt;/em&gt;&lt;/strong&gt; and  &lt;strong&gt;&lt;em&gt;findOne.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Accessibility Option 2: Authenticated Only
&lt;/h4&gt;

&lt;p&gt;However, should you choose the authenticated way, here is how to do it. There are two ways to achieve this; the first one is to create &lt;strong&gt;&lt;em&gt;API Token&lt;/em&gt;&lt;/strong&gt; in the settings page, then we need to attach it with our requests by adding it to the headers as an &lt;strong&gt;&lt;em&gt;Authorization&lt;/em&gt;&lt;/strong&gt; header and setting the value to be &lt;strong&gt;&lt;em&gt;bearer &lt;/em&gt;&lt;/strong&gt; , the second way is to create a new entry in the &lt;strong&gt;&lt;em&gt;User&lt;/em&gt;&lt;/strong&gt; collection, via &lt;strong&gt;&lt;em&gt;Content Manager&lt;/em&gt;&lt;/strong&gt; page, then send a &lt;strong&gt;&lt;em&gt;Post&lt;/em&gt;&lt;/strong&gt; request to &lt;code&gt;/api/auth/local&lt;/code&gt; with an attached JSON body containing identifier which could be either the username or email, and password, of the newly created user in the &lt;strong&gt;&lt;em&gt;User&lt;/em&gt;&lt;/strong&gt; collection, &lt;strong&gt;NOT THE ADMIN ACCOUNT WE CREATED IN INITIALIZE STRAPI.&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;{
 "identifier": "email or username",
 "password": "password"
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;If the request were successful, you would get a response containing the &lt;strong&gt;&lt;em&gt;JWT&lt;/em&gt;&lt;/strong&gt; field, and now we need to do the same thing, send it with each request via headers in an &lt;strong&gt;&lt;em&gt;Authorization&lt;/em&gt;&lt;/strong&gt; header and set the value to be &lt;strong&gt;&lt;em&gt;bearer .&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Now to access it, go to &lt;strong&gt;&lt;em&gt;Settings,&lt;/em&gt;&lt;/strong&gt; then roles, click on &lt;strong&gt;&lt;em&gt;Authenticated&lt;/em&gt;&lt;/strong&gt; , scroll down to the collection you created (in my case, it's Blog-post), click it, then tick &lt;strong&gt;&lt;em&gt;find&lt;/em&gt;&lt;/strong&gt; and  &lt;strong&gt;&lt;em&gt;findOne.&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;h4&gt;
  
  
  Testing Graphql Endpoint
&lt;/h4&gt;

&lt;p&gt;To access Graphql go to &lt;code&gt;/graphql&lt;/code&gt;, and now, we can see the input field on the left side; here, we will put our queries to query our Strapi application, an example of a query:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;query {
  blogPosts {
    data {
      id
      attributes {
        title
        description
        body
      }
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And in my case, the response is:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;  "data": {
    "blogPosts": {
      "data": [
        {
          "id": "1",
          "attributes": {
            "title": "test",
            "description": "test",
            "body": "test"
          }
        }
      ]
    }
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Testing Rest Endpoint
&lt;/h4&gt;

&lt;p&gt;All we need to do is send a GET request to &lt;code&gt;/api/blog-posts/&lt;/code&gt;. An example of a response would be:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;{
    "data": [
        {
            "id": 1,
            "attributes": {
                "title": "test",
                "description": "test",
                "body": "test",
                "createdAt": "2023-01-30T20:28:28.141Z",
                "updatedAt": "2023-01-30T20:28:29.027Z",
                "publishedAt": "2023-01-30T20:28:29.025Z"
            }
        }
    ],
    "meta": {
        "pagination": {
            "page": 1,
            "pageSize": 25,
            "pageCount": 1,
            "total": 1
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We have finished the Strapi section and will continue with NextJS.&lt;/p&gt;

&lt;h3&gt;
  
  
  Starting With NextJS
&lt;/h3&gt;

&lt;p&gt;Create a new directory inside the &lt;strong&gt;&lt;em&gt;pages&lt;/em&gt;&lt;/strong&gt; directory and name it &lt;strong&gt;&lt;em&gt;blog&lt;/em&gt;&lt;/strong&gt; ; next, create a new &lt;code&gt;index.tsx&lt;/code&gt; file and initialize a basic react component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {NextPage} from "next";

interface Props {
}

const About: NextPage&amp;lt;Props&amp;gt; = (Props) =&amp;gt; {
    return (
        &amp;lt;p&amp;gt;About Page&amp;lt;/p&amp;gt;
    )
}

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

&lt;/div&gt;



&lt;p&gt;Now we are to visit &lt;code&gt;blog&lt;/code&gt; and view the About Page.&lt;/p&gt;

&lt;h4&gt;
  
  
  Creating Interfaces
&lt;/h4&gt;

&lt;p&gt;We will need a few interfaces; let's start by creating a &lt;strong&gt;&lt;em&gt;common&lt;/em&gt;&lt;/strong&gt; folder containing all of our basic modules, then create another folder called &lt;strong&gt;&lt;em&gt;types&lt;/em&gt;&lt;/strong&gt; which will contain all our types and interfaces then create a new typescript I will name &lt;strong&gt;&lt;em&gt;BlogInterfaces&lt;/em&gt;&lt;/strong&gt; ; now let the first interface, which is going to &lt;code&gt;IBlogIdentification&lt;/code&gt; and it will contain our identification field; in our case, it's the id of the blog post.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export interface IBlogIdentification {
    id: string
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we need an interface to hold the blog fields' title, description, and body; name it &lt;code&gt;IBlogFields&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export interface IBlogFields {
    title: string,
    description: string,
    body: string
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Next, we need an interface for blog attributes we will receive from the GraphQL query; name it &lt;code&gt;IBlogAttributes&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export interface IBlogAttributes {
    attributes: Partial&amp;lt;IBlogFields&amp;gt; &amp;amp; Pick&amp;lt;IBlogFields, 'title'&amp;gt;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;I have used Partial and Pick utility types to make all of &lt;code&gt;IBlogFields&lt;/code&gt; fields optional except title.&lt;/p&gt;

&lt;p&gt;Lastly, we will need an interface to handle the whole blog entry; name it &lt;code&gt;IBlog&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export interface IBlog extends IBlogIdentification, IBlogAttributes{}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now let's update the Props interface on the &lt;strong&gt;&lt;em&gt;blog&lt;/em&gt;&lt;/strong&gt;  page.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Props {
    blogs: IBlog[]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  GraphQL Works
&lt;/h4&gt;

&lt;p&gt;Before we start fetching data, we need to do GraphQL Works. First, we need to install two packages to be able to interact with GraphQL; we will need the &lt;code&gt;graphql&lt;/code&gt; and &lt;code&gt;@apollo/client packages&lt;/code&gt;.&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 graphql, @apollo/client
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Second, we need to write the queries; we will need three queries, the first to list blogs, the second is to get a single blog, and the third is to get the list of blog Ids'; in the &lt;strong&gt;&lt;em&gt;common&lt;/em&gt;&lt;/strong&gt; folder, create a new folder and call it graphql, then create a new file and call it &lt;code&gt;queries.tsx&lt;/code&gt;, and add the following queries.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const LIST_BLOG = gql(`query {
  blogPosts {
    data {
      id
      attributes {
        title
      }
    }
  }
}`)

export const SINGLE_BLOG = gql(`query ($blogId: string!) {
  blogPosts(filters: {id: {eq: $blogId}}) {
    data {
      id
      attributes {
        title
        description
        body
      }
    }
  }
}`)

export const LIST_ID = gql(`query {
  blogPosts {
    data {
      id
    }
  }
}`)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The third thing we need is to store Strapi's address, and the most convenient way is to store it inside the &lt;strong&gt;&lt;em&gt;env&lt;/em&gt;&lt;/strong&gt; variables; NextJS already comes with a built-in environment variable module, so there is no need to install &lt;code&gt;dotenv&lt;/code&gt;, all we need to do is to go to &lt;code&gt;next-config.js&lt;/code&gt;, and add the following export.&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 = {
  env: {
    STRAPI_ADDRESS: "http://127.0.0.1:1337/graphql"
  },
  nextConfig,
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And the last thing we need is an &lt;code&gt;ApolloClient&lt;/code&gt; to be to connect with the GraphQL server, inside the &lt;strong&gt;&lt;em&gt;graphql&lt;/em&gt;&lt;/strong&gt; folder, create a new file and name it &lt;code&gt;client.tsx&lt;/code&gt;, then add 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;import {ApolloClient, InMemoryCache, NormalizedCacheObject} from "@apollo/client";

const client: ApolloClient&amp;lt;NormalizedCacheObject&amp;gt; = new ApolloClient({
    uri: process.env.STRAPI_ADDRESS,
    cache: new InMemoryCache(),
});

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

&lt;/div&gt;



&lt;p&gt;Note: the cache is a way for the &lt;code&gt;ApolloClient&lt;/code&gt; to cache results, it's a big topic and out of scope for this post. More info can be found &lt;a href="https://www.apollographql.com/docs/react/caching/overview" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;h4&gt;
  
  
  Fetching Data
&lt;/h4&gt;

&lt;p&gt;Now we can start implementing the fetching procedure; let's start by creating the &lt;code&gt;getStaticProps&lt;/code&gt; function:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const getStaticProps: GetStaticProps&amp;lt;Props&amp;gt; = async () =&amp;gt; {

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

&lt;/div&gt;



&lt;p&gt;We are going to use &lt;code&gt;getStaticProps&lt;/code&gt; because it will pre-render the page at build time, and the data will not be changing consistently; there is no need to send a request to our CMS every time.&lt;/p&gt;

&lt;p&gt;Now we can start querying Strapi; let's get a list of blogs.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    const {data} = await client.query({query: LIST_BLOG})
    const blogs: IBlog[] = data.blogPosts.data;

    return {
        props: {
            blogs
        }
    }
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h4&gt;
  
  
  Displaying Blog List
&lt;/h4&gt;

&lt;p&gt;Now that we can retrieve a list of blogs, we can start displaying them; we need new folders. To make it easier, I will show a demo below of my project structure.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;common
--elements
----blog
------BlogTitle.tsx

modules
--blog
----BlogCardList.tsx
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We need two files, &lt;code&gt;BlogTitle&lt;/code&gt; will render the title of a blog, and &lt;code&gt;BlogCardList&lt;/code&gt; will use &lt;code&gt;BlogTitle&lt;/code&gt; to render a list of blogs, let's start with &lt;code&gt;BlogTitle&lt;/code&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Props {
    title: string
    isClickable: boolean
    blogId?: string
}

const BlogTitle: NextPage&amp;lt;Props&amp;gt; = ({title, isClickable, blogId}) =&amp;gt; {
    if(isClickable &amp;amp;&amp;amp; blogId) {
        return (
            &amp;lt;Link href={`/blog/${blogId}`}&amp;gt;{title}&amp;lt;/Link&amp;gt;   
        )
    } else {
        return (
            &amp;lt;p&amp;gt;{title}&amp;lt;/p&amp;gt;
        )
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Note: Because I know in the commercial version, I will be using the blog title in multiple locations, and it will have more props and functionality attached to it, I chose to make the blog title a separate component; however, you can choose not to.&lt;/p&gt;

&lt;p&gt;Now to the list of cards.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface Props {
    blogs: IBlog[]
}

const BlogCardList: NextPage&amp;lt;Props&amp;gt; = ({blogs}) =&amp;gt; {
    return (
        &amp;lt;div&amp;gt;
            {blogs.map((blog, i) =&amp;gt; {
                return (
                    &amp;lt;div key={i}&amp;gt;
                        &amp;lt;BlogTitle 
                            title={blog.attributes.title} 
                            isClickable={true} 
                            blogId={blog.id}
                        /&amp;gt;
                    &amp;lt;/div&amp;gt;
                );
            })}
        &amp;lt;/div&amp;gt;
    )
}

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

&lt;/div&gt;



&lt;p&gt;Now to show the list, we need to add &lt;code&gt;BlogCardList&lt;/code&gt; to about page.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Blog: NextPage&amp;lt;Props&amp;gt; = ({blogs}) =&amp;gt; {
    return (
        &amp;lt;BlogCardList blogs={blogs}/&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now if we go to &lt;code&gt;/blog&lt;/code&gt;, we should see a list of blog titles.&lt;/p&gt;

&lt;h4&gt;
  
  
  Displaying A Single Blog Post
&lt;/h4&gt;

&lt;p&gt;Let's start creating the individual blog post page, create a new file, and call it &lt;code&gt;[id].tsx&lt;/code&gt; inside the &lt;strong&gt;&lt;em&gt;blog&lt;/em&gt;&lt;/strong&gt; directory inside the &lt;strong&gt;&lt;em&gt;pages&lt;/em&gt;&lt;/strong&gt; directory, initialize a new basic react component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;import {NextPage} from "next";
import {IBlog} from "@/common/types/BlogInterfaces";

interface Props {
    blog: IBlog
}

const client = new ApolloClient({
    uri: process.env.STRAPI_ADDRESS,
    cache: new InMemoryCache()
});

const Blog: NextPage&amp;lt;Props&amp;gt; = ({blog}) =&amp;gt; {
    return (
        &amp;lt;p&amp;gt;Blog Here&amp;lt;p/&amp;gt;
    )
}

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

&lt;/div&gt;



&lt;p&gt;We are going to utilize NextJS's &lt;code&gt;getStaticPaths&lt;/code&gt; and &lt;code&gt;getStaticProps&lt;/code&gt; functions, more info can be found &lt;a href="https://nextjs.org/docs/api-reference/data-fetching/get-static-paths" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export const getStaticPaths: GetStaticPaths = async () =&amp;gt; {
    const {data} = await client.query({query: LIST_ID })
    const ids: IBlogIdentification[] = data.blogPosts.data;

    const paths = ids.map(id =&amp;gt; {
        return {params: {...id}}
    })

    return {
        paths,
        fallback: true
    }
}

export const getStaticProps: GetStaticProps&amp;lt;Props&amp;gt; = async ({params}) =&amp;gt; {
    console.log()
    const {data} = await client.query({query: SINGLE_BLOG, variables: {blogId: params!.id}})
    const blog: IBlog = data.blogPosts.data[0];

    return {
        props: {
            blog
        }
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And now, we can access the blog data inside the component.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const Blog: NextPage&amp;lt;Props&amp;gt; = ({blog}) =&amp;gt; {
    console.log(blog)
    return (
        &amp;lt;div&amp;gt;
            &amp;lt;p&amp;gt;{blog.id}&amp;lt;/p&amp;gt;
            &amp;lt;p&amp;gt;{blog.attributes.title}&amp;lt;/p&amp;gt;
            &amp;lt;p&amp;gt;{blog.attributes.description}&amp;lt;/p&amp;gt;
            &amp;lt;p&amp;gt;{blog.attributes.body}&amp;lt;/p&amp;gt;
        &amp;lt;/div&amp;gt;
    )
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now our blog is functional; we can retrieve and display a list of blogs and a single blog post.&lt;/p&gt;

</description>
      <category>react</category>
      <category>webdev</category>
      <category>softwaredevelopment</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Upgrade Your Development Skills: Introduction to SOLID Principles</title>
      <dc:creator>Dev Kadiem</dc:creator>
      <pubDate>Thu, 26 Jan 2023 08:26:56 +0000</pubDate>
      <link>https://dev.to/kadiemq/upgrade-your-development-skills-introduction-to-solid-principles-57ii</link>
      <guid>https://dev.to/kadiemq/upgrade-your-development-skills-introduction-to-solid-principles-57ii</guid>
      <description>&lt;p&gt;A clear distinction between junior and senior developers is how well senior developers future-proof their programs; one way of achieving this is to use a well-known code or rules, like SOLID principles, which Robert C. Martin developed in his essay, "Design Principles and Design Patterns."&lt;/p&gt;

&lt;p&gt;SOLID is an acronym for single responsibility, open-closed, Liskov substitution, interface segregation, and dependency inversion principle, and it's important to state that SOLID is mainly for OOP.&lt;/p&gt;

&lt;p&gt;It's important to recall that this is an introduction; thus, I will use easy scenarios, and the examples shown are for learning purposes only and not for commercial use. Lastly, I'll use sudo code to make it reachable to most people.&lt;/p&gt;




&lt;h2&gt;
  
  
  Single Responsibility Principle
&lt;/h2&gt;

&lt;p&gt;The single responsibility principle states, "A class should have only one reason to change." According to the previous state, each class is responsible for only one part during the software lifespan.&lt;/p&gt;

&lt;p&gt;To kick off the article, I'll create a simple User class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class User {
    function profile()
    function login()
    function register()
    function sendVerificationEmail()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As we can see, the class is responsible for more than one part, and my way of applying the principles is the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class User {
    function profile()
}

class Authentication {
    function login()
}

class Signup {
    function register()
    function sendVerificationEmail()
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We now have three classes, each responsible for only one part.&lt;/p&gt;




&lt;h2&gt;
  
  
  Open Closed Principle
&lt;/h2&gt;

&lt;p&gt;The open-closed principle states, "A class should be open to extension but closed to modifying." According to the previous state, each class should be written in a way that allows the addition of functionality but does not allow alteration of its core.&lt;/p&gt;

&lt;p&gt;To demonstrate a demo of this principle, I'll create another User class but this time, it will have a variable called &lt;code&gt;type&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class User {
    var type

    constructor(var type) {
        this.type = type
    }

    function doSomething() {
      if(type == "normal") {
        // ...
      } else if(type == "professional") {
        // ...
      }
    }

    // ...
}

User normalUser = new User("normal")
User professionalUser = new User("professional")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The class is open for modification because &lt;code&gt;type&lt;/code&gt; has a direct influence on the class's functionality; this is an example of why we need the open-closed principle. Let's see an example of how to apply the principle here:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;abstract class User {
    abstract function doSomething()
}

class NormalUser Inherits User {
    function doSomething() {
      // ...
    }
}

class ProfessionalUser Inherits User {
    function doSomething() {
      // ...
    }
}

User normalUser = new NormalUser()
User professionalUser = new ProfessionalUser()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;By implementing the principle, we can write a more precise functionality.&lt;/p&gt;




&lt;h2&gt;
  
  
  Liskov Substitution Principle
&lt;/h2&gt;

&lt;p&gt;The Liskov substitution principle states, "if S is a subtype of T, then objects of type T may be replaced with objects of type S" Liskov substitution is better explained with an example:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;abstract class Employee {
    abstract function getBonus()
}

class HardWorkingEmployee Inherits Employee {
    function getBonus() {
        // ...
    }
}

class LackingEmployee Inherits Employee {
    function getBonus() {
        Error
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And now, to instantiate an instance of &lt;code&gt;HardWorkingEmployee&lt;/code&gt; class:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;Employee employee = new HardWorkingEmloyee()
employee.getBonus()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The example above would work perfectly, now let's change &lt;code&gt;HardWorkingEmployee&lt;/code&gt; with &lt;code&gt;LackingEmployee&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;employee = new LackingEmployee()
employee.getBonus()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The example above would not work because, &lt;code&gt;LackingEmployee&lt;/code&gt; does not implement &lt;code&gt;bonus&lt;/code&gt; function, even though they both are of type &lt;code&gt;Employee&lt;/code&gt;, and that is a violation of the Liskov Substitution; an easy fix for this situation is the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;abstract class Employee {
    // ...
}

interface EligableForBonus {
    function getBonus()
}

class HardWorkingEmployee Inherits Employee, EligableForBonus {
    function getBonus() {
        // ...
    }
}

class LackingEmployee Inherits Employee {
    // ...
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now &lt;code&gt;LackingEmployee&lt;/code&gt; does not inherit any non-implemented functionality.&lt;/p&gt;




&lt;h2&gt;
  
  
  Interface Segregation Principle
&lt;/h2&gt;

&lt;p&gt;The interface segregation principle states, "Clients should not be forced to depend upon interfaces that they do not use." It means that when a class inherits a parent, it should implement all of its functionality.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface UserFunctions {
    function function1()
    function function2()
    function function3()
    function function4()
}

class User inherits UserFunctions {
    function function1() {
      // ..
    }

    function function2() {
      // ..
    }

    function function3() {
      // ..
    }

    function function4() {
      Error
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The User class does not implement &lt;code&gt;function4&lt;/code&gt; and thus, it violates the interface segregation principle; one way of fixing it is the following:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;interface CoreUserFunctions {
    function function1()
    function function2()
    function function3()
}

interface ExtraUserFunctions {
    function function4()
}

class BasicUser inherits UserFunctions {
    function function1() {
      // ..
    }

    function function2() {
      // ..
    }

    function function3() {
      // ..
    }
}

class UpgradedUser inherits UserFunctions, ExtraUserFunctions {
    function function1() {
      // ..
    }

    function function2() {
      // ..
    }

    function function3() {
      // ..
    }

    function function4() {
      // ..
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we have &lt;code&gt;BasicUser&lt;/code&gt; and &lt;code&gt;UpgradedUser&lt;/code&gt; and both fully implement what they inherit.&lt;/p&gt;




&lt;h2&gt;
  
  
  Dependency Inversion Principle
&lt;/h2&gt;

&lt;p&gt;The Dependency Inversion Principle states, "The interaction between high level and low level modules should be thought of as an abstract interaction between them." It means that if we have interactions between high-level and low-level modules or classes, we should add a middle layer because they both operate at different levels of complexity.&lt;br&gt;
&lt;br&gt;
 &lt;/p&gt;
&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class DataAccesslayer {
    function saveToDatabase(data) {
        // ...
    }
}

class User {
    DataAccesslayer dataAccesslayer
    dataAccesslayer.saveToDatabase(data)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;


&lt;p&gt;The example above does not implement the Dependency inversion principle, thus any modification to &lt;code&gt;DataAccessLayer&lt;/code&gt; might means we need to modify &lt;code&gt;User&lt;/code&gt; class also, a better implementation would be 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;interface DataAccesslayerInterface {
    function saveToDatabase(data)
}

class DataAccesslayer inherits DataAccesslayerInterface {
    function saveToDatabase(data) {
        // ...
    }
}

class User {
    DataAccesslayerInterface dataAccesslayer
    dataAccesslayer.saveToDatabase(data)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Now we have an abstraction layer, which means that modification on &lt;code&gt;DataAccesslayer&lt;/code&gt; will no longer need modification on User class because the abstraction layer does not change; thus function signature does not change&lt;/p&gt;

</description>
      <category>devplusplus</category>
      <category>announcement</category>
      <category>community</category>
    </item>
    <item>
      <title>Python Django: Create a more secure database by using a custom field</title>
      <dc:creator>Dev Kadiem</dc:creator>
      <pubDate>Tue, 17 Jan 2023 17:19:05 +0000</pubDate>
      <link>https://dev.to/kadiemq/python-django-create-a-more-secure-database-by-using-a-custom-field-1b9l</link>
      <guid>https://dev.to/kadiemq/python-django-create-a-more-secure-database-by-using-a-custom-field-1b9l</guid>
      <description>&lt;p&gt;One way of enhancing the security of a database is by encrypting it. Luckily by utilizing Django, we can do this automatically. We only need the signing and models packages from the core Django packages.&lt;/p&gt;

&lt;p&gt;Let's start by importing the required packages:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.core import signing
from django.db.models import TextField
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;First, the &lt;code&gt;signing&lt;/code&gt; is a cryptographic signing package; it allows encrypting and decrypting using the &lt;code&gt;SECRET_KEY&lt;/code&gt; found in &lt;code&gt;settings.py&lt;/code&gt;; more info can be found at the bottom, and we need the &lt;code&gt;TextField&lt;/code&gt; because we will extend the default one with more functionality.&lt;/p&gt;




&lt;p&gt;Now let's create and init the new field. I'll name it &lt;code&gt;EncryptedTextField&lt;/code&gt;:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;class EncryptedTextField(models.TextField):
    def __init__(self, *args, **kwargs):
        super(EncryptedTextField, self).__init__(*args, **kwargs)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;Now for the encrypting part:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    def get_db_prep_save(self, value, connection):
        value = super().get_db_prep_value(value, connection)
        if value is None:
            return value

        if len(value) == 0:
            return value

        return ((signing.dumps(str(value))).encode('utf-8')).decode('utf-8')
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;get_db_prep_save&lt;/code&gt; is a function that runs when we try to save data to the database; we are getting the raw data by &lt;code&gt;get_db_prep_value&lt;/code&gt; and then return an encrypted version of it &lt;code&gt;return ((signing.dumps(str(value))).encode('utf-8')).decode('utf-8')&lt;/code&gt;. More info can be found at the bottom.&lt;/p&gt;




&lt;p&gt;Now for the decrypting part:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;    def from_db_value(self, value, *args, **kwargs):
        if value is None:
            return value

        if len(value) == 0:
            return value

        return signing.loads(value)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The &lt;code&gt;def from_db_value&lt;/code&gt; is a function that runs when we try to get data from the database, &lt;code&gt;value&lt;/code&gt; here represents the encrypted data, so we need to decrypt it, which is done here &lt;code&gt;return signing.loads(value)&lt;/code&gt;. More info can be found at the bottom.&lt;/p&gt;




&lt;p&gt;Example of usage:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;public_api = EncryptedTextField()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;Example of a full code:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from django.db.models import TextField
from django.core import signing

class EncryptedTextField(models.TextField):
    def __init__(self, *args, **kwargs):
        super(EncryptedTextField, self).__init__(*args, **kwargs)

    def get_db_prep_save(self, value, connection):
        value = super().get_db_prep_value(value, connection)
        if value is None:
            return value

        if len(value) == 0:
            return value

        return ((signing.dumps(str(value))).encode('utf-8')).decode('utf-8')

    def to_python(self, value):
        return value

    def from_db_value(self, value, *args, **kwargs):
        if value is None:
            return value

        if len(value) == 0:
            return value
        return signing.loads(value)
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;






&lt;p&gt;Links to more info:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;signing&lt;/code&gt; package: &lt;a href="https://docs.djangoproject.com/en/4.1/topics/signing/"&gt;https://docs.djangoproject.com/en/4.1/topics/signing/&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;get_db_prep_save&lt;/code&gt; function:&lt;br&gt;
&lt;a href="https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.Field.get_db_prep_save"&gt;https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.Field.get_db_prep_save&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;li&gt;&lt;p&gt;The &lt;code&gt;from_db_value&lt;/code&gt; function:&lt;br&gt;
&lt;a href="https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.Field.from_db_value"&gt;https://docs.djangoproject.com/en/4.1/ref/models/fields/#django.db.models.Field.from_db_value&lt;/a&gt;&lt;/p&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>django</category>
      <category>python</category>
      <category>database</category>
      <category>security</category>
    </item>
    <item>
      <title>Do you know why array[index] is n(1)?</title>
      <dc:creator>Dev Kadiem</dc:creator>
      <pubDate>Mon, 16 Jan 2023 16:14:29 +0000</pubDate>
      <link>https://dev.to/kadiemq/do-you-know-why-arrayindex-is-n1-j2o</link>
      <guid>https://dev.to/kadiemq/do-you-know-why-arrayindex-is-n1-j2o</guid>
      <description>&lt;p&gt;When I started working in web development, I had no idea why &lt;code&gt;array[index]&lt;/code&gt; is &lt;code&gt;n(1)&lt;/code&gt; because I was primarily working with high-level languages, and the mystery carried on with me until I started working with low-level language Rust.&lt;/p&gt;

&lt;p&gt;To answer why it's &lt;code&gt;n(1)&lt;/code&gt;, we must first understand what a pointer is: an object that stores a memory address. Thus when we use a pointer, we are accessing a memory location rather than the underlying data.&lt;/p&gt;

&lt;p&gt;As for the array data structure, an array is a collection of elements stored in a contiguous memory location; it fulfills an entire row of memory addresses with no spaces or gaps between elements.&lt;/p&gt;

&lt;p&gt;Now that we have defined what a pointer and array are, it won't be a surprise when I say that when we instantiate an array, we create a pointer (The naming differs between languages)&lt;/p&gt;

&lt;p&gt;&lt;code&gt;let arr = [1,2,3,4,5]&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Now that we know that &lt;code&gt;arr&lt;/code&gt; is a pointer (with extra data like length, size), it's safe to say that &lt;code&gt;arr&lt;/code&gt; is pointing to the memory address of the first element of the array. In other words, the memory address of &lt;code&gt;arr&lt;/code&gt; and the memory address of &lt;code&gt;arr[0]&lt;/code&gt; is the same.&lt;/p&gt;

&lt;p&gt;Lastly, an example would make everything clear. Let's say that &lt;code&gt;arr&lt;/code&gt; is in memory location 10, which means that the first element is also in memory location 10; now, assuming that &lt;code&gt;Number&lt;/code&gt; in Javascript is 8 Bytes, the second element will be in location 18, and the third will be in 26.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;arr[0] -&amp;gt; stored in memory location 10&lt;/code&gt;&lt;br&gt;
&lt;code&gt;arr[1] -&amp;gt; stored in memory location 18&lt;/code&gt;&lt;br&gt;
&lt;code&gt;arr[2] -&amp;gt; stored in memory location 26&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;And that is why &lt;code&gt;array[index]&lt;/code&gt; is &lt;code&gt;n(1)&lt;/code&gt; because all we need to get is the &lt;code&gt;memory location of the first element + (Data size in bytes * index)&lt;/code&gt;.&lt;/p&gt;

</description>
      <category>gratitude</category>
      <category>modding</category>
    </item>
  </channel>
</rss>
