<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dennis on Medium]]></title>
        <description><![CDATA[Stories by Dennis on Medium]]></description>
        <link>https://medium.com/@thecodinganalyst?source=rss-b7d1517f4110------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9fr45EL7xmTc1gbiHxbZMw@2x.jpeg</url>
            <title>Stories by Dennis on Medium</title>
            <link>https://medium.com/@thecodinganalyst?source=rss-b7d1517f4110------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 14:43:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thecodinganalyst/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to handle Internal Error in Spring for GraphQL]]></title>
            <link>https://levelup.gitconnected.com/how-to-handle-internal-error-in-spring-for-graphql-f0b4dd3bf883?source=rss-b7d1517f4110------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0b4dd3bf883</guid>
            <category><![CDATA[spring-graphql]]></category>
            <category><![CDATA[spring-boot-graphql]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[graphql-errors]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Dennis]]></dc:creator>
            <pubDate>Wed, 06 Sep 2023 03:30:21 GMT</pubDate>
            <atom:updated>2023-09-08T14:58:30.282Z</atom:updated>
            <content:encoded><![CDATA[<p>This is an extension to the articles - <a href="https://www.thecodinganalyst.com/tutorial/Getting-started-with-spring-and-graphql/">Getting started with Spring and GraphQl</a> and <a href="https://www.thecodinganalyst.com/tutorial/Integration-testing-on-Spring-Boot-GraphQL-Starter-with-HttpGraphQlTester/">Integration testing on Spring Boot GraphQL Starter with HttpGraphQlTester</a>.</p><p>GraphQL pretty much handles validation issues for us, like the screenshot below. We missed out a required field, and graphql provides the appropriate message for us automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ria_VV1KwvyhC0ZjxTLLZA.png" /></figure><p>However, if the exception is due to the internal execution to do the mutation or query of the data, graphql will only give an Internal Error, without much information.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u8A_mXo2asOHdTKzep9RhQ.png" /></figure><p>For example, in the update function below, the program will first get the repository to find the product, before updating the product with the fields from the updatedProduct and save it back in the repository.</p><pre>public Mono&lt;Product&gt; updateProduct(String id, Product updatedProduct){<br>    return productRepository.findById(id)<br>            .switchIfEmpty(Mono.error(new IllegalArgumentException(&quot;Product not found&quot;)))<br>            .flatMap(product -&gt; {<br>                product.setName(updatedProduct.getName());<br>                product.setDescription(updatedProduct.getDescription());<br>                product.setPrice(updatedProduct.getPrice());<br>                product.setCategory(updatedProduct.getCategory());<br>                return productRepository.save(product);<br>            });<br>}</pre><p>If the product id is not found in the repository, it should return a Mono error, encapsulating an IllegalArgumentException with the appropriate error message - Product not found.</p><p>However, this information is not passed on to the graphql, like what we saw in the screenshot earlier. The message is intentionally opaque to avoid leaking implementation details. Nevertheless, we can handle this error such that it can return the appropriate message to the client.</p><p>To handle the exceptions for only with the specific controller itself, we can add the handle function with the @GraphQlExceptionHandler, as described in the <a href="https://docs.spring.io/spring-graphql/docs/current/reference/html/#controllers.exception-handler">documentation</a>.</p><pre>@Controller<br>@Slf4j<br>public class ProductController {<br><br>    ...<br><br>    @GraphQlExceptionHandler<br>    public GraphQLError handle(@NonNull Throwable ex, @NonNull DataFetchingEnvironment environment){<br>        return GraphQLError<br>                .newError()<br>                .errorType(ErrorType.BAD_REQUEST)<br>                .message(ex.getMessage())<br>                .path(environment.getExecutionStepInfo().getPath())<br>                .location(environment.getField().getSourceLocation())<br>                .build();<br>    }<br>}</pre><p>In the above function, we got the Throwable and DataFetchingEnvironment to return the error message and the path and location of where the exception occurred, returning a GraphQLError to the client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7gx33cCbiuU_UzoNKi2UHA.png" /></figure><p>Running the same function again, now we get a more meaningful message. Do note that for the above method, it only handles exceptions from the ProductController class.</p><p>Alternatively, we can also create an extension of the DataFetcherExceptionResolverAdapter as a fallback to handle exceptions not caught by the respective controllers, as described in the <a href="https://docs.spring.io/spring-graphql/docs/current/reference/html/#execution.exceptions">documentation</a>.</p><pre>@Component<br>public class CustomExceptionResolver extends DataFetcherExceptionResolverAdapter {<br>    @Override<br>    protected GraphQLError resolveToSingleError(@NonNull Throwable ex, @NonNull DataFetchingEnvironment env){<br>        return GraphqlErrorBuilder.newError()<br>                .errorType(ErrorType.BAD_REQUEST)<br>                .message(ex.getMessage())<br>                .path(env.getExecutionStepInfo().getPath())<br>                .location(env.getField().getSourceLocation())<br>                .build();<br>    }<br>}</pre><p>We can test that it works in the following integration test. Here, after executing the graphql, we call the errors() and expect() to check on the error message. Without the above implementation, the test will fail because it would get in Internal Error instead.</p><pre>@Test<br>@Order(5)<br>void updateProduct_invalidProduct(){<br>    this.httpGraphQlTester<br>            .document(&quot;&quot;&quot;<br>                    mutation {<br>                        updateProduct(<br>                            id: &quot;123&quot;,<br>                            updatedProduct: {<br>                                name: &quot;Pilot G1 Pen&quot;,<br>                                description: &quot;Best selling gel-based ball point pen&quot;,<br>                                price: 1.80<br>                                category: &quot;Stationery&quot;<br>                            }<br>                        ){<br>                            id<br>                            name<br>                            description<br>                            price<br>                            category<br>                        }<br>                    }<br>                    &quot;&quot;&quot;)<br>            .execute()<br>            .errors()<br>            .expect(error -&gt; Objects.equals(error.getMessage(), &quot;Product not found&quot;));<br>}</pre><p>A working copy of the above code is available on <a href="https://github.com/thecodinganalyst/graphql/blob/main/src/main/java/com/hevlar/intro/graphql/controller/ProductController.java">https://github.com/thecodinganalyst/graphql/blob/main/src/main/java/com/hevlar/intro/graphql/controller/ProductController.java</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0b4dd3bf883" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-handle-internal-error-in-spring-for-graphql-f0b4dd3bf883">How to handle Internal Error in Spring for GraphQL</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integration testing on Spring Boot GraphQL Starter with HttpGraphQlTester]]></title>
            <link>https://levelup.gitconnected.com/integration-testing-on-spring-boot-graphql-starter-with-httpgraphqltester-cc7248a48112?source=rss-b7d1517f4110------2</link>
            <guid isPermaLink="false">https://medium.com/p/cc7248a48112</guid>
            <category><![CDATA[httpgraphqltester]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[spring-boot-graphql]]></category>
            <category><![CDATA[integration-test]]></category>
            <category><![CDATA[spring-graphql]]></category>
            <dc:creator><![CDATA[Dennis]]></dc:creator>
            <pubDate>Tue, 05 Sep 2023 02:12:20 GMT</pubDate>
            <atom:updated>2023-09-08T15:18:05.432Z</atom:updated>
            <content:encoded><![CDATA[<p>Following my <a href="https://www.thecodinganalyst.com/tutorial/Spring-boot-application-getting-started/">previous article on getting started with spring and graphql</a>, let’s look at how we can do integration testing on the graphql spring boot application.</p><p>You might wonder if it is necessary to do integration testing, can I just leave it to the unit tests? Well, for a simple controller like the one below, there is really nothing much to unit test on.</p><pre>@QueryMapping<br>public Flux&lt;Product&gt; getAllProducts(){<br>    return productService.getAllProducts();<br>}</pre><p>We will definitely need to have unit tests for our service layer, but having integration test on our controller helps us to ensure we have implemented our schema.graphqls correctly, and we have passed on our error message to the graphql, so that it will not just give an “Internal Error”. We shall discuss more on that in the next article.</p><p>To do integration testing on all the layers (controller, service, repository), we need the full setup to run the test, hence we need to enable @SpringBootTest. Spring for GraphQL provides a <a href="https://docs.spring.io/spring-graphql/docs/current/reference/html/#testing.graphqltester">GraphQlTester</a> interface for testing the graphql queries. And it has different implementations for different ways how we use it, via Http, Websockets, or RSockets. Since we are creating http api, we will implement the HttpGraphQlTester. To autowire the HttpGraphQlTester into our test class, we can simply add the @AutoConfigureHttpGraphQlTester annotation to our class, and declare the HttpGraphQlTester by annotating it with the @Autowired annotation.</p><pre>@SpringBootTest<br>@AutoConfigureHttpGraphQlTester<br>@TestInstance(TestInstance.Lifecycle.PER_CLASS)<br>@TestMethodOrder(MethodOrderer.OrderAnnotation.class)<br>@Testcontainers<br>@ContextConfiguration(classes = TestIntroGraphQlApplication.class)<br>class ProductControllerIntegrationTest {<br><br>    @Autowired<br>    HttpGraphQlTester httpGraphQlTester;<br><br>}</pre><blockquote>The @TestInstance is added because in my case, I want to create a single instance to run all the test functions in the class instead of the default one instance per function, so that I can make use of the data created in my first few functions for my subsequent tests. And the TestMethodOrder allows me to specify the order of the tests to run.</blockquote><blockquote>The @Testcontainers indicates that this function will start the docker service to create the database for our tests, and the @ContextConfiguration tells spring where to get the configurations, which in my case, contains the configurations of the testcontainer.</blockquote><p>The <a href="https://github.com/spring-projects/spring-graphql/blob/main/spring-graphql-test/src/main/java/org/springframework/graphql/test/tester/GraphQlTester.java">GraphQlTester</a> contains a list of interfaces to help with testing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*M-K1Jp3wcVGd5_XtD9UwPQ.png" /></figure><p>For a mutation mapping function in the controller, like the function below, we are passing in a Product in the parameter, and it should return a Mono of the created Product.</p><pre>@MutationMapping<br>public Mono&lt;Product&gt; createProduct(@Argument Product product){<br>    log.info(&quot;createProduct: &quot; + product.toString());<br>    return productService.createProduct(product);<br>}</pre><p>A simple integration test on implementing graphql on the controller will look something like this.</p><pre>@Test<br>@Order(1)<br>void createProduct() {<br>    Product product = this.httpGraphQlTester<br>            .document(&quot;&quot;&quot;<br>                        mutation {<br>                            createProduct(product: {<br>                                name: &quot;Pilot Pen&quot;,<br>                                description: &quot;Gel-based ball point pen&quot;,<br>                                price: 1.50,<br>                                category: &quot;Stationery&quot;<br>                            }){<br>                                id<br>                                name<br>                                description<br>                                price<br>                                category<br>                            }<br>                        }<br>                    &quot;&quot;&quot;)<br>            .execute()<br>            .errors()<br>            .verify()<br>            .path(&quot;createProduct&quot;)<br>            .entity(Product.class)<br>            .get();<br>    assertThat(product.getId()).isNotNull();<br>    assertThat(product.getName()).isEqualTo(&quot;Pilot Pen&quot;);<br>    assertThat(product.getDescription()).isEqualTo(&quot;Gel-based ball point pen&quot;);<br>    assertThat(product.getPrice()).isEqualTo(BigDecimal.valueOf(1.50));<br>    assertThat(product.getCategory()).isEqualTo(&quot;Stationery&quot;);<br>    savedProduct = product;<br>}</pre><p>Running it in our graphiql should return the following result.</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;createProduct&quot;: {<br>      &quot;id&quot;: &quot;64f68c13aca30273b0f87534&quot;,<br>      &quot;name&quot;: &quot;Pilot Pen&quot;,<br>      &quot;description&quot;: &quot;Gel-based ball point pen&quot;,<br>      &quot;price&quot;: 1.5,<br>      &quot;category&quot;: &quot;Stationery&quot;<br>    }<br>  }<br>}</pre><p>In the function, we pass in our graphql syntax to our httpGraphQlTester with the document() function, and pipe it to execute() to get it executed. After executing the graphql, we can pipe it to errors() and verify() to verify that there are no errors in the execution. So if there are any errors from the execution, the function will fail. Then we pipe it to path(&quot;createProduct&quot;) to navigate to the createProduct json node in the result, which should be returning us a Product, and we use the get() function to get it mapped our Product class, and we assigned it to the product variable in our function. Then we can use our usual assertion functions to verify the return values against what we expect.</p><p>A working copy of the above code is available on <a href="https://github.com/thecodinganalyst/graphql/blob/main/src/test/java/com/hevlar/intro/graphql/controller/ProductControllerIntegrationTest.java">https://github.com/thecodinganalyst/graphql/blob/main/src/test/java/com/hevlar/intro/graphql/controller/ProductControllerIntegrationTest.java</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cc7248a48112" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/integration-testing-on-spring-boot-graphql-starter-with-httpgraphqltester-cc7248a48112">Integration testing on Spring Boot GraphQL Starter with HttpGraphQlTester</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with Spring and GraphQL]]></title>
            <link>https://levelup.gitconnected.com/getting-started-with-spring-and-graphql-3750533bc7eb?source=rss-b7d1517f4110------2</link>
            <guid isPermaLink="false">https://medium.com/p/3750533bc7eb</guid>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[graphql-vs-rest]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[testcontainer]]></category>
            <category><![CDATA[spring-graphql]]></category>
            <dc:creator><![CDATA[Dennis]]></dc:creator>
            <pubDate>Thu, 31 Aug 2023 15:58:57 GMT</pubDate>
            <atom:updated>2023-09-03T15:36:54.722Z</atom:updated>
            <content:encoded><![CDATA[<p>The most common way of creating APIs is using REST (Representational State Transfer), of which we make use of the http verbs (POST, GET, PUT, DELETE) to state what is the operation. However, if we want to allow our API clients to specify exactly what should be the fields to be retrieved, so that the client only gets what it needs, we can’t really achieve that easily with REST.</p><p>Introduce <a href="https://graphql.org/">GraphQL</a>, it is a software for implementing APIs by allowing users to define their data, queries, and mutations with a type language, so that clients can query the APIs from a single endpoint.</p><p>For example, if you have a product catalogue system, with REST, you would define the APIs as such</p><pre>Create   - [POST] /products<br>Read All - [GET] /products<br>Read One - [GET] /products/{id}<br>Update   - [PUT] /products/{id} {product}<br>Delete   - [DELETE] /products/{id}</pre><p>With GraphQL, it’s just one endpoint - /graphql and we only use POST. And we define our schema.graphqls file to define our data, queries, and mutations as such.</p><pre># schema.graphqls<br><br># Define the Product type<br>type Product {<br>  id: ID!<br>  name: String!<br>  description: String<br>  price: Float!<br>  category: String!<br>}<br><br># Define the Query type for Read operations<br>type Query {<br>  # Get a single product by ID<br>  getProduct(id: ID!): Product<br><br>  # Get all products (optionally by category)<br>  getAllProducts: [Product]<br>}<br><br>input ProductInput {<br>  name: String!<br>  description: String<br>  price: Float!<br>  category: String!<br>}<br><br># Define the Mutation type for Create, Update, and Delete operations<br>type Mutation {<br>  # Create a new product<br>  createProduct(product: ProductInput!): Product<br><br>  # Update an existing product<br>  updateProduct(id: ID!, updatedProduct: ProductInput!): Product<br><br>  # Delete a product<br>  deleteProduct(id: ID!): Boolean<br>}</pre><p>The syntax is almost identical to typescript, we define the our Product type to describe our data, what fields are present, and what are their types. Then we define our APIs with the Query type and Mutation type. As the name suggests, Query is just for getting data, and if we are to modify any data with our API, we use Mutation. Here we define the getAllProducts and getProduct queries to read the data, and createProduct, updateProduct, and deleteProduct to create, update, and delete our data. It’s like back to the old way of creating APIs without using REST http methods. And if we need to pass in objects as parameters to our APIs, we need to create an input type. We can’t use the original defined Product type.</p><p>To call our APIs, we send a http POST to the /graphql endpoint, with the graphql syntax in the data of the http body. For example, to call the createProduct, we would pass in the following graphql query.</p><pre>mutation {<br>  createProduct (product: {<br>    name: &quot;pen&quot;,<br>    description: &quot;writing instrument&quot;,<br>    price: 1.50<br>    category: &quot;stationery&quot;<br>  }){<br>    id<br>    name<br>    description<br>    price<br>    category<br>  }<br>}</pre><p>and we will get the following in return.</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;createProduct&quot;: {<br>      &quot;id&quot;: &quot;64f051c2aca30273b0f87531&quot;,<br>      &quot;name&quot;: &quot;pen&quot;,<br>      &quot;description&quot;: &quot;writing instrument&quot;,<br>      &quot;price&quot;: 1.5,<br>      &quot;category&quot;: &quot;stationery&quot;<br>    }<br>  }<br>}</pre><p>Notice that we specify the fields at the end of the query, this is mandatory for all non-scalar type return results, so we can specify just the fields we need. For example, if our graphql query is just</p><pre>mutation {<br>  createProduct (product: {<br>    name: &quot;pen&quot;,<br>    description: &quot;writing instrument&quot;,<br>    price: 1.50<br>    category: &quot;stationery&quot;<br>  }){<br>    id<br>    name<br>    description<br>  }<br>}</pre><p>then we will get only the specified fields in return.</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;createProduct&quot;: {<br>      &quot;id&quot;: &quot;64f0528baca30273b0f87532&quot;,<br>      &quot;name&quot;: &quot;pen&quot;,<br>      &quot;description&quot;: &quot;writing instrument&quot;<br>    }<br>  }<br>}</pre><h3>Implementing in Spring Boot</h3><p>Let’s try to implement the above in a spring boot application. A good use case for using graphql is for microservices, with its ability to allow dynamic specification of what fields are needed, it can be easily implemented for future usage without having to create new APIs for different field requirements. And with microservices, having non-blocking functions helps with better resource utilization, particularly when you have multiple services running in parallel and competing for resources. So in our example, we are going to use reactive programming to create our application. A working example of the application is available on <a href="https://github.com/thecodinganalyst/graphql">https://github.com/thecodinganalyst/graphql</a>. Make sure you have dockerhub and mongodb installed to run the application and the tests.</p><pre>implementation &#39;org.springframework.boot:spring-boot-starter-data-mongodb-reactive:3.1.3&#39;<br>implementation &#39;org.springframework.boot:spring-boot-starter-graphql:3.1.3&#39;<br>implementation &#39;org.springframework.boot:spring-boot-starter-webflux:3.1.3&#39;</pre><p>For a start, we shall add spring-boot-starter-webflux and spring-boot-starter-graphql to our dependencies. For database, we’re going with MongoDB, and we’re using the reactive version of the driver, so we add spring-boot-starter-data-mongodb-reactive.</p><p>For testing, other than the usual spring-boot-starter-test, we need to add reactor-test from project reactor to make use of the StepVerifier to test reactively. And lastly, we will use <a href="https://testcontainers.com/">testcontainers</a> to create the mongodb for testing, so we shall add spring-boot-testcontainers, <a href="https://mvnrepository.com/artifact/org.testcontainers/junit-jupiter">junit-jupiter</a> and <a href="https://mvnrepository.com/artifact/org.testcontainers/mongodb">mongodb</a> libraries from testcontainers. Make sure we use version 3.x for our spring boot, so that we can make use of the @ServiceConnection annotation to easily set up our testcontainers.</p><blockquote>To know more about using testcontainers, do visit <a href="https://www.thecodinganalyst.com/reference/Spring-boot-testing-with-MongoDB/">https://www.thecodinganalyst.com/reference/Spring-boot-testing-with-MongoDB/</a>.</blockquote><pre>testImplementation &#39;org.springframework.boot:spring-boot-starter-test:3.1.3&#39;<br>testImplementation &#39;org.springframework.boot:spring-boot-testcontainers:3.1.3&#39;<br>testImplementation &#39;io.projectreactor:reactor-test:3.5.9&#39;<br>testImplementation &#39;org.springframework.graphql:spring-graphql-test:1.2.2&#39;<br>testImplementation &#39;org.testcontainers:junit-jupiter:1.18.3&#39;<br>testImplementation &#39;org.testcontainers:mongodb:1.18.3&#39;</pre><p>Next, place the schema.graphqls file in the src/main/java/resources/graphql folder. This is the default location for the graphql schema file. Then set the mongodb connection string properties in the src/main/java/resources/application.properties file. I’m naming my database intro, you can change it to anything you like, but make sure to create the database in your local mongodb.</p><pre>spring.data.mongodb.database=intro<br>spring.data.mongodb.port=27017<br>spring.data.mongodb.host=localhost<br>spring.data.mongodb.auto-index-creation=true<br><br>spring.graphql.graphiql.enabled=true</pre><p>The spring.graphql.graphiql.enabled property enables the /graphiql endpoint which you can browse on your browser to test your graphql. As in the screenshot below, not only does it allow you to run your api, it also provides documentation on the types, queries, and mutations available on your endpoint.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l5A-BVWD3GjcdjJUY8LL4g.png" /></figure><p>So, to begin, we create the Product class as defined in our schema.</p><pre>@Document<br>@Data<br>@AllArgsConstructor<br>@NoArgsConstructor<br>public class Product {<br>    @Id<br>    String id;<br>    String name;<br>    String description;<br>    BigDecimal price;<br>    String category;<br><br>    public Product(String name, String description, BigDecimal price, String category){<br>        this.name = name;<br>        this.description = description;<br>        this.price = price;<br>        this.category = category;<br>    }<br>}</pre><p>The @Document specifies that this class is identified as a mongodb document, and the @Data, @AllArgsConstructor, and @NoArgsConstructor are lombok annotations to create the boiler code, such as the getters, setters, and constructors we need for our data class.</p><pre>@Repository<br>public interface ProductRepository extends ReactiveMongoRepository&lt;Product, String&gt; {<br>}</pre><p>For our repository, since we are using reactive programming, we extend ReactiveMongoRepository instead of MongoRepository.</p><pre>@Service<br>public class ProductService {<br>    private final ProductRepository productRepository;<br><br>    public ProductService(ProductRepository productRepository){<br>        this.productRepository = productRepository;<br>    }<br><br>    public Mono&lt;Product&gt; createProduct(Product product){<br>        return productRepository.save(product);<br>    }<br><br>    public Flux&lt;Product&gt; getAllProducts(){<br>        return productRepository.findAll();<br>    }<br><br>    public Mono&lt;Product&gt; getProduct(String id){<br>        return productRepository.findById(id);<br>    }<br><br>    public Mono&lt;Product&gt; updateProduct(String id, Product updatedProduct){<br>        return productRepository.findById(id)<br>                .switchIfEmpty(Mono.error(new IllegalArgumentException(&quot;Product not found&quot;)))<br>                .flatMap(product -&gt; {<br>                    product.setName(updatedProduct.getName());<br>                    product.setDescription(updatedProduct.getDescription());<br>                    product.setPrice(updatedProduct.getPrice());<br>                    product.setCategory(updatedProduct.getCategory());<br>                    return productRepository.save(product);<br>                });<br>    }<br><br>    public Mono&lt;Boolean&gt; deleteProduct(String id){<br>        return productRepository.findById(id)<br>                .switchIfEmpty(Mono.error(new IllegalArgumentException(&quot;Product not found&quot;)))<br>                .flatMap(product -&gt; productRepository.deleteById(id).thenReturn(true));<br>    }<br>}</pre><p>This is what we create for our service, not too much different from the usual way in non-reactive spring web as depicted in <a href="https://www.thecodinganalyst.com/tutorial/Spring-boot-application-getting-started/">https://www.thecodinganalyst.com/tutorial/Spring-boot-application-getting-started/</a>. Except that since it is reactive, we are returning streams, and we encapsulate our return types with Mono for returning single objects, and Flux for returning multiple objects. Do visit <a href="https://www.baeldung.com/reactor-core">https://www.baeldung.com/reactor-core</a> to know more about Mono and Flux in the reactor-core project.</p><p>The updateProduct method above first look up for the product with the id field, and returns an error if a product with the id is not found. If the product is found, it updates the product with the values passed in the parameter, and save the product back to the repository.</p><pre>@Controller<br>public class ProductController {<br><br>    private final ProductService productService;<br><br>    public ProductController(ProductService productService){<br>        this.productService = productService;<br>    }<br><br>    @MutationMapping<br>    public Mono&lt;Product&gt; createProduct(@Argument Product product){<br>        return productService.createProduct(product);<br>    }<br><br>    @QueryMapping<br>    public Flux&lt;Product&gt; getAllProducts(){<br>        return productService.getAllProducts();<br>    }<br><br>    @QueryMapping<br>    public Mono&lt;Product&gt; getProduct(@Argument String id){<br>        return productService.getProduct(id);<br>    }<br><br>    @MutationMapping<br>    public Mono&lt;Product&gt; updateProduct(@Argument String id, @Argument Product updatedProduct){<br>        return productService.updateProduct(id, updatedProduct);<br>    }<br><br>    @MutationMapping<br>    public Mono&lt;Boolean&gt; deleteProduct(@Argument String id){<br>        return productService.deleteProduct(id);<br>    }<br>}</pre><p>Lastly, we create our ProductController. Instead of annotating it with @RestController, we just need to annotate it with @Controller, since we are not using REST. For our functions to map to our queries and mutations defined in our schema.graphqls, we need to annotate them with either @QueryMapping or @MutationMapping respectively, with the function name matching the actual queries/mutations. The same is for the parameters, but we annotate them with the @Argument annotation instead.</p><p>That’s it! Try to bootRun it and navigate to the /graphiql endpoint to test the APIs.</p><p>In the next article, I shall explain how to do integration testing on the APIs.</p><p>Once again, a complete working source code of the above application is available on <a href="https://github.com/thecodinganalyst/graphql">https://github.com/thecodinganalyst/graphql</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3750533bc7eb" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/getting-started-with-spring-and-graphql-3750533bc7eb">Getting started with Spring and GraphQL</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Start Tutorial on Microservices with Spring Cloud Netflix Eureka]]></title>
            <link>https://levelup.gitconnected.com/quick-start-tutorial-on-microservices-with-spring-cloud-netflix-eureka-5b799ee28f7e?source=rss-b7d1517f4110------2</link>
            <guid isPermaLink="false">https://medium.com/p/5b799ee28f7e</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[openfeign]]></category>
            <category><![CDATA[netflix-eureka]]></category>
            <category><![CDATA[spring-cloud]]></category>
            <dc:creator><![CDATA[Dennis]]></dc:creator>
            <pubDate>Sat, 29 Jul 2023 03:14:12 GMT</pubDate>
            <atom:updated>2023-07-30T16:49:25.747Z</atom:updated>
            <content:encoded><![CDATA[<p>In traditional application development, we have everything under a single project. But when the project gets bigger, involving multiple teams, it might make sense to split a monolithic application into multiple smaller applications, each governed by a different team, and each of the smaller applications can still work together like one application. That is the concept of microservices.</p><p>Splitting an application into different smaller applications inevitably comes with additional complexities. The most eminent one is that we now need a way for the applications to talk to one another. Unlike a monolith application, we cannot just import the files and call the functions. Since our applications now reside in different servers, we have to call one another over the network, usually with api calls. And in order to call other applications reliably, we need another service to register all the microservices, and provide the address of each microservice, so that we don’t need to fix the api calls to certain ip addresses. Certain microservices can be expecting more load, and will be available in more than 1 instance, so the server will also need to provide load balancing to distribute the load. These are additional tasks for the application as a whole, on top of providing what the application is meant to do. So unless there is real requirement to split the applications to be hosted at different places, even while still on the same cloud environment, microservices can meant additional costs in time, complexity, and money.</p><p>Because it is so complex, having a framework to take care of these additional complexities can really help. <a href="https://spring.io/projects/spring-cloud">Spring Cloud</a> is the goto framework to use if you are using java and spring boot. There are a few implementations for the microservice architecture mentioned above that are directly supported by the spring cloud project, namely <a href="https://github.com/Netflix/eureka">Netflix Eureka</a>, <a href="https://www.consul.io/">Hashicorp Consul</a>, and <a href="https://github.com/Netflix/eureka">Apache Zookeeper</a>, serving more or less the same functionalities of service discovery, coordination, and configuration management in microservices architecture. In this article, I will describe how to create a microservice architecture using Netflix Eureka with the <a href="https://spring.io/projects/spring-cloud-netflix">Spring Cloud Netflix Eureka</a> project.</p><p>Considering a ISP Service Centre, where the ISP provides broadband, mobile, and cable tv services, and the service centre provides customer service to walk-in customers who wanted to get help for the services they subscribed from this ISP. There is a central queue, where walk-in customers will register their mobile number to get a queue ticket, regardless of which service they need help for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/0*FMDCk8ZyIwS4g6fS.png" /></figure><p>To kickstart the development, we shall create a Eureka Server application to handle the registration of the microservices, we shall name the project — EurekaServer. In our IDE, we will create a new spring project with 2 dependencies - <a href="https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web">Spring Boot Starter Web</a> and <a href="https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-server">Spring Cloud Starter Netflix Eureka Server</a>. Our build.gradle file will look something like this</p><pre>plugins {<br>    id &#39;java&#39;<br>    id &#39;org.springframework.boot&#39; version &#39;3.1.2&#39;<br>    id &#39;io.spring.dependency-management&#39; version &#39;1.1.2&#39;<br>}<br><br>group = &#39;com.hevlar.queue&#39;<br>version = &#39;0.0.1-SNAPSHOT&#39;<br><br>java {<br>    sourceCompatibility = &#39;17&#39;<br>}<br><br>repositories {<br>    mavenCentral()<br>}<br><br>ext {<br>    set(&#39;springCloudVersion&#39;, &quot;2022.0.3&quot;)<br>}<br><br>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>    implementation &#39;org.springframework.cloud:spring-cloud-starter-netflix-eureka-server&#39;<br>    testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br>}<br><br>dependencyManagement {<br>    imports {<br>        mavenBom &quot;org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}&quot;<br>    }<br>}<br><br>tasks.named(&#39;test&#39;) {<br>    useJUnitPlatform()<br>}</pre><p>Then in our application class, we simply add the @EnableEurekaServer annotation.</p><pre>@SpringBootApplication<br>@EnableEurekaServer<br>public class EurekaServerApplication {<br><br>    public static void main(String[] args) {<br>        SpringApplication.run(EurekaServerApplication.class, args);<br>    }<br>}</pre><p>Then we populate the src\main\resources\application.properties with the application name, server, as well as the following eureka client properties.</p><pre>spring.application.name=eureka-server<br>server.port=8761<br><br>eureka.client.register-with-eureka=false<br>eureka.client.fetch-registry=false</pre><p>The 2 eureka properties are required for the eureka server instance, so that it will not keep trying to ping the eureka server. That is because the eureka server is also a eureka client, and eureka clients are supposed to ping the server every now and then so that the server can know that it is alive. We don’t need the server to do that, so we set these 2 properties to false.</p><p>That’s it! If we just boot-run the application and navigate to http://localhost:8761, we should see the following page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4esdaar8p33VGqCs.png" /></figure><p>Next, we shall create the application for the central queue system, and we create another spring boot project named — QueueProvider, with the following dependencies - <a href="https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web">Spring Boot Starter Web</a> and <a href="https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-client">Spring Cloud Starter Netflix Eureka Client</a>.</p><p>Our build.gradle will look like this</p><pre>plugins {<br>    id &#39;java&#39;<br>    id &#39;org.springframework.boot&#39; version &#39;3.1.2&#39;<br>    id &#39;io.spring.dependency-management&#39; version &#39;1.1.2&#39;<br>}<br><br>group = &#39;com.hevlar.queue&#39;<br>version = &#39;0.0.1-SNAPSHOT&#39;<br><br>java {<br>    sourceCompatibility = &#39;17&#39;<br>}<br><br>repositories {<br>    mavenCentral()<br>}<br><br>ext {<br>    set(&#39;springCloudVersion&#39;, &quot;2022.0.3&quot;)<br>}<br><br>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>    implementation &#39;org.springframework.cloud:spring-cloud-starter-netflix-eureka-client&#39;<br>    testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br>}<br><br>dependencyManagement {<br>    imports {<br>        mavenBom &quot;org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}&quot;<br>    }<br>}<br><br>tasks.named(&#39;test&#39;) {<br>    useJUnitPlatform()<br>}</pre><p>And again, we update our application.properties with the application name and server port.</p><pre>spring.application.name=queue-provider<br>server.port=8100<br><br>eureka.client.service-url.defaultZone=http://localhost:8761/eureka/</pre><p>The eureka.client.service-url.defaultZone is a map of the urls to communicate with the eureka server, for the client to poll the server to let it know it’s alive.</p><p>This QueueProvider application will serve a queue number api from the default host - http://localhost:8100/. For simplicity sake, we just update our application class with the @RestController annotation, and create a @GetMapping function to serve an <a href="https://www.baeldung.com/java-atomic-variables">AtomicInteger</a>, so that the queue number can be thread-safe.</p><pre>@SpringBootApplication<br>@EnableDiscoverClient<br>@RestController<br>public class QueueProviderApplication {<br>  <br>  AtomicInteger centralQueue = new AtomicInteger(1);<br>   <br>  public static void main(String[] args) {<br>    SpringApplication.run(QueueProviderApplication.class, args);<br>  }<br><br>  @GetMapping<br>  public Integer getQueue(){<br>    return centralQueue.getAndIncrement();<br>  }<br>}</pre><p>The @EnableDiscoveryClient is part of the spring cloud ecosystem, and is used to enable service discovery capabilities in spring cloud applications. It also works with other implementations like Hashicorp Consul and Apache Zookeeper. Service discovery is a critical aspect in microservices architecture, where multiple services need to communicate with each other. In a microservices architecture, the services are dynamic, and can be added and removed under different scenarios based on scaling requirements, service failures, etc. Service discovery allow services to find and communicate with one another without relying on hardcoded URLs or IP addresses, which are not practical in a dynamic environment. With the @EnableDiscoveryClient annotation, the application will register itself with the chosen service registry (in our case, the Eureka server) with its name, instance id, port, etc, so that the service is visible to other services. Then it will also send regular heartbeats to the service registry so that it the service registry will know that the service is up. Then other services in the registry can lookup available instances of a particular service based on the service name.</p><p>We can now bootRun this application, and navigate to http://localhost:8100 to get our queue number served. Do refresh it a few times to see the queue number increments itself.</p><p>We navigate back to our eureka server, and we should see the new QueueProvider instance in the Instances currently registered with Eureka section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EuLl_jEx00LVclvR.png" /></figure><p>Lastly, we want to create the BroadbandQueue application to simulate the broadband branch of the ISP, getting the central queue number from the QueueProvider application. So, we create another eureka client application with the same <a href="https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-web">Spring Boot Starter Web</a> and <a href="https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-netflix-eureka-client">Spring Cloud Starter Netflix Eureka Client</a> dependencies. And in order to call the api from QueueManager, we will need a web service client to call the api, and for this application, we are going to use <a href="https://spring.io/projects/spring-cloud-openfeign">OpenFeign</a>, adding <a href="https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign">Spring Cloud Starter OpenFeign</a> to the dependencies.</p><pre>plugins {<br>    id &#39;java&#39;<br>    id &#39;org.springframework.boot&#39; version &#39;3.1.2&#39;<br>    id &#39;io.spring.dependency-management&#39; version &#39;1.1.2&#39;<br>}<br><br>group = &#39;com.hevlar.queue&#39;<br>version = &#39;0.0.1-SNAPSHOT&#39;<br><br>java {<br>    sourceCompatibility = &#39;17&#39;<br>}<br><br>repositories {<br>    mavenCentral()<br>}<br><br>ext {<br>    set(&#39;springCloudVersion&#39;, &quot;2022.0.3&quot;)<br>}<br><br>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>    implementation &#39;org.springframework.cloud:spring-cloud-starter-netflix-eureka-client&#39;<br>    implementation &#39;org.springframework.cloud:spring-cloud-starter-openfeign&#39;<br>    testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br>}<br><br>dependencyManagement {<br>    imports {<br>        mavenBom &quot;org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}&quot;<br>    }<br>}<br><br>tasks.named(&#39;test&#39;) {<br>    useJUnitPlatform()<br>}</pre><p>Just like the QueueProvider, we need to name our application name, define the port, and set the eureka server in our application.properties.</p><pre>spring.application.name=broadband-queue<br>server.port=8200<br><br>eureka.client.service-url.defaultZone=http://localhost:8761/eureka/</pre><p>In our application class, we need to add the @EnableDiscoveryClient and @EnableFeignClients annotations.</p><pre>@SpringBootApplication<br>@EnableDiscoveryClient<br>@EnableFeignClients<br>public class BroadbandQueueApplication {<br>  public static void main(String[] args) {<br>    SpringApplication.run(BroadbandQueueApplication.class, args);<br>  }<br>}</pre><p>The @EnableFeignClients will enable the automatic scanning of Feign client interfaces within the package. Feign is a declarative web service client developed by Netflix and integrated into the spring cloud ecosystem, providing an easy and concise way to interact with RESTful services. To use feign, we need to declare interfaces annotated with the @FeignClient interface, and provide the apis as the interface methods. The application annotated with @EnableFeignClients will scan for interfaces annotated with the @FeignClient and create proxy implementation for each discovered interface. Then these feign clients can be injected into other components and used to make http requests to the corresponding services.</p><p>So we shall declare our feign interface — external/QueueProvider.</p><pre>@FeignClient(&quot;queue-provider&quot;)<br>public interface QueueProvider {<br>    @RequestMapping(value = &quot;/&quot;, method = RequestMethod.GET)<br>    Integer getQueue();<br>}</pre><p>The value queue-provider is the service name of the QueueProvider service we created earlier. By default, the service name will be the spring application name defined in the spring.application.name property. It’s good that because we are using Feign, we don’t need to specify a hardcoded ip address like http://localhost:8100, but just the service name, so that it can be more dynamic. The getQueue method, annotated with the @RequestMapping, defines the actual api our application will need to call. In our example, we are just calling the root - http://localhost:8100/, so the value in the @RequestMapping is just /, and we define the method to use as GET. As defined in the return type of the getQueue method, the api is supposed to return just an Integer.</p><p>So now that we have the api to use defined, we can now create the api we are going to expose in our BroadbandQueue application. In our example, we are going to expose the api http://localhost:8200/queue/{mobileNo}, which requires a mobileNo as the parameter. This simulates the scenario in a service centre, that a walk-in customer will need to enter his/her mobile number to register for a queue number, so that the application can send an sms to the customer when it is his/her turn. So now, we define a BroadbandQueueController class to define the api we are going to expose.</p><pre>@RestController<br>public class BroadbandQueueController {<br><br>  private final QueueProvider queueProvider;<br><br>  public BroadbandQueueController(QueueProvider queueProvider){<br>    this.queueProvider = queueProvider;<br>  }<br><br>  @RequestMapping(&quot;/queue/{mobileNo}&quot;)<br>  public BroadbandQueue registerQueue(@PathVariable @NonNull String mobileNo){<br>    return new BroadbandQueue(mobileNo, queueProvider.getQueue());<br>  }<br>}</pre><p>The function returns a BroadbandQueue defined as such -</p><pre>public record BroadbandQueue(String mobileNo, Integer queueNo){}</pre><p>So now, if we bootRun this BroadbandQueue application and look at our Eureka server, we can see it in the list of instances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*q5CTCEEIeAf2fhq9.png" /></figure><p>And we can navigate to the BroadbandQueue application on http://localhost:8200/queue/{arbitrary mobile no}, we can see it working.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/0*41J40iEXYxs77g9V.png" /></figure><p>You can refresh the page a few times to see the queue number increasing.</p><p>In our BroadbandQueueController, we inject the QueueProvider feign client interface we defined earlier, and call the getQueue() method to get the queue number from the QueueProvider service, and pass the value in its own api. So in this way, we demonstrated how to call another service from a service.</p><p>The source code for the example above is available on <a href="https://github.com/thecodinganalyst/QueueSystem">https://github.com/thecodinganalyst/QueueSystem</a>.</p><p>This article is originally published on <a href="https://www.thecodinganalyst.com/tutorial/quick-start-tutorial-on-microservices-with-spring-cloud-netflix-eureka/">https://www.thecodinganalyst.com/tutorial/quick-start-tutorial-on-microservices-with-spring-cloud-netflix-eureka/</a>.</p><h2>Level Up Coding</h2><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li></ul><p>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></p><p><strong>🧠 AI Tools ⇒ </strong><a href="https://www.aimind.so/prompt-generator?utm_source=luc&amp;utm_medium=article"><strong>Become an AI prompt engineer</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5b799ee28f7e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/quick-start-tutorial-on-microservices-with-spring-cloud-netflix-eureka-5b799ee28f7e">Quick Start Tutorial on Microservices with Spring Cloud Netflix Eureka</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A quickstart refresher to React for programmers]]></title>
            <link>https://levelup.gitconnected.com/a-quickstart-refresher-to-react-for-programmers-ebf8ef3be436?source=rss-b7d1517f4110------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebf8ef3be436</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend]]></category>
            <dc:creator><![CDATA[Dennis]]></dc:creator>
            <pubDate>Mon, 10 Jul 2023 15:35:28 GMT</pubDate>
            <atom:updated>2023-07-11T02:57:18.704Z</atom:updated>
            <content:encoded><![CDATA[<p>Like <a href="https://www.thecodinganalyst.com/knowledgebase/Getting-started-with-angular/">Angular</a>, React is another popular library to build frontend single-page-applications. We can create a react app by using <a href="https://create-react-app.dev/">Create React App</a>, run npx create-react-app --template typescript &lt;app-name&gt; and the scaffolding of the application will be generated for us in typescript.</p><h3>React Component returns HTML rendering in JSX</h3><p>Each function is supposed to return a rendering of a html component, in the form of JSX. JSX is essentially a javascript extension that includes a html syntax, so that we can return html in our react functions. It is almost completely the same as html, except that</p><ol><li>because there are some html keywords that clashes with some javascript keywords (e.g. class), there are some slight changes to the html DOM, which can be found at <a href="https://react.dev/reference/react-dom/components">https://react.dev/reference/react-dom/components</a>.</li><li>there should be a single root element, you can use &lt;&gt;&lt;/&gt; as the root.</li><li>all the tags must be closed.</li><li>html syntax are inside () brackets, while js/ts syntax are inside {} brackets.</li></ol><p>A simple way is to use a jsx convertor - <a href="https://transform.tools/html-to-jsx">https://transform.tools/html-to-jsx</a> to easily transform your html to jsx.</p><pre>const TaskList = () =&gt; {<br>  const title: string = &quot;Tasks&quot;;<br>  return (<br>    &lt;&gt;<br>      &lt;b&gt;{title}&lt;/b&gt;<br>      &lt;ul&gt;<br>        &lt;li&gt;Task 1&lt;/li&gt;<br>        &lt;li&gt;Task 2&lt;/li&gt;<br>        &lt;li&gt;Task 3&lt;/li&gt;<br>      &lt;/ul&gt;<br>    &lt;/&gt;<br>  );<br>}<br>export default TaskList;</pre><p><a href="https://codesandbox.io/s/react-basic-spwtdj">CodeSandbox</a></p><h3>React is a state machine, rerenders upon state changes</h3><p>To have states in react, we need to use the <a href="https://react.dev/reference/react/useState">useState hook</a> to define the state.</p><h4>1 . The const [tasks, setTasks] = useState(initialTask) sets the state variable to be named tasks, and we can use the function setTasks to update the state. The initial value of tasks is set to initialTask.</h4><blockquote>useState is a hook, and hooks are only allowed to be called at the top level of your component.</blockquote><h4>2. In the below example, only changes to the state - tasks, i.e. using of setTasks, will trigger a rerender of the component. Meaning, if we simply reassign the task with e.g. tasks = updatedTask, or tasks.push(newTask), etc, will not trigger the rerendering.</h4><blockquote>Instead of assigning a new value to setTasks, the setter function also accepts a function as the parameter - setTasks(currentTasks =&gt; return newTasks), so that it can return a new state based on the current state.</blockquote><blockquote>If count = 5, calling setCount(count + 1) 3 times is calling setCount(5 + 1) 3 times, which results in count = 6. Use setCount(count =&gt; count + 1) instead if you want to increment it 3 times.</blockquote><h4>3. States are immutable, so to reassign the states with the existing values, we can use something like {…task, done: checked} to create a new copy of task, and set the done property to checked. Or for the array, we can use the array functions like <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map">map</a> or <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">filter</a> that returns a new copy of the array.</h4><h4>4. Because the UI is assigned with values from the state, we need to provide functions to update the state, so that the UI will be updated upon human inputs. In the below example, without the onChange method, to call the checkBoxHandler to update the value of the task, clicking on the checkbox will not check or uncheck it.</h4><pre>&lt;input<br>  type=&quot;checkbox&quot;<br>  checked={task.done}<br>  onChange={(e) =&gt; checkBoxHandler(task.id, e.target.checked)}<br>/&gt;</pre><h4>5. Every iterating/looping component/tag needs to have a key with a unique value, to uniquely identify the looping component, e.g. &lt;li key={task.id}&gt;.</h4><pre>import { useState } from &quot;react&quot;;<br><br>interface Task {<br>  id: number;<br>  title: string;<br>  done: boolean;<br>}<br><br>const initialTasks: Task[] = [<br>  { id: 0, title: &quot;Buy Milk&quot;, done: false },<br>  { id: 1, title: &quot;Water Plants&quot;, done: true },<br>  { id: 2, title: &quot;Send Letter&quot;, done: false }<br>];<br><br>const TaskList = () =&gt; {<br>  const title: string = &quot;Tasks&quot;;<br>  const [tasks, setTasks] = useState(initialTasks);<br>  const checkBoxHandler = (id: number, checked: boolean) =&gt; {<br>    setTasks(<br>      tasks.map((task) =&gt; {<br>        if (task.id === id) {<br>          return { ...task, done: checked };<br>        } else {<br>          return task;<br>        }<br>      })<br>    );<br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;b&gt;{title}&lt;/b&gt;<br>      &lt;ul&gt;<br>        {tasks.map((task) =&gt; (<br>          &lt;li key={task.id}&gt;<br>            &lt;input<br>              type=&quot;checkbox&quot;<br>              checked={task.done}<br>              onChange={(e) =&gt; checkBoxHandler(task.id, e.target.checked)}<br>            /&gt;<br>            {task.title}<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/&gt;<br>  );<br>};<br>export default TaskList;</pre><p><a href="https://codesandbox.io/s/react-state-k7crss">CodeSandbox</a></p><h3>Passing properties in React</h3><p>We can provide properties to our component in the parameter of our component function. In the below example, we provide 2 properties - task and checkBoxHandler, inside the curly brackets {}, which denotes the contents as part of an object.</p><pre>const TaskItem = ({ task, checkBoxHandler }: TaskItemProps) =&gt; {<br>  return (<br>    &lt;li&gt;<br>      &lt;input<br>        type=&quot;checkbox&quot;<br>        checked={task.done}<br>        onChange={(e) =&gt; checkBoxHandler(task.id, e.target.checked)}<br>      /&gt;<br>      {task.title}<br>    &lt;/li&gt;<br>  );<br>};</pre><p>Because we are using typescript, the types of everything needs to be provided, so we need to declare the type of the parameter object passed in to the component, so we declare this object as TaskItemProps, and we declared it before the function as such.</p><pre>type TaskItemProps = {<br>  task: Task;<br>  checkBoxHandler: (id: number, checked: boolean) =&gt; void;<br>};</pre><p>So the full result is as below.</p><pre>import { useState } from &quot;react&quot;;<br><br>interface Task {<br>  id: number;<br>  title: string;<br>  done: boolean;<br>}<br><br>const initialTasks: Task[] = [<br>  { id: 0, title: &quot;Buy Milk&quot;, done: false },<br>  { id: 1, title: &quot;Water Plants&quot;, done: true },<br>  { id: 2, title: &quot;Send Letter&quot;, done: false }<br>];<br><br>type TaskItemProps = {<br>  task: Task;<br>  checkBoxHandler: (id: number, checked: boolean) =&gt; void;<br>};<br><br>const TaskItem = ({ task, checkBoxHandler }: TaskItemProps) =&gt; {<br>  return (<br>    &lt;li&gt;<br>      &lt;input<br>        type=&quot;checkbox&quot;<br>        checked={task.done}<br>        onChange={(e) =&gt; checkBoxHandler(task.id, e.target.checked)}<br>      /&gt;<br>      {task.title}<br>    &lt;/li&gt;<br>  );<br>};<br><br>const TaskList = () =&gt; {<br>  const title: string = &quot;Tasks&quot;;<br>  const [tasks, setTasks] = useState(initialTasks);<br>  const checkBoxHandler = (id: number, checked: boolean) =&gt; {<br>    setTasks(<br>      tasks.map((task) =&gt; {<br>        if (task.id === id) {<br>          return { ...task, done: checked };<br>        } else {<br>          return task;<br>        }<br>      })<br>    );<br>  };<br><br>  return (<br>    &lt;&gt;<br>      &lt;b&gt;{title}&lt;/b&gt;<br>      &lt;ul&gt;<br>        {tasks.map((task) =&gt; (<br>          &lt;TaskItem<br>            key={task.id}<br>            task={task}<br>            checkBoxHandler={checkBoxHandler}<br>          &gt;&lt;/TaskItem&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/&gt;<br>  );<br>};<br>export default TaskList;</pre><p><a href="https://codesandbox.io/s/react-properties-g2g8dv?file=/src/App.tsx">CodeSandbox</a></p><h3>Use useRef to keep variables updated but not triggering re-renders</h3><p>In React, when we declare any variables normally like let title = &#39;hello world&#39;, and try to mutate it by title = &#39;bye world&#39;, the title will be reset back to hello world every time the component re-renders. If we want to keep the variable updated, but we don’t need to trigger any re-rendering when the value changes, we can use useRef to declare it, and use &lt;ref&gt;.current to retrieve it or mutate it.</p><p>The below example shows a number text box and an add button. Typing a number in the text box and click the add button will add the number to the previous total (which is 0 for the first time), and show the total below. There is another undo button, which undoes the last action. In order to do that, each time the add button is clicked, the number will be added to a history list. So we need the data in the history list to persist throughout the re-renders, but we don’t need any changes to the history to trigger a re-render, so a useRef will be the solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*_IGguv2VN69fH2IQY9B8gA.png" /></figure><pre>import { useState, useRef } from &quot;react&quot;;<br><br>const Accumulator = () =&gt; {<br>  const [value, setValue] = useState(&quot;&quot;);<br>  const [total, setTotal] = useState(0);<br>  let history = useRef&lt;number[]&gt;([]);<br>  const updateTotal = (num: number) =&gt; {<br>    setTotal((total) =&gt; total + num);<br>    history.current.push(num);<br>    setValue(&quot;&quot;);<br>  };<br>  const undoAdd = () =&gt; {<br>    if (history.current.length &gt; 0) {<br>      let lastValue = history.current.pop() || 0;<br>      setValue(String(lastValue));<br>      setTotal((total) =&gt; total - lastValue);<br>    }<br>  };<br>  return (<br>    &lt;div&gt;<br>      &lt;input<br>        type=&quot;number&quot;<br>        value={value}<br>        onChange={(e) =&gt; setValue(e.target.value)}<br>      /&gt;<br>      &lt;button onClick={(e) =&gt; updateTotal(+value)}&gt;Add&lt;/button&gt;<br>      &lt;br /&gt;<br>      Total: {total}<br>      &lt;br /&gt;<br>      &lt;button disabled={history.current.length === 0} onClick={() =&gt; undoAdd()}&gt;<br>        Undo<br>      &lt;/button&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export default Accumulator;</pre><p><a href="https://codesandbox.io/s/react-ref-demo-wnfljc">CodeSandbox</a></p><h3>Use useEffect to create side effects after rendering<a href="https://www.thecodinganalyst.com/knowledgebase/a-quick-start-refresher-to-react-for-programmers/#use-useeffect-to-create-side-effects-after-rendering">P</a></h3><ol><li>Call useEffect(() =&gt; { ...execute something }) to execute something everytime after each render</li><li>Call useEffect(() =&gt; { ...execute something }, []) to execute something once after the component mounts the first time.</li><li>Call useEffect(() =&gt; { ...execute something }, [someVar]) to execute something each time someVar changes value.</li><li>Call useEffect(() =&gt; { ...execute something; return () =&gt; { ...execute cleanup } }, []) to execute cleanup actions each time before the effect runs again, and once before the component unmounts.</li></ol><p>Below is an example to use effects to fetch the list of users when the component mounts the first time, and fetches the todos for the selected user when the selected user changes.</p><pre>import { useEffect, useState } from &quot;react&quot;;<br><br>interface Todo {<br>  userid: number;<br>  id: number;<br>  title: string;<br>  completed: boolean;<br>}<br><br>interface User {<br>  id: number;<br>  name: string;<br>}<br><br>export default function TodoList() {<br>  const [users, setUsers] = useState&lt;User[]&gt;([]);<br>  const [selectedUserId, setSelectedUserId] = useState&lt;number | undefined&gt;(<br>    undefined<br>  );<br>  const [todos, setTodos] = useState&lt;Todo[]&gt;([]);<br><br>  async function fetchUsers() {<br>    await fetch(&quot;https://jsonplaceholder.typicode.com/users&quot;)<br>      .then((response) =&gt; response.json())<br>      .then((json) =&gt; {<br>        setUsers(json);<br>        setSelectedUserId(json &amp;&amp; json.length &gt; 0 ? json[0].id : 0);<br>      });<br>  }<br><br>  async function fetchTodos(userId: number) {<br>    await fetch(`https://jsonplaceholder.typicode.com/users/${userId}/todos`)<br>      .then((response) =&gt; response.json())<br>      .then((json) =&gt; setTodos(json));<br>  }<br><br>  useEffect(() =&gt; {<br>    fetchUsers();<br>  }, []);<br><br>  useEffect(() =&gt; {<br>    if (selectedUserId) {<br>      fetchTodos(selectedUserId!);<br>    }<br>  }, [selectedUserId]);<br><br>  return (<br>    &lt;div&gt;<br>      User:<br>      &lt;select<br>        value={selectedUserId}<br>        onChange={(e) =&gt; setSelectedUserId(Number(e.target.value))}<br>      &gt;<br>        {users.map((user) =&gt; (<br>          &lt;option key={user.id} value={user.id}&gt;<br>            {user.name}<br>          &lt;/option&gt;<br>        ))}<br>      &lt;/select&gt;<br>      &lt;ul&gt;<br>        {todos.map((todo) =&gt; (<br>          &lt;li key={todo.id}&gt;<br>            {todo.title} {todo.completed &amp;&amp; &quot;✔&quot;}<br>          &lt;/li&gt;<br>        ))}<br>      &lt;/ul&gt;<br>    &lt;/div&gt;<br>  );<br>}</pre><p><a href="https://codesandbox.io/s/react-effects-demo-gfjxg4">CodeSandbox</a></p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🧠 AI Tools ⇒ <a href="https://www.aimind.so/">View Now</a></li></ul><p>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></p><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebf8ef3be436" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/a-quickstart-refresher-to-react-for-programmers-ebf8ef3be436">A quickstart refresher to React for programmers</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to deal with nested entities in Spring Controller]]></title>
            <link>https://levelup.gitconnected.com/how-to-deal-with-nested-entities-in-spring-controller-8bb404eae3a2?source=rss-b7d1517f4110------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bb404eae3a2</guid>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-boot]]></category>
            <dc:creator><![CDATA[Dennis]]></dc:creator>
            <pubDate>Wed, 28 Jun 2023 06:51:37 GMT</pubDate>
            <atom:updated>2023-06-29T23:38:06.956Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating a webservice with Spring is almost trivial, you usually won’t go wrong by following the <a href="https://www.thecodinganalyst.com/tutorial/Spring-boot-application-getting-started/">tutorials</a>. However, things can get tricky sometimes when you want more features out of it. One example is when you are having nested entities like a father and sons relationship.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*hmUT3A2Xjo3wJoGp5eEdIw.png" /></figure><p>Using Spring Boot and Spring Data, the entities can be declared as such.</p><pre>@Data<br>@Builder<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@Entity<br>public class Father {<br>    @Id<br>    @GeneratedValue<br>    Long id;<br>    String name;<br>    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = &quot;father&quot;, orphanRemoval = true)<br>    @Builder.Default<br>    List&lt;Son&gt; sonList = new ArrayList&lt;&gt;();<br><br>}</pre><pre>@Data<br>@Entity<br>@Builder<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class Son {<br>    @Id<br>    @GeneratedValue<br>    Long id;<br>    String name;<br>    @ManyToOne(fetch = FetchType.LAZY)<br>    @JoinColumn<br>    @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = &quot;id&quot;, scope = Father.class)<br>    Father father;<br>}</pre><p>But when we try to do a test, it might even seem ok when getting the result from the insert, but not when we try to use the get to get the inserted result again from the controller.</p><pre>@Test<br>void create_willFail() throws Exception {<br>    Son son1 = Son.builder().name(&quot;son 1&quot;).build();<br>    Son son2 = Son.builder().name(&quot;son 2&quot;).build();<br>    Father father = Father.builder().name(&quot;father&quot;).sonList(List.of(son1, son2)).build();<br><br>    MvcResult insertResult = mvc.perform(post(&quot;/fathers&quot;)<br>            .contentType(MediaType.APPLICATION_JSON)<br>            .content(objectMapper.writeValueAsString(father)))<br>            .andExpect(status().isCreated())<br>            .andReturn();<br>    String insertResultJson = insertResult.getResponse().getContentAsString();<br>    Father insertedFather = objectMapper.readValue(insertResultJson, Father.class);<br>    assertThat(insertedFather.getSonList().size(), is(2));<br><br>    MvcResult getResult = mvc.perform(get(&quot;/fathers/&quot; + insertedFather.getId())<br>                    .contentType(MediaType.APPLICATION_JSON)<br>                    .content(objectMapper.writeValueAsString(father)))<br>            .andExpect(status().isOk())<br>            .andReturn();<br>    String getResultJson = getResult.getResponse().getContentAsString();<br>    Father gotFather = objectMapper.readValue(getResultJson, Father.class);<br>    assertThat(gotFather.getSonList().size(), is(0));<br>}</pre><p>The reason we get the 2 sons from the first assertion is because we already added the 2 sons in the father object which we have sent to the controller. But because the sons doesn’t have the father field set, the father field of the 2 sons are empty. And since the foreign key is at the son, the relationship isn’t persisted.</p><p>One might think an easy solution is to set the father field in the son explicitly, but it will still fail with a stackoverflow. It happens because when the objectMapper will be recursively serializing the sonList and father relationships. Plus, it doesn’t feel intuitive for the api user to set the father field in the sons, when the sonList of the father field is already populated.</p><pre>@Test<br>void create_willOverflow(){<br>    Son son1 = Son.builder().name(&quot;son 1&quot;).build();<br>    Son son2 = Son.builder().name(&quot;son 2&quot;).build();<br>    Father father = Father.builder().name(&quot;father&quot;).sonList(List.of(son1, son2)).build();<br>    son1.setFather(father);<br>    son2.setFather(father);<br><br>    assertThrows(JsonMappingException.class, () -&gt; objectMapper.writeValueAsString(father));<br>}</pre><p>Let’s do it again with a ParentClass and ChildClass.</p><pre>@Data<br>@Entity<br>@Builder<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class ParentClass {<br>    @Id<br>    @GeneratedValue<br>    Long id;<br>    String name;<br>    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = &quot;parent&quot;, orphanRemoval = true)<br>    @Builder.Default<br>    List&lt;ChildClass&gt; children = new ArrayList&lt;&gt;();<br>}</pre><pre>@Data<br>@Entity<br>@Builder<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class ChildClass {<br>    @Id<br>    @GeneratedValue<br>    Long id;<br>    String name;<br>    @ManyToOne(fetch = FetchType.LAZY)<br>    @JoinColumn<br>    @ToString.Exclude<br>    ParentClass parent;<br>}</pre><p>Instead of using our domain class directly in the controllers, it is better to create DTOs (<a href="https://martinfowler.com/eaaCatalog/dataTransferObject.html">Data Transfer Objects</a>) for the entities class instead, so that we can also hide certain information of our entities that shouldn’t be known by the api users.</p><pre>@Data<br>@Builder<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class ParentClassDto {<br>    @EqualsAndHashCode.Exclude<br>    Long id;<br>    String name;<br>    List&lt;ChildClassDto&gt; children;<br><br>    public ParentClass toParentClass(){<br>        ParentClass parentClass = ParentClass.builder()<br>                .id(id)<br>                .name(name)<br>                .children(ChildClassDto.fromChildClassDtoList(children))<br>                .build();<br>        parentClass.getChildren().forEach(child -&gt; child.setParent(parentClass));<br>        return parentClass;<br>    }<br><br>    public static ParentClassDto fromParentClass(ParentClass parentClass){<br>        return ParentClassDto.builder()<br>                .id(parentClass.getId())<br>                .name(parentClass.getName())<br>                .children(parentClass.getChildren().stream().map(ChildClassDto::fromChildClass).toList())<br>                .build();<br>    }<br>}</pre><pre>@Data<br>@Builder<br>@NoArgsConstructor<br>@AllArgsConstructor<br>public class ChildClassDto {<br>    @EqualsAndHashCode.Exclude<br>    Long id;<br>    String name;<br><br>    public ChildClass toChildClass(){<br>        return ChildClass.builder()<br>                .id(id)<br>                .name(name)<br>                .build();<br>    }<br><br>    public static ChildClassDto fromChildClass(ChildClass childClass){<br>        return ChildClassDto.builder()<br>                .id(childClass.getId())<br>                .name(childClass.getName())<br>                .build();<br>    }<br><br>    public static List&lt;ChildClass&gt; fromChildClassDtoList(List&lt;ChildClassDto&gt; childClassDtoList){<br>        return childClassDtoList.stream()<br>                .map(ChildClassDto::toChildClass)<br>                .toList();<br>    }<br>}</pre><p>In the DTOs, we can also provide the mapping methods to map the entities to DTOs, and vice versa. We can also use dedicated mapper class instead, and use Java Records for the DTOs, which makes it even cleaner. But we shall stick to this for now, so that we have less files to manage.</p><p>I also added the <a href="https://projectlombok.org/features/EqualsAndHashCode">@EqualsAndHashCode.Exclude</a> to the id fields, so that I can simply compare 2 DTOs just on the other value fields for equality, in order not to compare the fields one by one in my tests.</p><p>Then in my controller, I will only accept and return the DTOs. So I’ll have to convert the DTOs to my entity objects when receiving the values from the api calls, and convert them from entity objects back to DTOs when I return the results.</p><pre>@RestController<br>public class ParentClassController {<br>    ParentClassRepository parentClassRepository;<br><br>    public ParentClassController(ParentClassRepository parentClassRepository){<br>        this.parentClassRepository = parentClassRepository;<br>    }<br><br>    @GetMapping<br>    public List&lt;ParentClassDto&gt; list(){<br>        return parentClassRepository.findAll()<br>                .stream().<br>                map(ParentClassDto::fromParentClass)<br>                .toList();<br>    }<br><br>    @GetMapping(&quot;/{id}&quot;)<br>    public ParentClassDto get(@PathVariable(&quot;id&quot;) String id){<br>        ParentClass parentClass = parentClassRepository.findById(Long.valueOf(id))<br>                .orElseThrow(() -&gt; new ResponseStatusException(HttpStatus.NOT_FOUND));<br>        return ParentClassDto.fromParentClass(parentClass);<br>    }<br><br>    @PostMapping<br>    @ResponseStatus(HttpStatus.CREATED)<br>    public ParentClassDto create(@RequestBody ParentClassDto parentClassDto){<br>        ParentClass parentClass = parentClassRepository.save(parentClassDto.toParentClass());<br>        return ParentClassDto.fromParentClass(parentClass);<br>    }<br><br>    @PutMapping(&quot;/{id}&quot;)<br>    public ParentClassDto update(@PathVariable(&quot;id&quot;) String id, @RequestBody ParentClassDto parentClassDto){<br>        ParentClass parentClass = parentClassDto.toParentClass();<br><br>        ParentClass retrievedParentClass = parentClassRepository.findById(Long.valueOf(id))<br>                .orElseThrow(() -&gt; new ResponseStatusException(HttpStatus.NOT_FOUND));<br><br>        retrievedParentClass.setName(parentClassDto.getName());<br><br>        retrievedParentClass.getChildren().clear();<br>        List&lt;ChildClass&gt; updatedChildren = new ArrayList&lt;&gt;(parentClass.getChildren());<br>        updatedChildren.forEach(childClass -&gt; childClass.setParent(retrievedParentClass));<br>        retrievedParentClass.getChildren().addAll(updatedChildren);<br><br>        ParentClass updatedParentClass = parentClassRepository.save(retrievedParentClass);<br>        return ParentClassDto.fromParentClass(updatedParentClass);<br>    }<br><br>    @DeleteMapping(&quot;/{id}&quot;)<br>    public void delete(@PathVariable(&quot;id&quot;) String id){<br>        parentClassRepository.deleteById(Long.valueOf(id));<br>    }<br>}</pre><p>So now, I just have to add the children DTOs in my parent DTO, and deal only with the parent DTO when using the api.</p><pre>@SpringBootTest<br>@AutoConfigureMockMvc<br>class ParentClassControllerTest {<br>    @Autowired<br>    MockMvc mvc;<br>    @Autowired<br>    ObjectMapper objectMapper;<br><br>    @Test<br>    void update() throws Exception {<br>        // First create the nested entities<br>        ChildClassDto child1 = ChildClassDto.builder()<br>                .name(&quot;child1&quot;)<br>                .build();<br>        ChildClassDto child2 = ChildClassDto.builder()<br>                .name(&quot;child2&quot;)<br>                .build();<br>        ParentClassDto parent = ParentClassDto.builder()<br>                .name(&quot;Parent&quot;)<br>                .children(List.of(child1, child2))<br>                .build();<br><br>        MvcResult insertResult = mvc.perform(post(&quot;/&quot;)<br>                .contentType(MediaType.APPLICATION_JSON)<br>                .content(objectMapper.writeValueAsString(parent)))<br>                .andExpect(status().isCreated())<br>                .andReturn();<br>        String insertResultJson = insertResult.getResponse().getContentAsString();<br>        ParentClassDto insertedParent = objectMapper.readValue(insertResultJson, ParentClassDto.class);<br><br>        // Then update<br>        ChildClassDto child1Update = ChildClassDto.builder().name(&quot;Updated Child 1&quot;).build();<br>        ChildClassDto child2Update = ChildClassDto.builder().name(&quot;Updated Child 2&quot;).build();<br>        ParentClassDto parentUpdate = ParentClassDto.builder()<br>                .name(&quot;Updated Parent&quot;)<br>                .children(List.of(child1Update, child2Update))<br>                .build();<br><br>        MvcResult updateResult = mvc.perform(put(&quot;/&quot; + insertedParent.getId().toString())<br>                .contentType(MediaType.APPLICATION_JSON)<br>                .content(objectMapper.writeValueAsString(parentUpdate)))<br>                .andExpect(status().isOk())<br>                .andReturn();<br>        String updateResultJson = updateResult.getResponse().getContentAsString();<br>        ParentClassDto updatedParent = objectMapper.readValue(updateResultJson, ParentClassDto.class);<br><br>        assertThat(updatedParent, is(parentUpdate));<br><br>        // Make sure next get still gets the same result<br>        MvcResult getResult = mvc.perform(get(&quot;/&quot; + insertedParent.getId().toString())<br>                        .contentType(MediaType.APPLICATION_JSON)<br>                        .content(objectMapper.writeValueAsString(parentUpdate)))<br>                .andExpect(status().isOk())<br>                .andReturn();<br>        String getResultJson = getResult.getResponse().getContentAsString();<br>        ParentClassDto gotParent = objectMapper.readValue(getResultJson, ParentClassDto.class);<br><br>        assertThat(gotParent, is(updatedParent));<br>    }<br>}</pre><p>A working copy of the above example is available on <a href="https://github.com/thecodinganalyst/SpringDataNestedEntityDemo">https://github.com/thecodinganalyst/SpringDataNestedEntityDemo</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bb404eae3a2" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-deal-with-nested-entities-in-spring-controller-8bb404eae3a2">How to deal with nested entities in Spring Controller</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with NestJS]]></title>
            <link>https://levelup.gitconnected.com/getting-started-with-nestjs-de7ea1713afd?source=rss-b7d1517f4110------2</link>
            <guid isPermaLink="false">https://medium.com/p/de7ea1713afd</guid>
            <category><![CDATA[nestjs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[nestjs-tutorial]]></category>
            <dc:creator><![CDATA[Dennis]]></dc:creator>
            <pubDate>Mon, 05 Jun 2023 15:07:40 GMT</pubDate>
            <atom:updated>2023-06-06T00:51:42.055Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://nestjs.com/">NestJS</a> is a nodejs framework for building backend applications, that is secure and scaleable. Following the SOLID principle, and having a modular architecture and built-in dependency injection system, it allows developers to create reliable and efficient backend systems without much effort.</p><p>To get started, we install the nestjs cli with npm install -g @nest/cli, then create a new project with nest new &lt;project-name&gt;. It then pretty much setup everything for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/251/0*xQKUZMKvrIoE6WQn.png" /></figure><p>First, let’s look at the main.ts, which is the file that really bootstraps our application, and you can see from the code that it listens to port 3000.</p><pre>import { NestFactory } from &#39;@nestjs/core&#39;;<br>import { AppModule } from &#39;./app.module&#39;;<br><br>async function bootstrap() {<br>  const app = await NestFactory.create(AppModule);<br>  await app.listen(3000);<br>}<br>bootstrap();</pre><p>So we navigate to localhost:3000 on our browser, and it just shows the Hello World!.</p><p>The nestjs structure is very similar to Angular, as in it is grouped into modules, and it uses the @ decorator with the imports, exports, providers etc to classify what are imported and exported to/from the module, which services it provides.</p><pre>@Module({<br>  imports: [],<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br>export class AppModule {}</pre><p>With the initial setup, nestjs creates an AppModule in the file named app.module.ts. Since nestjs is framework for building web backend applications, it has a controllers array variable to list the files which exposes the apis from this module. The AppController is the name of the class in app.controller.ts.</p><p>It also has a provider array variable with AppService in the list. Having the AppService in the providers variable means that AppService is available for <a href="https://www.thecodinganalyst.com/software%20engineering/dependency-injection/">dependency injection</a>.</p><p>Let’s first look at the AppService in the app.service.ts. The @Injectable() decorator marks the class as a provider, and it just has a single function called getHello().</p><pre>@Injectable()<br>export class AppService {<br>  getHello(): string {<br>    return &#39;Hello World!&#39;;<br>  }<br>}</pre><p>The AppController class in the app.controller.ts is decorated with the @Controller() to indicate that it is a controller and it can receive inbound requests and produce responses.</p><pre>@Controller()<br>export class AppController {<br>  constructor(private readonly appService: AppService) {}<br><br>  @Get()<br>  getHello(): string {<br>    return this.appService.getHello();<br>  }<br>}</pre><p>First, in the constructor, we inject the AppService. Then there is a function named getHello() which is decorated with the @Get() decorator. The Get() decorator marks it as a get request, and without any paths in the parameter, it is just listening to the root /. In the function, it just uses the AppService injected from the constructor, and returns the getHello().</p><p>To truely see the efficiency of nestjs, let’s create a REST API. Run the following command in the root folder of the application</p><pre>nest generate resource products</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/0*d9szHR6Y4XTbfMvu.png" /></figure><p>NestJS can create not just REST API, but also for graphQL, websockets, and microservices. But here, we will just select REST API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/0*9pltH2YmY5xfHMcT.png" /></figure><p>And let it generate the CRUD entry points for us.</p><p>We can see here it creates a new products module under the src folder, and creates all the module, service, controller, entity and dtos for us. And it also updates the AppModule to import the new ProductsModule.</p><pre>@Module({<br>  imports: [ProductsModule],<br>  controllers: [AppController],<br>  providers: [AppService],<br>})<br>export class AppModule {}</pre><p>The product.entity.ts contains the main Product entity for our module, with just an empty Product which we can customize.</p><pre>export class Product {}</pre><p>The create-product.dto.ts and update-product.dto.ts are data-transfer-objects, which are usually a subset of the original entity, just for the create and update apis, so that we don’t have to expose the unnecessary fields of the entity in the api. For example, the ID is going to be auto-generated, and not needed in the create api.</p><pre>export class CreateProductDto {}</pre><pre>export class UpdateProductDto extends PartialType(CreateProductDto) {}</pre><p>I like that the controller is created for us with all the necessary CRUD functions, and the service already injected in for us. You can see that there is a products in the @Controller() decorator, meaning this api will be exposed in localhost:3000/products.</p><pre>@Controller(&#39;products&#39;)<br>export class ProductsController {<br>  constructor(private readonly productsService: ProductsService) {}<br><br>  @Post()<br>  create(@Body() createProductDto: CreateProductDto) {<br>    return this.productsService.create(createProductDto);<br>  }<br><br>  @Get()<br>  findAll() {<br>    return this.productsService.findAll();<br>  }<br><br>  @Get(&#39;:id&#39;)<br>  findOne(@Param(&#39;id&#39;) id: string) {<br>    return this.productsService.findOne(+id);<br>  }<br><br>  @Patch(&#39;:id&#39;)<br>  update(@Param(&#39;id&#39;) id: string, @Body() updateProductDto: UpdateProductDto) {<br>    return this.productsService.update(+id, updateProductDto);<br>  }<br><br>  @Delete(&#39;:id&#39;)<br>  remove(@Param(&#39;id&#39;) id: string) {<br>    return this.productsService.remove(+id);<br>  }<br>}</pre><p>We just need to fill in the functions in our service.</p><pre>@Injectable()<br>export class ProductsService {<br>  create(createProductDto: CreateProductDto) {<br>    return &#39;This action adds a new product&#39;;<br>  }<br><br>  findAll() {<br>    return `This action returns all products`;<br>  }<br><br>  findOne(id: number) {<br>    return `This action returns a #${id} product`;<br>  }<br>  <br>  update(id: number, updateProductDto: UpdateProductDto) {<br>    return `This action updates a #${id} product`;<br>  }<br><br>  remove(id: number) {<br>    return `This action removes a #${id} product`;<br>  }<br>}</pre><p>To make this product useful, we shall add database access for the products, so that we can persist the data. NestJS integrates with <a href="https://typeorm.io/">TypeORM</a> to make database access a breeze. So first, we have to install the necessary components. In this tutorial, we are just going to save our data in <a href="https://mariadb.org/">MariaDB</a>.</p><pre>npm install --save @nestjs/typeorm typeorm mysql2</pre><p>We also need to install @nestjs/config, so that we can use the .env file, which we don’t commit, for our secrets.</p><pre>npm install --save @nestjs/config</pre><p>Then we need to add the config module and connection information to our AppModule.</p><pre>import * as process from &#39;process&#39;;<br><br>@Module({<br>  imports: [<br>    ConfigModule.forRoot({ isGlobal: true }),<br>    ProductsModule,<br>    TypeOrmModule.forRoot({<br>      type: &#39;mysql&#39;,<br>      host: process.env.MARIADB_HOST,<br>      port: parseInt(process.env.MARIADB_PORT, 10),<br>      username: process.env.MARIADB_USER,<br>      password: process.env.MARIADB_PASSWORD,<br>      database: process.env.MARIADB_DATABASE,<br>      entities: [Product],<br>      synchronize: true, // to be removed for production<br>    }),<br>  ],<br>  controllers: [AppController],<br>  providers: [AppService],<br>})</pre><p>Notice that there is an entities variable, which we populate it with an array containing just the Product. This sets up Product to be an entity to be managed by TypeORM.</p><p>The connection details are saved in a .env file in the root folder of the project as such.</p><pre>MARIADB_HOST=localhost<br>MARIADB_PORT=3306<br>MARIADB_USER=root<br>MARIADB_PASSWORD=password<br>MARIADB_DATABASE=nile</pre><blockquote>We shouldn’t commit this .env file to the repository to protect our secrets</blockquote><blockquote>Setting the synchonize variable to true helps during development to create the tables automatically when we run the application, and this variable should be removed during production, so that our tables and data will not be reset everytime we deploy it.</blockquote><p>Now we can populate our Product entity with the fields we need. First we annotate the Product class with the @Entity() decorator, and set up the columns with the @Column(). The id field is meant to be an autogenerated number, so it is annotated with the @PrimaryGeneratedColumn().</p><pre>@Entity()<br>export class Product {<br>  @PrimaryGeneratedColumn()<br>  id: number;<br><br>  @Column()<br>  name: string;<br><br>  @Column()<br>  description: string;<br><br>  @Column()<br>  pictureUrl: string;<br><br>  @Column()<br>  category: string;<br><br>  @Column(&#39;decimal&#39;, { scale: 2 })<br>  price: number;<br>}</pre><p>Then we update our ProductsModule to import TypeOrmModule.forFeature([Product]), so that we can inject the repository for Product in the classes in our module.</p><pre>@Module({<br>  imports: [TypeOrmModule.forFeature([Product])],<br>  controllers: [ProductsController],<br>  providers: [ProductsService],<br>})<br>export class ProductsModule {}</pre><p>So we add a constructor in our ProductsService to inject the product repository.</p><pre>constructor(<br>    @InjectRepository(Product) private productsRepository: Repository&lt;Product&gt;,<br>) {}</pre><p>Then we can update the other functions in the ProductsService to make use of the products repository.</p><pre>async create(createProductDto: CreateProductDto) {<br>  const product = this.productsRepository.create(createProductDto);<br>  return await this.productsRepository.save(product);<br>}<br><br>async findAll() {<br>  return await this.productsRepository.find();<br>}<br><br>async findOne(id: number) {<br>  return await this.productsRepository.findOneBy({ id });<br>}<br><br>async update(id: number, updateProductDto: UpdateProductDto) {<br>  await this.productsRepository.update({ id }, updateProductDto);<br>  return this.productsRepository.findOneBy({ id });<br>}<br><br>async remove(id: number) {<br>  return await this.productsRepository.delete({ id });<br>}</pre><p>Notice that in the create function, we are using the CreateProductDto, which should be a subset of the product entity. So, we should also update the class.</p><pre>export class CreateProductDto {<br>  name: string;<br>  description: string;<br>  pictureUrl: string;<br>  category: string;<br>  price: number;<br>}</pre><p>And thats it, we are done. Do remember to create the mariadb database in your local, and try out the apis. A full working copy of the above application is available on <a href="https://github.com/thecodinganalyst/nile">https://github.com/thecodinganalyst/nile</a>.</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de7ea1713afd" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/getting-started-with-nestjs-de7ea1713afd">Getting started with NestJS</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spring boot testing with MongoDB using TestContainers]]></title>
            <link>https://levelup.gitconnected.com/spring-boot-testing-with-mongodb-using-testcontainers-796320067c62?source=rss-b7d1517f4110------2</link>
            <guid isPermaLink="false">https://medium.com/p/796320067c62</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[spring-testing]]></category>
            <category><![CDATA[testcontainer]]></category>
            <category><![CDATA[mongodb]]></category>
            <dc:creator><![CDATA[Dennis]]></dc:creator>
            <pubDate>Fri, 26 May 2023 07:46:35 GMT</pubDate>
            <atom:updated>2023-05-28T16:22:19.851Z</atom:updated>
            <content:encoded><![CDATA[<p>When we need to test our spring boot application that is running MongoDB, it will by default connect to the MongoDB instance with the connection details in our application.properties. This might not be ideal, as every time we run the same tests, which might be inserting data, our collection grows if we don’t clean it up regularly. Or our test might just fail, because we are inserting duplicating data. A cleaner approach to testing with MongoDB is to start an instance of it in a docker container every time we run the tests. This way, the MongoDB instance is also destroyed after our tests, so that we don’t have to worry about accumulating data. It might seem a hassle to configure something like this, but actually junit-jupiter has an extension to do that automatically for us, called <a href="https://www.testcontainers.org/">TestContainers</a>.</p><p>To incorporate TestContainers to our spring boot application, we need to add the dependencies to our build.gradle.</p><pre>testImplementation &quot;org.testcontainers:testcontainers:1.18.1&quot;<br>testImplementation &quot;org.testcontainers:junit-jupiter:1.18.1&quot;<br>testImplementation &quot;org.testcontainers:mongodb:1.18.1&quot;</pre><p>I’m testing for MongoDB, so I have the org.testcontainers:mongodb, but if you are using other databases, you can find the list of supported containers and their dependency from under the Modules menu on <a href="https://www.testcontainers.org/">https://www.testcontainers.org/</a>.</p><p>And as mentioned above, we are running the database in containers, so naturally, we need to have docker installed and running. If you are not familiar with Docker, do checkout this article on <a href="https://www.thecodinganalyst.com/knowledgebase/Containerizing-with-Docker-explained/">Containerizing with Docker explained</a>.</p><p>For tests that you need to run testcontainers, simply annotate the class with @TestContainers. It will then scan all fields in the class that is annotated with the @Container and run the containers’ lifecycle methods, i.e. to start them.</p><p>The @Container will be the docker container of the MongoDB we want to start for running our tests.</p><pre>@Container<br>public static MongoDBContainer mongoDBContainer = new MongoDBContainer(&quot;mongo:latest&quot;).withExposedPorts(27017);</pre><p>The mongo:latest is the tag of the docker container to run. I’m just using the latest container here, but if a specific version of MongoDB is required, you can find the tags in the <a href="https://hub.docker.com/_/mongo/tags">list of official MongoDB tags on DockerHub</a>. The 27017 is the default port used by MongoDB.</p><p>Containers that are declared as static will be shared between the test methods, and started only once, which will last through all the test methods, then it will be shut down. Containers declared as instance fields will be started and stopped for every test method.</p><p>For connecting to the database in the container, we still need our usual database connection settings in our application.properties in the src/test/resources folder. But as the port exposed by our docker might not be the same every time, we need to make it a variable, and get the value from the @Container. Here, we specify the ${mongodb.container.port} as the variable.</p><pre>spring.data.mongodb.database=OAuth2Sample<br>spring.data.mongodb.port=${mongodb.container.port}<br>spring.data.mongodb.host=localhost<br>spring.data.mongodb.auto-index-creation=true</pre><p>Then we get the mapped port from the container and set it in the variable. And in order to reuse it, we make it a configuration class.</p><pre>@Configuration<br>@EnableMongoRepositories<br>public class MongoDBTestContainerConfig {<br>    @Container<br>    public static MongoDBContainer mongoDBContainer = new MongoDBContainer(&quot;mongo:latest&quot;)<br>            .withExposedPorts(27017);<br><br>    static {<br>        mongoDBContainer.start();<br>        var mappedPort = mongoDBContainer.getMappedPort(27017);<br>        System.setProperty(&quot;mongodb.container.port&quot;, String.valueOf(mappedPort));<br>    }<br>}</pre><p>And when we need to use it in our test class, we add this configuration class to the @ContextConfiguration annotation.</p><pre>@DataMongoTest<br>@Testcontainers<br>@ContextConfiguration(classes = MongoDBTestContainerConfig.class)<br>class AppUserRepositoryTest {<br><br>    @Autowired<br>    MongoTemplate mongoTemplate;<br><br>    @Autowired<br>    AppUserRepository appUserRepository;<br><br>    @Test<br>    void givenUserExists_whenFindByUsername_thenGetUser() {<br>        AppUser appUser = new AppUser(&quot;user1&quot;, &quot;password&quot;);<br>        mongoTemplate.save(appUser);<br><br>        Optional&lt;AppUser&gt; user = appUserRepository.findByUsername(&quot;user1&quot;);<br>        assertTrue(user.isPresent());<br>        assertThat(user.get().getUsername(), is(&quot;user1&quot;));<br>        assertThat(user.get().getPassword(), is(&quot;password&quot;));<br>    }<br><br>    @Test<br>    void givenNonExistingUser_whenFindByUsername_thenReturnNotPresent(){<br>        Optional&lt;AppUser&gt; user = appUserRepository.findByUsername(&quot;something&quot;);<br>        assertTrue(user.isEmpty());<br>    }<br>}</pre><p>A working example of the above code is available on <a href="https://github.com/thecodinganalyst/oauth2">https://github.com/thecodinganalyst/oauth2</a>. This is part of a project to demonstrate the <a href="https://www.thecodinganalyst.com/tutorial/OAuth2-login-with-spring-boot/">implementation of OpenID Connect / OAuth2 for login</a>, and <a href="https://www.thecodinganalyst.com/tutorial/how-to-create-a-user-in-spring-after-login-with-openid-connect/">creating of a user in MongoDB for users who logged in for the first time</a>.</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>💰 Free coding interview course ⇒ <a href="https://skilled.dev/?utm_source=luc&amp;utm_medium=article">View Course</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=796320067c62" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/spring-boot-testing-with-mongodb-using-testcontainers-796320067c62">Spring boot testing with MongoDB using TestContainers</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a new user after OpenID Connect login in Spring Boot]]></title>
            <link>https://towardsdev.com/how-to-create-a-new-user-after-openid-connect-login-in-spring-boot-9b8bd6fc47a6?source=rss-b7d1517f4110------2</link>
            <guid isPermaLink="false">https://medium.com/p/9b8bd6fc47a6</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[openid-connect]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[spring-security]]></category>
            <dc:creator><![CDATA[Dennis]]></dc:creator>
            <pubDate>Fri, 19 May 2023 08:10:46 GMT</pubDate>
            <atom:updated>2023-05-19T16:52:49.099Z</atom:updated>
            <content:encoded><![CDATA[<p>Following my <a href="https://www.thecodinganalyst.com/tutorial/OAuth2-login-with-spring-boot/">last article on creating OpenID Connect login with Spring Boot</a>, we shall now enhance the application to create a user in our MongoDB database for new user logins. I am using a local installation of <a href="https://www.mongodb.com/try/download/community">MongoDB Community Edition</a> for my database.</p><p>Firstly, we add the implementation &#39;org.springframework.boot:spring-boot-starter-data-mongodb&#39; dependency to our build.gradle file, so that we can use MongoDB in our spring boot project. Then we add the database configurations in our application.properties.</p><pre>spring.data.mongodb.database=OAuth2Sample<br>spring.data.mongodb.port=27017<br>spring.data.mongodb.host=localhost<br>spring.data.mongodb.auto-index-creation=true</pre><p>We need the auto-index-creation property so that the indexes created in our classes below can be created automatically. <a href="https://docs.spring.io/spring-data/mongodb/docs/current-SNAPSHOT/reference/html/#mapping.index-creation">https://docs.spring.io/spring-data/mongodb/docs/current-SNAPSHOT/reference/html/#mapping.index-creation</a></p><p>Next, we create our user class, which we shall name it AppUser. This class should implement the <a href="https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/core/userdetails/UserDetails.html">UserDetails</a> interface, as UserDetails is the representation of the user returned by Spring Security.</p><pre>@Document(collection = &quot;AppUser&quot;)<br>@NoArgsConstructor<br>@AllArgsConstructor<br>@Data<br>public class AppUser implements UserDetails {</pre><pre>    @Indexed(unique = true)<br>    String username;<br>    String password;<br>    boolean accountNonExpired;<br>    boolean accountNonLocked;<br>    boolean credentialsNonExpired;<br>    boolean enabled;<br>    Collection&lt;? extends GrantedAuthority&gt; grantedAuthorities;</pre><pre>    public AppUser(String username, String password){<br>        this.username = username;<br>        this.password = password;<br>        this.accountNonExpired = true;<br>        this.accountNonLocked = true;<br>        this.credentialsNonExpired = true;<br>        this.enabled = true;<br>    }</pre><pre>    @Override<br>    public Collection&lt;? extends GrantedAuthority&gt; getAuthorities() {<br>        return grantedAuthorities;<br>    }</pre><pre>    @Override<br>    public String getPassword() {<br>        return password;<br>    }</pre><pre>    @Override<br>    public String getUsername() {<br>        return username;<br>    }</pre><pre>    @Override<br>    public boolean isAccountNonExpired() {<br>        return accountNonExpired;<br>    }</pre><pre>    @Override<br>    public boolean isAccountNonLocked() {<br>        return accountNonLocked;<br>    }</pre><pre>    @Override<br>    public boolean isCredentialsNonExpired() {<br>        return credentialsNonExpired;<br>    }</pre><pre>    @Override<br>    public boolean isEnabled() {<br>        return enabled;<br>    }<br>}</pre><p>The @Document(collection = &quot;AppUser&quot;) annotation specifies that this is the entity class that represents a mongodb document, under the collection named AppUser. In terms of RDBMS, a collection is like a table, whereas a document is like a row in the table.</p><p>The @Indexed(unique = true) annotation over the username attribute specifies that the field should be a unique index. Mongodb will create a default _id as the primary key, and we are not going to overwrite it, so we just have to make the username unique.</p><p>Next, we can create the repository class for this entity.</p><pre>@Repository<br>public interface AppUserRepository extends MongoRepository&lt;AppUser, String&gt;{<br>    Optional&lt;AppUser&gt; findByUsername(String username);<br>}</pre><p>Next again, we shall create a class to implement UserDetailsService. This is the service used by spring security to retrieve the user. What we are doing here is to override the loadUserByUsername method, so that whenever a call to retrieve the user, it will get the user from our AppUserRepository.</p><pre>@Service<br>public class AppUserDetailsService implements UserDetailsService {<br>  AppUserRepository appUserRepository;<br><br>  public AppUserDetailsService(AppUserRepository appUserRepository){<br>    this.appUserRepository = appUserRepository;<br>  }<br>  <br>  @Override<br>  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {<br>    return appUserRepository.findByUsername(username)<br>                .orElseThrow(() -&gt; new UsernameNotFoundException(&quot;User &quot; + username + &quot; not found&quot;));<br>  }<br>}</pre><p>Lastly, in order to only add the user after it is authenticated, we shall add an EventListener to listen for the <a href="https://docs.spring.io/spring-security/site/docs/current/api/org/springframework/security/authentication/event/AuthenticationSuccessEvent.html">AuthenticationSuccessEvent</a>.</p><pre>@EventListener<br>public void onSuccess(AuthenticationSuccessEvent successEvent){<br>    Authentication authentication = successEvent.getAuthentication();<br>    <br>    OAuth2LoginAuthenticationToken oAuth2Token = getOAuth2Token(authentication);<br>    OAuth2User oAuth2User = getOAuth2User(authentication);<br>    <br>    if(oAuth2Token != null &amp;&amp; oAuth2User != null){<br>        String email = oAuth2User.getAttribute(&quot;email&quot;);<br>        if(email == null) return;<br>        try{<br>            userDetailsService.loadUserByUsername(email);<br>        }catch (UsernameNotFoundException exception){<br>            AppUser appUser = new AppUser(email, null);<br>            appUserRepository.save(appUser);<br>        }<br>    }<br>}<br><br>private OAuth2User getOAuth2User(Authentication authentication){<br>    return authentication.getPrincipal() instanceof OAuth2User user ?<br>            user :<br>            null;<br>}<br><br>private OAuth2LoginAuthenticationToken getOAuth2Token(Authentication authentication){<br>    return authentication instanceof OAuth2LoginAuthenticationToken token ?<br>            token :<br>            null;<br>}</pre><p>The event will contain the Authentication, and to determine if it is an OIDC or OAuth2 login, and not other authentication types like UsernamePassword, we only proceed if the Authentication is of type OAuth2LoginAuthenticationToken. The principal of the OAuth2LoginAuthenticationToken should also be of type OAuth2User.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/0*jEK3KOEVDuN8T-wG.png" /></figure><p>The OAuth2User will have a map of attributes, like name, first name, last name, email, etc. For our context, we just need to retrieve the email to be used as the username for our UserDetails. After we get the email, we can use the UserDetailsService to try and retrieve the user from our repository, and if the user is not found, then we create a new user and add it to our repository.</p><p>Lastly, to test the above implementation works, we shall add the unit tests as such.</p><pre>@ExtendWith(MockitoExtension.class)<br>class AuthenticationEventListenerTest {<br>    @InjectMocks<br>    AuthenticationEventListener authenticationEventListener;<br>    <br>    @Mock<br>    AuthenticationSuccessEvent successEvent;<br><br>    @Mock<br>    UserDetailsService userDetailsService;<br><br>    @Mock<br>    OAuth2LoginAuthenticationToken authentication;<br><br>    @Mock<br>    OAuth2User oAuth2User;<br><br>    @Mock<br>    UserDetails userDetails;<br><br>    @Mock<br>    AppUserRepository appUserRepository;<br><br>    @Test<br>    void givenUserDoesNotExist_whenLoginWithOAuth2_thenAddUser() {<br>        when(successEvent.getAuthentication()).thenReturn(authentication);<br>        when(authentication.getPrincipal()).thenReturn(oAuth2User);<br>        when(oAuth2User.getAttribute(&quot;email&quot;)).thenReturn(&quot;user@example.com&quot;);<br>        when(userDetailsService.loadUserByUsername(anyString())).thenThrow(new UsernameNotFoundException(&quot;&quot;));<br>        <br>        authenticationEventListener.onSuccess(successEvent);      <br>        <br>        verify(userDetailsService).loadUserByUsername(&quot;user@example.com&quot;);<br>        verify(appUserRepository).save(any(AppUser.class));<br>    }<br><br>    @Test<br>    void givenUserDoExist_whenLoginWithOAuth2_thenUserNotAdded() {    <br>        when(successEvent.getAuthentication()).thenReturn(authentication);<br>        when(authentication.getPrincipal()).thenReturn(oAuth2User);<br>        when(oAuth2User.getAttribute(&quot;email&quot;)).thenReturn(&quot;user@example.com&quot;);<br>        when(userDetailsService.loadUserByUsername(anyString())).thenReturn(userDetails);<br>        <br>        authenticationEventListener.onSuccess(successEvent);     <br>        <br>        verify(userDetailsService).loadUserByUsername(&quot;user@example.com&quot;);<br>        verify(appUserRepository, never()).save(any(AppUser.class));<br>    }<br>}</pre><p>A full working copy of the above implementation can be found on <a href="https://github.com/thecodinganalyst/oauth2">https://github.com/thecodinganalyst/oauth2</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9b8bd6fc47a6" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/how-to-create-a-new-user-after-openid-connect-login-in-spring-boot-9b8bd6fc47a6">How to create a new user after OpenID Connect login in Spring Boot</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OpenID Connect login with Spring Boot]]></title>
            <link>https://towardsdev.com/oidc-login-with-spring-boot-953cbd2cbd80?source=rss-b7d1517f4110------2</link>
            <guid isPermaLink="false">https://medium.com/p/953cbd2cbd80</guid>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[oauth2]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[spring-security]]></category>
            <category><![CDATA[openid-connect]]></category>
            <dc:creator><![CDATA[Dennis]]></dc:creator>
            <pubDate>Thu, 18 May 2023 08:08:16 GMT</pubDate>
            <atom:updated>2023-05-19T02:38:34.542Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://auth0.com/intro-to-iam/what-is-openid-connect-oidc">OpenID Connect (OIDC)</a> is an identity authentication protocol, using the mechanism of <a href="https://auth0.com/intro-to-iam/what-is-oauth-2">OAuth2</a>, to allow applications to delegate their login function to identity providers like Google and Facebook. By using OIDC, users can use their existing credentials (like their gmail or facebook account) to login to applications, without the need to create and remember a new password for the application.</p><p>With spring boot, we can easily incorporate OIDC login to our applications without much hassle, even the login page is created for us automatically. We can use it on top of the normal form login too. This article will demonstrate how to allow users to login with google and facebook, and the next article will discuss on how to add the user to the applications user repository if it is the first time login, so that whatever settings for the user can be saved and retrieved for future logins.</p><p>To start, make sure the required dependencies are added to the build.gradle.</p><pre>dependencies {<br>    implementation &#39;org.springframework.boot:spring-boot-starter-oauth2-client&#39;<br>    implementation &#39;org.springframework.boot:spring-boot-starter-web&#39;<br>    testImplementation &#39;org.springframework.boot:spring-boot-starter-test&#39;<br>}</pre><p>The main dependency required for the OIDC login is the <a href="https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-oauth2-client">spring-boot-starter-oauth2-client</a>, and I have the spring-boot-starter-web for the REST controller.</p><p>I have a very basic REST controller to display a “Hello World” message in the root site.</p><pre>@RestController()<br>public class PageController {<br>    @GetMapping(&quot;/&quot;)<br>    public String home(){<br>        return &quot;Hello World&quot;;<br>    }<br>}</pre><p>And I will set up the spring security configurations as below.</p><pre>@Configuration<br>public class SecurityConfig {</pre><pre>    @Bean<br>    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{<br>        http.authorizeHttpRequests()<br>                .anyRequest()<br>                .authenticated()<br>                .and()<br>                .oauth2Login()<br>                .and()<br>                .formLogin()<br>                .and()<br>                .logout();<br>        return http.build();<br>    }</pre><pre>    @Bean<br>    public PasswordEncoder passwordEncoder(){<br>        return new BCryptPasswordEncoder();<br>    }</pre><pre>}</pre><p>The anyRequest().authenticated() ensures that any requests to any of the pages in our application will require the user to be logged in. So when a user tries to access any pages in the application (which in this case is http://localhost:8080/), will be redirected to a login page. The oauth2Login() gets spring boot to supply the oauth2 login options in the login form. We’ve also added formLogin() to allow the typical username and password login, for more details on how to configure the formLogin(), do visit <a href="https://www.thecodinganalyst.com/tutorial/how-to-configure-access-management-in-spring-security/">my previous article on username and password authentication</a>.</p><h3>Google Login Configuration</h3><p>To allow login with gmail, we need a google cloud account. So if you do not already have a google cloud account, you need to create one at <a href="https://cloud.google.com/">https://cloud.google.com/</a>. After you created an account, you need to create a project for your application. Then make sure you have your project selected, navigate to API &amp; Services &gt; Credentials.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/0*Fc-QbM6qaWkxtk_0.png" /></figure><p>Then click on the + CREATE CREDENTIALS and select to create a OAUTH CLIENT ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*9VfXhU9qIo4Hy4iL.png" /></figure><p>Choose Web Application for the application type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*jai5sZorXOqMxS7N.png" /></figure><p>The Authorized Javascript origins specifies the url where your application should be called from, so that the calls from your application will not be blocked. As we are just running from our localhost, we just put http://localhost:8080. The Authorized redirect URIs is the URI which google should be redirecting your user to, after the user was successfully authenticated by google. The <a href="https://docs.spring.io/spring-security/reference/servlet/oauth2/login/core.html#oauth2login-sample-redirect-uri">default redirect URI template in Spring</a> is {baseURL}/login/oauth2/code/{registrationId}. So we shall enter <a href="http://localhost:8080/login/oauth2/code/google.">http://localhost:8080/login/oauth2/code/google.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/518/0*-GuKxNGstP0WqJN_.png" /></figure><p>You should see the Client ID and Client Secrets at the right hand side of the same page. This is the credentials for your application to use the google login. Take note it and save it somewhere as we are going to need it in our application.properties later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/0*kRQ0FQcBNdlx4EMC.png" /></figure><h3>Facebook Login Configuration</h3><p>Likewise for facebook, we also need a facebook developer account. So head over to <a href="https://developers.facebook.com/">https://developers.facebook.com/</a> and create an account if you don’t have one. Then create an App in the developer portal, selecting Set up Facebook Login in the option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/0*AT3zxj8_RIdKqGiL.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/0*bv_Ja1xOOrnMfzTY.png" /></figure><p>After the application is created, select Products from the menu, and click the Configure button for the Facebook Login, then select Settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vsYBiXd9BQBF7zM0.png" /></figure><p>As the purpose of setting this up is to enable users to login via OIDC, which is based on OAuth2, we need to enable the Client OAuth login and Web OAuth login.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/967/0*rUr78COsKhRjw30i.png" /></figure><p>Lastly, select Settings from the menu, and choose Basic. Copy the App ID and App Secret.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*DHd78P86gKLwf38u.png" /></figure><h3>Spring Application Configuration<a href="https://www.thecodinganalyst.com/tutorial/OAuth2-login-with-spring-boot/#spring-application-configuration">Permalink</a></h3><p>By right, when we configure oAuth2, we need to configure many things like the authorizationUri, tokenUri, userInfoUri, etc. However, as these uris are unlikely to change often, <a href="https://github.com/spring-projects/spring-security/blob/main/config/src/main/java/org/springframework/security/config/oauth2/client/CommonOAuth2Provider.java">spring boot actually provides configurations for Google, Github, Okta, and Facebook out of the box</a> with <a href="https://github.com/spring-projects/spring-security/blob/main/config/src/main/java/org/springframework/security/config/oauth2/client/CommonOAuth2Provider.java">CommonOAuth2Provider</a>. So if you are using any of the above providers, you only need to specify the client-id and client-secret, as it is unique for every application.</p><p>So we need to add the following to our application.properties file, replacing the values with the respective client id and client secrets saved earlier.</p><pre>spring.security.oauth2.client.registration.google.client-id=ENTER_YOUR_GOOGLE_CLIENT_ID<br>spring.security.oauth2.client.registration.google.client-secret=ENTER_YOUR_GOOGLE_CLIENT_SECRET<br>spring.security.oauth2.client.registration.facebook.client-id=ENTER_YOUR_FACEBOOK_CLIENT_ID<br>spring.security.oauth2.client.registration.facebook.client-secret=ENTER_YOUR_FACEBOOK_CLIENT_SECRET</pre><p>That was almost correct, except no, we can’t commit our secrets to a repository. So instead, we should do this.</p><pre>spring.security.oauth2.client.registration.google.client-id=${GOOGLE_OAUTH2_CLIENT_ID}<br>spring.security.oauth2.client.registration.google.client-secret=${GOOGLE_OAUTH2_CLIENT_SECRET}<br>spring.security.oauth2.client.registration.facebook.client-id=${FACEBOOK_OAUTH2_CLIENT_ID}<br>spring.security.oauth2.client.registration.facebook.client-secret=${FACEBOOK_OAUTH2_CLIENT_SECRET}</pre><p>So, instead of saving our secrets publicly, we use environment variables. But to run it locally, we should save the environment variables in our configuration. If you are using IntelliJ, right click the bootRun in our gradle window on our IDE (IntelliJ), and select Modify Run Configuration.... Then add the above variables as environment variables. Afterwards, when you run bootRun again to start the application, the environment variables will be automatically added to the command which our IDE use to start our application.</p><p>To run it on our CI/CD environment on Github, go to your project, click Settings from the menu, then in the Secrets and variables section, under Action, create either the Environment Serects or Repository secrets.</p><h3>Login Page</h3><p>Now, when we bootRun the application, and go to our browser, navigating to http://localhost:8080, we will be automatically redirected to a login page provided by Spring Boot, with the options to login with OAuth2 by either Google or Facebook.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/604/0*E0zmocyRyF1NCLjV.png" /></figure><p>A full working copy of the code above is available at <a href="https://github.com/thecodinganalyst/oauth2">https://github.com/thecodinganalyst/oauth2</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=953cbd2cbd80" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/oidc-login-with-spring-boot-953cbd2cbd80">OpenID Connect login with Spring Boot</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>