<?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: Rida F Najid</title>
    <description>The latest articles on DEV Community by Rida F Najid (@rfnajid).</description>
    <link>https://dev.to/rfnajid</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%2F917689%2F1fd6f809-9ba2-4a2f-b2f9-6a627cac8166.jpeg</url>
      <title>DEV Community: Rida F Najid</title>
      <link>https://dev.to/rfnajid</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rfnajid"/>
    <language>en</language>
    <item>
      <title>Easy GraphQL Server in Node.js</title>
      <dc:creator>Rida F Najid</dc:creator>
      <pubDate>Tue, 28 Feb 2023 07:05:39 +0000</pubDate>
      <link>https://dev.to/rfnajid/easy-graphql-server-in-nodejs-3n2g</link>
      <guid>https://dev.to/rfnajid/easy-graphql-server-in-nodejs-3n2g</guid>
      <description>&lt;p&gt;In this article, we will create a simple CRUD (Create, Read, Update, Delete) using GraphQL in Node.js&lt;/p&gt;

&lt;p&gt;I'll be using the following tools :&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Express&lt;/li&gt;
&lt;li&gt;Typescript &lt;/li&gt;
&lt;li&gt;Apollo Server for the GraphQL engine&lt;/li&gt;
&lt;li&gt;Sequelize&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Javascript environment is very opinionated you can use other tools to achieve the same goal. But the idea is similiar.&lt;/p&gt;

&lt;p&gt;I assume that you're already familiar in Node.js development. So, I won't explain further on the project setup. I want to focus on GraphQL explanation. If you want to see my setup you can check it out on my Github repo below.&lt;/p&gt;

&lt;p&gt;I have this model&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 MovieModel extends Model {
    id: number;
    title: string;
    description: string;
    posterUrl: string;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;We will create GraphQL based on the &lt;strong&gt;MovieModel&lt;/strong&gt;.&lt;/p&gt;

&lt;h3&gt;
  
  
  Schema
&lt;/h3&gt;

&lt;p&gt;In GraphQL, you need to define a schema. The schema is like a blueprint of how GraphQL API can be accessed. You can learn more about GraphQL schema &lt;a href="https://graphql.org/learn/schema/" rel="noopener noreferrer"&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;There are two main operations in GraphQL: Query and Mutation. Query is read-only operation. It does not modify any data. Mutation is request for modifying data. It's used to create, update or delete data on the server. You need to define your operations in schema.&lt;/p&gt;

&lt;p&gt;There are other operation types too such as Subscription. But, in this article I won't dive further other operations.&lt;/p&gt;

&lt;p&gt;Okay, we need to create root schema first, it looks 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;export const rootSchema = `#graphql

 type Query {
     root: String
 }
 type Mutation {
     root: String
 }
`;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;And then we create Movie schema.&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 movieSchema = `#graphql

 type Movie {
   id: Int!
   title: String!
   description: String
   posterUrl: String
 }

 extend type Query {
    getAllMovies: [Movie]
    getOneMovie(id: Int!): Movie
 }

 extend type Mutation {
    createMovie(title: String!, description: String, posterUrl: String): Movie

    updateMovie(id: Int, title: String, description: String, posterUrl: String): Movie

    deleteMovie(id: Int!): String
 }
 `
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;As you can see, we can define custom data type on GraphQL schema. In this case, I created &lt;strong&gt;Movie&lt;/strong&gt; type that has same attributes as the &lt;strong&gt;MovieModel&lt;/strong&gt;.&lt;/p&gt;

&lt;p&gt;After that we need to define our operations. &lt;/p&gt;

&lt;p&gt;I created two Query operations. &lt;strong&gt;getAllMovies&lt;/strong&gt; and &lt;strong&gt;getOneMovie&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;getAllMovies&lt;/strong&gt; doesn't have any input, but it will return an array of &lt;strong&gt;Movie&lt;/strong&gt;. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;getOneMovie&lt;/strong&gt; have one input, &lt;strong&gt;id&lt;/strong&gt; with an integer type. The exclamation mark (!) indicates that the input is required.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;getOneMovie&lt;/strong&gt; will only return one &lt;strong&gt;Movie&lt;/strong&gt; data. That's why it doesn't have square brackets.&lt;/p&gt;

&lt;p&gt;And then I created three mutations. Basically it's for create, update and delete. &lt;/p&gt;

&lt;p&gt;There's no different in syntax between Query and Mutation.&lt;/p&gt;

&lt;h3&gt;
  
  
  Resolver
&lt;/h3&gt;

&lt;p&gt;A resolver is the logical function when a GraphQL API is called. The resolver function must has same name as defined in the schema.&lt;/p&gt;

&lt;p&gt;Here's example of &lt;strong&gt;Movie&lt;/strong&gt; Resolver&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const MovieResolver = {
    Query: {
        async getAllMovies(root, input, context) {
            return Movie.findAll();
        },
        async getOneMovie(root, input, context){
           return Movie.findByPk(input.id);
        }
    },
    Mutation : {
        async createMovie(root, input, context) {
            const { title, description, posterUrl } = input;
            return Movie.create({ title, description, posterUrl });
        },
        async updateMovie(root, input, context) {
            const id = input.id;
            const movie = input;
            await Movie.update(movie, { 
                where: { id: id }
            });

            return {id: id, ...movie};

        },
        async deleteMovie(root, {id}, context){
            const deleteRes = await Movie.destroy({
                where: {id: id}
            });

            if(deleteRes){
                return `Movie id:${id} has been deleted`;
            }else{
                return `Can't delete Movie id:${id}`;
            }
        },
    }
}

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

&lt;/div&gt;



&lt;p&gt;To put it simply, Resolver is like Controller in MVC design pattern.&lt;/p&gt;

&lt;h3&gt;
  
  
  Initializing Apollo Server
&lt;/h3&gt;

&lt;p&gt;The final touch is to initialize Apollo Server in &lt;strong&gt;main.ts&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;
async function startServer(){
    const app = express();

    const schema = makeExecutableSchema({
        resolvers: [MovieResolver],
        typeDefs: [rootSchema, movieSchema],
    });

    const apolloServer = new ApolloServer({
        schema: schema,
        introspection: true,
    });

    await apolloServer.start();

    app.use(
        cors(),
        bodyParser.json(),
        expressMiddleware(apolloServer)
    )

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

startServer();

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

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;makeExecutableSchema&lt;/strong&gt; is a function to register our resolvers and schema. &lt;/p&gt;

&lt;p&gt;&lt;strong&gt;introspection&lt;/strong&gt; is feature in Apollo to enable GraphQL Server to get the specification details of schema. It's useful in development stage. But, it should be disabled in production for security purpose.&lt;/p&gt;

&lt;p&gt;Apollo has built in GUI GraphQL Client. You can access it in /graphql&lt;/p&gt;

&lt;p&gt;Here's an example of query and mutation request on Apollo GraphQL Client&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F029r3de5mn5bpz9m6eau.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2F029r3de5mn5bpz9m6eau.png" alt="Example of Query in GraphQL" width="800" height="224"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq9zfb57ki7qk3je3412r.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media2.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fq9zfb57ki7qk3je3412r.png" alt="Example of Mutation in GraphQL" width="800" height="226"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;That's it for now!&lt;/p&gt;

&lt;p&gt;You can access my code here &lt;/p&gt;

&lt;p&gt;&lt;a href="https://github.com/rfnajid/apollo-graphql-example" rel="noopener noreferrer"&gt;https://github.com/rfnajid/apollo-graphql-example&lt;/a&gt;&lt;/p&gt;

</description>
      <category>gaminghardware</category>
      <category>cloudgaming</category>
      <category>gamedeals</category>
      <category>gamepass</category>
    </item>
    <item>
      <title>Optimistic Locking on Spring Boot</title>
      <dc:creator>Rida F Najid</dc:creator>
      <pubDate>Mon, 09 Jan 2023 13:13:21 +0000</pubDate>
      <link>https://dev.to/rfnajid/optimistic-locking-on-spring-boot-812</link>
      <guid>https://dev.to/rfnajid/optimistic-locking-on-spring-boot-812</guid>
      <description>&lt;p&gt;If your application has massive traffic. Sometimes there will be conflicting updates between data.&lt;/p&gt;

&lt;p&gt;For example, User A and User B accidentally trying to update same data on same time. Both of their updates will be saved and both users will receive a successful response. Both of them will assume their data correctly saved. But, that's not the case - the first saved data will replaced by the last one. We don't know which user saved it first.&lt;/p&gt;

&lt;p&gt;In order to prevent this, we can use Optimistic Locking. In Optimistic Locking we need to save record version in database.&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%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fu6bhjd1ffp51xtjcembj.jpg" 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%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Farticles%2Fu6bhjd1ffp51xtjcembj.jpg" alt="optimistic locking example"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;If there's modification on a record, we need to check its version first. If the new data version is lower than the version in the database, it will be rejected. If it has the correct version, the new data will be saved and the version will be incremented.&lt;/p&gt;

&lt;p&gt;It has quite a lot logic right? But, don't worry all of that process will be taken care by JPA.&lt;/p&gt;

&lt;p&gt;We need to add the &lt;a class="mentioned-user" href="https://dev.to/version"&gt;@version&lt;/a&gt; annotation to the entity.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@Entity
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    Long id;

    String name;

    @Version
    Long version;
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;strong&gt;All done!&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Here's a test script to check if Optimistic Locking is working correctly.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;@DataJpaTest
public class RepoTest {

    @Autowired
    StudentRepository repo;

    @Test
    void testOptimisticLock(){
        Student initStudent = new Student(1L, "Andy", 0L);
        Student insertedStudent = repo.saveAndFlush(initStudent);

        assertEquals(0, insertedStudent.getVersion());

        insertedStudent.setName("Jack");
        Student updatedStudent = repo.saveAndFlush(insertedStudent);

        assertEquals(1, updatedStudent.getVersion());

        assertThrows(OptimisticLockingFailureException.class, () -&amp;gt;
            repo.saveAndFlush(initStudent)
        );
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;&lt;a href="https://github.com/rfnajid/optimisticlock" rel="noopener noreferrer"&gt;You can check the full code here&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;*&lt;em&gt;Note *&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;If you don't want to add dedicated version field to your existing table, you can use the update date as the version instead.&lt;/p&gt;

</description>
      <category>java</category>
      <category>springboot</category>
      <category>programming</category>
    </item>
    <item>
      <title>Why react is so hard</title>
      <dc:creator>Rida F Najid</dc:creator>
      <pubDate>Thu, 03 Nov 2022 13:12:49 +0000</pubDate>
      <link>https://dev.to/rfnajid/why-react-is-so-hard-327g</link>
      <guid>https://dev.to/rfnajid/why-react-is-so-hard-327g</guid>
      <description>&lt;p&gt;Here's my POV why react is so hard. Especially for OOP-minded and beginner.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;useEffect doesn't make any sense&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Since React 16.8, They introduced more simple way to write React in alternative to class based component. They call it React Hooks. To be honest, It really makes write React app more simple.&lt;/p&gt;

&lt;p&gt;But, it has a downside for an OOP-minded programmer like me. In React Hooks, we use state to declare variables, by calling useState function.&lt;/p&gt;

&lt;p&gt;And... there's a function called useEffect. At first, it doesn't make sense. I don't need fancy effects to build simple ToDo App. It turns out, it called useEffect not because of it will use animation effect. But, every DOM changing or data fetching are called "side-effect". That's why they named it useEffect. It doesn't make any sense for me. It should be called update, onRefresh or something like that.&lt;/p&gt;

&lt;p&gt;According to documentation useEffect is Hook version of componentDidMount, componentDidUpdate, and componentWillUnmount combined. Every mount, update and unmount will call useEffect. It doesn't make any sense right??&lt;/p&gt;

&lt;p&gt;In contrary from most developers, I will recommend you to keep using React class based component, if you have strong OOP philosophy. It more easy to understand although it will require more codes.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Zv9QERsI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bfaytupiokoropl5txpx.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Zv9QERsI--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bfaytupiokoropl5txpx.png" alt="Comparison React hooks vs React class based component" width="720" height="486"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;blockquote&gt;
&lt;p&gt;Comparison React hooks vs React class based component&lt;/p&gt;
&lt;/blockquote&gt;

&lt;p&gt;&lt;strong&gt;Logic and View mixed together&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As an OOP-minded developer, most of us like to separate codes between logics and views. Logic is for data manipulation, data fetching, etc. and view is for showing end result to user. Usually, we use html or templating engine to make it more cleaner.&lt;/p&gt;

&lt;p&gt;But, in React you cannot separate "html" from JS. That's why its called JSX. If you're not accustomed by this, you'll constantly lost in your own codes. In order to avoid this, you need to splice component into smaller components.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;CSS-in-JS&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;React can generate CSS by using JS. Biggest difference between classic CSS and CSS-in-JS is syntax formatting. CSS-in-JS use camel case.&lt;/p&gt;

&lt;p&gt;This is optional feature, we can still import classic CSS module.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;State Management&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;Communication between components need a global state. A lot of ways to manage state in React. The official way is using React Context. You don't need any dependencies to use React Context. But, it has limitation. It's not recommend if your app is growing bigger and bigger.&lt;/p&gt;

&lt;p&gt;The alternative is using Redux. Most people are using Redux. In real life, Redux is the standard React State Management. A lot of React job opportunities include Redux as Technical Requirement.&lt;/p&gt;

&lt;p&gt;In my honest opinion, learning curve of React Context and Redux is too steep. Both of them are too complex.&lt;/p&gt;

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

&lt;ul&gt;
&lt;li&gt;
&lt;a href="https://www.pexels.com/photo/love-people-woman-heart-11035471/"&gt;Thumbnail image by RealToughCandy.com&lt;/a&gt; &lt;/li&gt;
&lt;li&gt;&lt;a href="https://reactjs.org/docs/hooks-effect.html"&gt;React useEffect documentation&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://blog.bitsrc.io/6-reasons-to-use-react-hooks-instead-of-classes-7e3ee745fe04"&gt;Snipped code of "Comparison React hooks vs React class based component" by bitsrc.io&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://reactjs.org/docs/context.html"&gt;React Context&lt;/a&gt;&lt;/li&gt;
&lt;li&gt;&lt;a href="https://redux.js.org/introduction/getting-started"&gt;Redux&lt;/a&gt;&lt;/li&gt;
&lt;/ul&gt;

</description>
      <category>webdev</category>
      <category>react</category>
      <category>reactnative</category>
      <category>javascript</category>
    </item>
  </channel>
</rss>
