<?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 Giacomo Mariani on Medium]]></title>
        <description><![CDATA[Stories by Giacomo Mariani on Medium]]></description>
        <link>https://medium.com/@giacomo-mariani?source=rss-52173d834c78------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NBNa-In0_zg_iXIQGx5_mA.jpeg</url>
            <title>Stories by Giacomo Mariani on Medium</title>
            <link>https://medium.com/@giacomo-mariani?source=rss-52173d834c78------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 10:15:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@giacomo-mariani/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[Why the Professional Scrum Developer (PSD) Certification is Worth it]]></title>
            <link>https://levelup.gitconnected.com/is-the-professional-scrum-developer-psd-certification-worth-it-19c58d0747af?source=rss-52173d834c78------2</link>
            <guid isPermaLink="false">https://medium.com/p/19c58d0747af</guid>
            <category><![CDATA[scrum]]></category>
            <category><![CDATA[professional-scrum]]></category>
            <category><![CDATA[scrum-developer]]></category>
            <category><![CDATA[certified-scrum-developer]]></category>
            <dc:creator><![CDATA[Giacomo Mariani]]></dc:creator>
            <pubDate>Wed, 14 Aug 2024 21:18:52 GMT</pubDate>
            <atom:updated>2024-10-17T04:26:35.414Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*i6mqTHKhpp-e_PY_l4HTrw.png" /></figure><p>In this post I share my thoughts on pursuing the <a href="https://www.scrum.org/assessments/professional-scrum-developer-certification">Professional Scrum Developer (PSD)</a> certification from <a href="https://www.scrum.org/">Scrum.org</a>.</p><p>To achieve the certification I studied the resources from the <a href="https://www.scrum.org/pathway/software-developer-learning-path/">Software Developer Learning Path</a>, which includes a lot of useful posts, videos and books.</p><p>When discussing the usefulness of a certification, I like to consider two aspects: the learning journey, and the concrete advantage given by the certification on the job market.</p><p><strong>The Learning Journey<br></strong>The learning journey has been eye-opening. I have not taken any Professional Scrum Developer class, I just read and watched all the resources from the learning path, so I am only presenting my experience following the <a href="https://www.scrum.org/pathway/software-developer-learning-path/">Software Developer Learning Path</a>, not the class. I had worked in Scrum teams for about two years before starting studying for the PSD certification. Before that, I had only studied Scrum superficially and without commitment. While reading the articles and books from the learning path, I started to reflect on my own experiences, seeing how I could improve to become a better developer and team member. The Scrum values of focus, respect, commitment, courage, and openness, as well as the agile manifesto principles became more than just words, as I started reflecting on my actions and attitude through them. Finishing the learning path took me five months, a time that has had a profound impact on my way of thinking, and helped me internalize the Scrum, DevOps, and agile values overall. The value of the PSD certification is that it gave me a goal and the focus to follow the learning path until the end.</p><p><strong>Advantage on the Job Market<br></strong>I haven’t seen any job announcement requiring a PSD certification or similar, but I have seen many mentioning working in a Scrum team. While experience counts more than certifications, I don’t think the two are mutually exclusive. I believe a certification can further show your motivation and interest in a topic, and the willingness to invest time and money to improve. Many, including myself, have years of experience in something, but still know it on a superficial way. With a certification you can at least show that you put some effort to get deeper. I believe experience counts, until a certain point, after which it is not a guarantee of knowledge or wisdom. Instead, you must actively desire growth, and pursuing certifications is a way to do it. Personally, if one day I will have to hire someone for a software developer position, I will consider any PSD or similar certification on the CV a big advantage, even over years of experience.</p><p><strong>Final Words</strong></p><p>Finally a consideration on the nature of the Professional Scrum Developer certification. Compared to other certifications for software developers, the PSD is less technical and more about having internalized the Scrum, DevOps, and in general agile culture, values, and attitude. I believe this type or knowledge, or wisdom, is difficult to learn only through work experience. Instead, you must be open to the learning journey, willing to change as a person, accept guidance, and admit mistakes. Voluntarily undertaking the PSD learning journey sets you in that context, and the certification at the end is the prize and proof of your undertaking.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19c58d0747af" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/is-the-professional-scrum-developer-psd-certification-worth-it-19c58d0747af">Why the Professional Scrum Developer (PSD) Certification is Worth it</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 Batch 5 examples with Tasklet and Chunk processing]]></title>
            <link>https://levelup.gitconnected.com/spring-batch-5-examples-tasklet-and-chunk-processing-ba4860618171?source=rss-52173d834c78------2</link>
            <guid isPermaLink="false">https://medium.com/p/ba4860618171</guid>
            <category><![CDATA[java-spring-developer]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-batch]]></category>
            <dc:creator><![CDATA[Giacomo Mariani]]></dc:creator>
            <pubDate>Fri, 20 Oct 2023 20:02:01 GMT</pubDate>
            <atom:updated>2023-10-29T16:24:21.025Z</atom:updated>
            <content:encoded><![CDATA[<p>Spring Batch 5 has brought relevant changes compared to previous versions. If in 2023 you are trying to implement a Spring Batch application, it is likely you are following examples based on previous Spring Batch versions, which do not work with version 5. Here I share a simple Hello World example, and a bit more advanced example to help you going with Spring Batch 5.</p><p>The project dependencies:</p><pre><br> &lt;dependencies&gt;<br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-batch&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-jdbc&lt;/artifactId&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;com.h2database&lt;/groupId&gt;<br>   &lt;artifactId&gt;h2&lt;/artifactId&gt;<br>   &lt;scope&gt;runtime&lt;/scope&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.postgresql&lt;/groupId&gt;<br>   &lt;artifactId&gt;postgresql&lt;/artifactId&gt;<br>   &lt;version&gt;42.6.0&lt;/version&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-boot-starter-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br><br>  &lt;dependency&gt;<br>   &lt;groupId&gt;org.springframework.batch&lt;/groupId&gt;<br>   &lt;artifactId&gt;spring-batch-test&lt;/artifactId&gt;<br>   &lt;scope&gt;test&lt;/scope&gt;<br>  &lt;/dependency&gt;<br> &lt;/dependencies&gt;</pre><h3>Hello World Example</h3><p>The ExampleApplication.java class:</p><pre>@SpringBootApplication<br>public class ExampleApplication {<br><br> @Autowired<br> private DataSource batchDataSource;<br><br> @Bean<br> public Step step(JobRepository jobRepository) {<br>  StepBuilder stepBuilderOne = new StepBuilder(&quot;step1&quot;, jobRepository);<br>   return stepBuilderOne.tasklet(helloWorldTasklet(), transactionManager())<br>    .build();<br> }<br><br> @Bean<br> public Job job(JobRepository jobRepository) {<br>  return new JobBuilder(&quot;job&quot;, jobRepository)<br>   .start(step(jobRepository))<br>   .build();<br> }<br><br> @Bean<br> public CompletionPolicy completionPolicy() {<br>  CompositeCompletionPolicy policy =<br>   new CompositeCompletionPolicy();<br>  policy.setPolicies(<br>   new CompletionPolicy[] {<br>    new TimeoutTerminationPolicy(3),<br>    new SimpleCompletionPolicy(1000)});<br>  return policy;<br> }<br><br> @Bean<br> public DataSourceTransactionManager transactionManager() {<br>  return new DataSourceTransactionManager(batchDataSource);<br> }<br><br>  @Bean<br>  public Tasklet helloWorldTasklet() {<br>    return (StepContribution contribution, ChunkContext chunkContext) -&gt; {<br>      System.out.println(&quot;Hello, World!&quot;);<br>      return RepeatStatus.FINISHED;<br>    };<br>  }<br><br> public static void main(String[] args) {<br>  SpringApplication.run(ExampleApplication.class, args);<br> }<br><br>}</pre><h3>Advanced Example</h3><p>The next example is a bit more complex. The job takes a chuck-based step.</p><blockquote>The difference between a Tasklet vs. Chunk processing, is that in Tasklet-based processing we a Tasklet executes a block of code within the same transaction context, until it returns RepatStatus.FINISHED. In Chunk-based processing we usually process data in chunks, and each chunk executes within its own transaction context, which allows to keep processing even if a transaction encounters an error.</blockquote><p>Chunk-based steps have at least two components, an ItemReader and an ItemWriter, plus an optional ItemProcessor. In this example the ItemReader is a JdbcCursorItemReader that reads from a database, and the ItemWriter is a FlatFileItemWriter, that writes to a file. In the example there is no ItemProcessor.</p><p>Here is the simplified project folder structure:</p><pre>ExampleApplication.java<br>/configuarion<br> - BatchConfiguration.java<br> - DbRowVerificationSkipper.java<br>/jobs<br> - DbReader.java<br> - JobConfiguration.java<br> - MyFileWriter.java<br>/listners<br> - DbReaderListener.java<br>/model<br> /mappers<br>  - MessageRowMapper.java<br> - Message.java</pre><p>The ExampleApplication.java now is simple, because we moved the logic to other classes:</p><pre>@SpringBootApplication<br>public class ExampleApplication {<br><br> public static void main(String[] args) {<br>  SpringApplication.run(ExampleApplication.class, args);<br> }<br><br>}</pre><p>The job and the step (we have just one job and one step here) are defined in /jobs/JobConfiguration.java. The job has one step, and the step reads from a database, then writes to a file. The step also has some basic logic related to error handling:</p><pre>@Configuration<br>public class JobConfiguration {<br><br>  @Autowired<br>  private DataSource batchDataSource;<br>  @Autowired<br>  private JdbcCursorItemReader messageItemReader;<br>  @Autowired<br>  private DbReaderListener DbReaderListener;<br>  @Autowired<br>  private ItemWriter myFlatFileItemWriter;<br><br>  @Bean<br>  public Step step(JobRepository jobRepository) {<br>    StepBuilder stepBuilderOne = new StepBuilder(&quot;step1&quot;, jobRepository);<br>  return stepBuilderOne.chunk(completionPolicy(), batchTransactionManager(batchDataSource))<br>      .reader(messageItemReader)<br>      .writer(myFlatFileItemWriter)<br>      .faultTolerant()<br>      .skipPolicy(new DbRowVerificationSkipper())<br>      .listener(DbReaderListener)<br>      .build();<br>  }<br><br>  @Bean<br>  public Job job(JobRepository jobRepository) {<br>    return new JobBuilder(&quot;job&quot;, jobRepository)<br>      .incrementer(new RunIdIncrementer())<br>      .start(step(jobRepository))<br>      .build();<br>  }<br><br>  @Bean<br>  public CompletionPolicy completionPolicy() {<br>    CompositeCompletionPolicy policy =<br>      new CompositeCompletionPolicy();<br>    policy.setPolicies(<br>      new CompletionPolicy[] {<br>        new TimeoutTerminationPolicy(1000),<br>        new SimpleCompletionPolicy(10)});<br>    return policy;<br>  }<br><br>  @Bean<br>  public DataSourceTransactionManager batchTransactionManager(DataSource dataSource) {<br>    return new DataSourceTransactionManager(dataSource);<br>  }<br><br>}</pre><p>What happens in the step() method above?</p><ul><li>We create a StepBuilder with a step name and the JobRepository passed by Spring Batch through the job() method</li><li>We return a Step with completion policy, Spring Batch default in-memory datasource, the db reader, the skip policy, and a listener to log errors.</li></ul><p>The completionPolicy <a href="https://docs.spring.io/spring-batch/docs/current/api/org/springframework/batch/repeat/policy/TimeoutTerminationPolicy.html">sets the timeout in milliseconds before gracefully exiting if the latest result does not come in</a>, and sets the chunk size to 10, <a href="https://docs.spring.io/spring-batch/docs/current/api/org/springframework/batch/repeat/policy/SimpleCompletionPolicy.html#DEFAULT_CHUNK_SIZE">which would be the number of items to read in a single chunk</a>. In our case an item would be a table row from the database.</p><p>The batchTransactionManager is creating the DataSourceTransactionManager using the Spring Batch default in-memory db, which contains the Spring Batch <a href="https://docs.spring.io/spring-batch/docs/current/reference/html/schema-appendix.html">Metadata-Schema</a>.</p><h4>The database reader</h4><p>This is the database reader used by the step:</p><pre>@Component<br>public class DbReader {<br><br>  @Autowired<br>  @Bean<br>  @StepScope<br>  public JdbcCursorItemReader&lt;Message&gt; messageItemReader( DataSource dataSource) {<br>    DriverManagerDataSource myDbDataSource = new DriverManagerDataSource();<br>    myDbDataSource.setDriverClassName(&quot;org.postgresql.Driver&quot;);<br>    myDbDataSource.setUrl(&quot;jdbc:postgresql://localhost:5434/my_database&quot;);<br>    myDbDataSource.setUsername(&quot;username_to_read_from_db&quot;);<br>    myDbDataSource.setPassword(&quot;username_password&quot;);<br><br>    return new JdbcCursorItemReaderBuilder&lt;Message&gt;()<br>      .name(&quot;messageItemReader&quot;)<br>      .dataSource(myDbDataSource)<br>      .sql(&quot;SELECT * FROM my_schema.message&quot;)<br>      .rowMapper(new MessageRowMapper())<br>      .build();<br>  }<br><br>}</pre><p>The reader gets a DataSource as parameter, but since it would be the same default in-memory database used by the batchTransactionManager, it instead creates a new DataSource to read from the database where the table we want to read (called message) is located. The MessageRowMapper is a class to map the database entries to a Message record:</p><pre>public class MessageRowMapper implements RowMapper&lt;Message&gt; {<br><br>  @Override<br>  public Message mapRow(ResultSet resultSet, int rowNumber) throws SQLException {<br><br>    Message message = new Message(<br>      resultSet.getLong(&quot;message_id&quot;),<br>      resultSet.getInt(&quot;recipient_id&quot;),<br>      resultSet.getString(&quot;subject&quot;),<br>      resultSet.getString(&quot;content&quot;),<br>      MessageStatus.valueOf(resultSet.getString(&quot;status&quot;)),<br>    );<br>    return message;<br>  }<br>}</pre><pre>public record Message(<br>  long id,<br>  int recipientId,<br>  String subject,<br>  String content,<br>  MessageStatus status,<br>) {<br>}</pre><h4>The file writer</h4><p>This is the file write used by the step:</p><pre>@Component<br>public class MyFileWriter {<br><br>  @Autowired<br>  @Bean<br>  @StepScope<br>  public FlatFileItemWriter&lt;Message&gt; myFlatFileItemWriter(Resource myFileResource) {<br>    return new FlatFileItemWriterBuilder&lt;Message&gt;()<br>      .name(&quot;myFileWriter&quot;)<br>      .resource((WritableResource) myFileResource)<br>      .formatted()<br>      .format(&quot;%s;%s;%s;%s;%s&quot;)<br>      .names( new String[] {<br>        &quot;id&quot;,<br>        &quot;recipientId&quot;,<br>        &quot;subject&quot;,<br>        &quot;content&quot;,<br>        &quot;status&quot;,<br>      })<br>      .build();<br>  }<br><br>}</pre><p>The myFlatItemWriter takes a file resource we defined separately in the configuration/BatchConfiguration.java class, and just writes what was read from the database to that file.</p><h4>Configurations and error handling</h4><p>This is the configuration/BatchConfiguration.java where we just define the file to write to:</p><pre>@Configuration<br>public class BatchConfiguration {<br><br>    @Bean<br>    public Resource myFileResource() {<br>        return new FileSystemResource(&quot;./messages_from_db&quot;);<br>    }<br><br>}</pre><p>This the configuration/DbRowVerificationSipper.java is used in the step() method to pass the skip policy. It basically define what and how many errors to tolerate before skipping the step:</p><pre>public class DbRowVerificationSkipper implements SkipPolicy {<br>  @Override<br>  public boolean shouldSkip(Throwable t, long skipCount) throws SkipLimitExceededException {<br>    //TODO: this is just an example, find a proper skip policy<br>    if(t instanceof SQLException) {<br>      return false;<br>    } else if(skipCount &lt;= 10) {<br>      return true;<br>    } else {<br>      return false;<br>    }<br>  }<br><br>}</pre><p>The listeners/DbReaderListener.java is used in the step() to just listen for errors and log them:</p><pre>@Component<br>public class DbReaderListener {<br>  private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());<br><br>  @OnReadError<br>  public void onReadError(Exception e) {<br>    log.error(e.getMessage());<br>  }<br><br>}</pre><p>This is quite a simple job, but I think it can be useful to get started with Spring Batch 5 jobs, and build on it. For me it was quite a challenge to get even this basic job working with Batch 5, as most tutorials, books, and documentation were based on previous Batch versions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ba4860618171" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/spring-batch-5-examples-tasklet-and-chunk-processing-ba4860618171">Spring Batch 5 examples with Tasklet and Chunk processing</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[AuthGuard & AuthGuard unit test with Angular 16]]></title>
            <link>https://levelup.gitconnected.com/authguard-authguard-unit-test-with-angular-16-c46738532cdd?source=rss-52173d834c78------2</link>
            <guid isPermaLink="false">https://medium.com/p/c46738532cdd</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Giacomo Mariani]]></dc:creator>
            <pubDate>Thu, 07 Sep 2023 20:36:09 GMT</pubDate>
            <atom:updated>2023-10-29T16:24:06.637Z</atom:updated>
            <content:encoded><![CDATA[<p>This tutorial demonstrates how I have implemented an <strong>auth guard </strong>and the <strong>unit tests for the auth guard</strong> in Angular 16. The <strong>auth</strong> <strong>guard</strong> is used to protect the routes that require the user to be logged in. Here is <strong>the implementation of the</strong> <strong><em>AuthGuard</em></strong>:</p><pre>import {inject} from &#39;@angular/core&#39;;<br>import {<br>  ActivatedRouteSnapshot,<br>  RouterStateSnapshot,<br>  Router,<br>  CanActivateFn, ActivatedRoute, mapToCanActivate<br>} from &#39;@angular/router&#39;;<br>import {catchError, of} from &#39;rxjs&#39;;<br>import { map } from &#39;rxjs/operators&#39;;<br>import { LoginService } from &#39;../services/login.service&#39;;<br>import {Constants} from &quot;../../constants&quot;;<br><br>export const AuthGuard: CanActivateFn = (route: ActivatedRouteSnapshot, state: RouterStateSnapshot) =&gt; {<br>  const loginService = inject(LoginService);<br>  const router = inject(Router);<br><br>  return loginService.isLoggedIn().pipe(<br>    map(loggedIn =&gt; loggedIn ? true : router.createUrlTree([router.parseUrl(Constants.LOGIN_ROUTE)], {<br>      queryParams: { loggedOut: true, origUrl: state.url }<br>    } )),<br>    catchError((err) =&gt; {<br>      router.navigate([Constants.LOGIN_ROUTE], {<br>        queryParams: { loggedOut: true, origUrl: state.url }<br>      });<br>      return of(false);<br>    })<br>  )<br>}</pre><p>As you can see the <em>AuthGuard</em> is a function of type <em>CanActivateFn</em>, which takes a route of type <em>ActivatedRouteSnapshot</em> and a state of type <em>RouterStateSnapshot</em>. The <em>AuthGuard</em> does the following:</p><ul><li>Injects the <em>LoginService</em> and the <em>Router</em></li><li>Calls the <em>LoginService.isLoggedIn</em> to verify if the user is logged in</li><li>If the <em>LoginService.isLoggedIn</em> returns true, AuthGuard returns true</li><li>If the <em>LoginService.isLoggedIn</em> returns <em>false</em>, AuthGuard calls <em>Router.CreateUrlTree</em> to return an URL of type <em>UrlTree</em> containing the login route with appended two url parameters: (1) <em>loggedOut</em>, to inform the login page that the user authentication state has already been checked and it is logged out, and (2) <em>origUrl</em>, which contains the route the user was trying to access, so that the login page can redirect the user to that route after successful login</li><li>If during one of the steps above occurs an error, it is caught and the code behaves as if the <em>LoginService.isLoggedIn</em> had returned <em>false</em></li></ul><p>Here is an example of how the <em>AuthGuard</em> is used in the <em>Router</em>:</p><pre>const routes: Routes = [<br>  { path: &#39;&#39;, redirectTo: `/${Constants.LOGIN_ROUTE}`, pathMatch: &#39;full&#39; },<br>  { path: Constants.LOGIN_ROUTE, component: AppLoginComponent, canActivate: [LoginGuard] },<br>  { path: Constants.LOGOUT_ROUTE, component: AppLoginComponent },<br>  { path: Constants.DATASETS_ROUTE, component: DatasetsComponent, canActivate: [AuthGuard] },<br>  { path: &#39;**&#39;, component: PageNotFoundComponent}<br>];</pre><p>As you can see, we also have a <em>LoginGuard</em>, that is used to skip the login page for users that are already logged in. I will not explain how I implemented the <em>LoginGuard</em>, because I think you will be able to implement one by yourself after reading this tutorial.</p><h3>The unit tests for AuthGuard</h3><p>When first trying to write the unit tests, I got the error:</p><p><em>NG0203: `inject()` must be called from an injection context such as a constructor, a factory function, a field initializer, or a function used with `runInInjectionContext`</em></p><p>As you can see here <a href="https://angular.io/errors/NG0203">https://angular.io/errors/NG0203</a>, the solution is to use <a href="https://angular.io/api/core/runInInjectionContext"><em>runInInjectionContext</em></a>. I came across many other challenges while trying to get the AuthGuard wokring with <em>runInInjectionContext</em>, but at the end I got the unit tests working and here is how they look:</p><pre>import {fakeAsync, TestBed, tick} from &#39;@angular/core/testing&#39;;<br>import {<br>  ActivatedRouteSnapshot, CanActivateFn,<br>  Router,<br>  RouterStateSnapshot,<br>  UrlSegment,<br>  UrlSegmentGroup,<br>  UrlTree<br>} from &#39;@angular/router&#39;;<br>import {Observable, of, throwError} from &#39;rxjs&#39;;<br>import {AuthGuard} from &quot;./AuthGuard&quot;;<br>import {LoginService} from &quot;../services/login.service&quot;;<br><br>describe(&#39;AuthGuard&#39;, () =&gt; {<br>  let mockLoginService: jasmine.SpyObj&lt;LoginService&gt;<br>  let mockRouter: jasmine.SpyObj&lt;Router&gt;<br>  const urlPath = &#39;/dataset&#39;<br>  const expectedUrl = &#39;login&#39;;<br>  const expectedQueryParams = { loggedOut: true, origUrl: urlPath };<br><br>  beforeEach(async () =&gt; {<br>    mockLoginService = jasmine.createSpyObj(AuthGuard, [&#39;isLoggedIn&#39;])<br>    mockRouter = jasmine.createSpyObj(AuthGuard, [&#39;navigate&#39;, &#39;createUrlTree&#39;, &#39;parseUrl&#39;])<br>    mockRouter.parseUrl.and.callFake((url: string) =&gt; {<br>      const urlTree = new UrlTree()<br>      const urlSegment = new UrlSegment( url, {})<br>      urlTree.root = new UrlSegmentGroup( [urlSegment], {})<br>      return urlTree<br>    });<br>    await TestBed.configureTestingModule( {<br>      providers: [<br>        {<br>          provide: Router,<br>          useValue: mockRouter<br>        },<br>        {<br>          provide: LoginService,<br>          useValue: mockLoginService<br>        },<br>      ]<br>    })<br>  })<br><br>  it(&#39;should return false if the user is not logged in &#39;, fakeAsync(async () =&gt; {<br>    mockIsLoggedInFalse()<br>    const authenticated = await runAuthGuardWithContext(getAuthGuardWithDummyUrl(urlPath))<br>    expect(authenticated).toBeFalsy()<br>  }))<br><br>  it(&#39;should return true if the user is logged in &#39;, fakeAsync(async () =&gt; {<br>    mockIsLoggedInTrue()<br>    const authenticated = await runAuthGuardWithContext(getAuthGuardWithDummyUrl(urlPath))<br>    expect(authenticated).toBeTruthy()<br>  }))<br><br>  it(&#39;should redirect to login with originalUrl and loggedOut url parameters if the user is not logged in &#39;, fakeAsync(async () =&gt; {<br>    mockIsLoggedInFalse()<br>    const authenticated = await runAuthGuardWithContext(getAuthGuardWithDummyUrl(urlPath))<br>    expect(mockRouter.createUrlTree).toHaveBeenCalledOnceWith([mockRouter.parseUrl(expectedUrl)],  { queryParams: expectedQueryParams })<br>    expect(authenticated).toBeFalsy()<br>  }))<br><br>  it(&#39;should redirect to login with originalUrl and loggedOut url parameters if catches an error &#39;, fakeAsync(async () =&gt; {<br>    mockLoginService.isLoggedIn.and.returnValue(throwError(() =&gt;&#39;Authentication error&#39;));<br>    const authenticated = await runAuthGuardWithContext(getAuthGuardWithDummyUrl(urlPath))<br>    expect(mockRouter.navigate).toHaveBeenCalledOnceWith([expectedUrl],  { queryParams: expectedQueryParams })<br>    expect(authenticated).toBeFalsy()<br>  }))<br><br>  function getAuthGuardWithDummyUrl(urlPath: string): () =&gt; boolean | UrlTree | Promise&lt;boolean | UrlTree&gt; | Observable&lt;boolean | UrlTree&gt; {<br>    const dummyRoute = new ActivatedRouteSnapshot( )<br>    dummyRoute.url = [ new UrlSegment(urlPath, {}) ]<br>    const dummyState: RouterStateSnapshot = { url: urlPath, root:  new ActivatedRouteSnapshot() }<br>    return () =&gt; AuthGuard(dummyRoute, dummyState)<br>  }<br><br>  async function runAuthGuardWithContext(authGuard: () =&gt; boolean | UrlTree | Promise&lt;boolean | UrlTree&gt; | Observable&lt;boolean | UrlTree&gt;): Promise&lt;boolean | UrlTree&gt; {<br>    const result = TestBed.runInInjectionContext(authGuard)<br>    const authenticated = result instanceof Observable ? await handleObservableResult(result) : result;<br>    return authenticated<br>  }<br><br>  function handleObservableResult(result: Observable&lt;boolean | UrlTree&gt;): Promise&lt;boolean | UrlTree&gt; {<br>    return new Promise&lt;boolean | UrlTree&gt;((resolve) =&gt; {<br>      result.subscribe((value) =&gt; {<br>        resolve(value);<br>      });<br>    });<br>  }<br><br>  const mockIsLoggedInTrue = () =&gt; {<br>    mockLoginService.isLoggedIn.and.returnValue(of(true));<br>  }<br><br>  const mockIsLoggedInFalse = () =&gt; {<br>    mockLoginService.isLoggedIn.and.returnValue(of(false));<br>  }<br><br>})</pre><p>I wanted to create this tutorial and share my solution because I spent quite many hours trying to figure out how to get the AuthGuard working, and especially trying to get the unit tests working. I hope this tutorial can save some time to somebody else out there.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c46738532cdd" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/authguard-authguard-unit-test-with-angular-16-c46738532cdd">AuthGuard &amp; AuthGuard unit test with Angular 16</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[An Accessible Modal Dialog with HTML, CSS, and JavaScript]]></title>
            <link>https://levelup.gitconnected.com/an-accessible-modal-dialog-with-html-css-and-javascript-d885004d0b3a?source=rss-52173d834c78------2</link>
            <guid isPermaLink="false">https://medium.com/p/d885004d0b3a</guid>
            <category><![CDATA[accessibility]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Giacomo Mariani]]></dc:creator>
            <pubDate>Tue, 24 Aug 2021 15:04:47 GMT</pubDate>
            <atom:updated>2021-08-24T15:04:47.265Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GYIerS1Q6vlvD84reSN1gw.jpeg" /></figure><p>In this post I want to share with the community a modal dialog I have implemented with HTML, CSS and JavaScript, that satisfies the tests set by the <a href="https://www.w3.org/WAI/GL/wiki/Using_ARIA_role%3Ddialog_to_implement_a_modal_dialog_box">W3C WCAG working group</a>:</p><ol><li>Check that role=dialog is an attribute of the container (such as a div) that is used as the custom dialog.</li><li>Check that the container is inserted (or made visible) via JavaScript following a user interaction or some other event.</li><li>When the dialog is activated, check that focus is set to an element in the container.</li><li>When the dialog is active, check that focus is never set to an element that is not in the container.</li><li>When the dialog is deactivated, check that focus is set to the control that originally activated the dialog.</li></ol><p>On top of these five points, I also want the modal dialog to satisfy the following:</p><ul><li>The modal dialog closes when the user clicks Escape.</li><li>The modal dialog closes when the user clicks outside its visible part.</li></ul><h3>The HTML code</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9b8514fa2f9f5c025d349ed793802b7/href">https://medium.com/media/d9b8514fa2f9f5c025d349ed793802b7/href</a></iframe><p>In the HTML code above the most relevant lines are:</p><p><strong>Line 12</strong>: We set the <a href="https://www.w3.org/TR/wai-aria-1.1/#aria-haspopup"><strong>aria-haspopup</strong></a> attribute to “<a href="https://www.w3.org/TR/wai-aria-1.1/#dialog">dialog</a>” in the body tag. I also considered setting it to “<a href="https://www.w3.org/TR/wai-aria-1.1/#alertdialog">alertdialog</a>”, but I thought that this popup is not meant to alert the user, so the “alert” role seems less fit for this case. We set this attribute to tell screen readers that the body element has a popup.</p><p><strong>Lines 15–16</strong>: This is the outer div of the modal, here: <br>- We give the<strong> role</strong> attribute “dialog” (could have been “alertdialog”).<br>- We set <a href="https://www.w3.org/TR/wai-aria-1.1/#aria-modal"><strong>aria-modal</strong></a> to true, in order to indicate to screen readers that this is a modal element.<br>- We specify the <a href="https://www.w3.org/TR/wai-aria-1.1/#aria-label">aria-label</a> as required by the dialog role. <br>- We set <a href="https://www.w3.org/TR/wai-aria-1.1/#aria-label">aria-live</a> to “assertive”, so that when the dialog updates (appears), the screen readers will announce it immediately.</p><p><strong>Lines 45–46</strong>: importing necessary scripts:<br>- The JavaScript code for the modal (see below).<br>- The <a href="https://github.com/WICG/inert"><strong>inert polyfill</strong></a>, to set all what is behind the modal as <a href="https://html.spec.whatwg.org/multipage/interaction.html#inert"><strong>inert</strong></a>, so that it is inaccessible not only to screen readers, but to keyboard navigation too.</p><h3>The JavaScript code</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e07af049b6d306c9b00dc3e5c3618f5d/href">https://medium.com/media/e07af049b6d306c9b00dc3e5c3618f5d/href</a></iframe><p>I tried to write the code in a self-explanatory way, but some parts might require a bit of explanation:</p><p><strong>Line 3</strong>: We save the element that has focus when the modal opens. This is necessary in order to put the focus back where it was, once the user closes the modal (line 25).</p><p><strong>Line 9</strong>: We want to close the modal when the user clicks on the “gray” opaque part (the overlay) around the modal box.</p><p><strong>Line 45</strong>: For this specific case, we could have looked only for buttons. To make the code more reusable, we look also for other elements that can receive focus and could be in a modal dialog. We set focus on the first element we find.</p><p><strong>Line 50</strong>: This is the part where we need the inert polyfill.</p><h3>The CSS style-sheet</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43363789933d08b8e6f2afc99e405e42/href">https://medium.com/media/43363789933d08b8e6f2afc99e405e42/href</a></iframe><p>I think the CSS does not require much explanation, but I feel like motivating the choice of choosing the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/display">CSS display property</a>, over the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/visibility">CSS visibility property</a>, or the <a href="https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/hidden">hidden</a> attribute.</p><p>Using <em>visibility</em> on the overlay, would have required (to be safe) setting <em>visibility</em> to “inherit” on the children, because descendants of the element will be visible if they have <em>visibility</em> set to <em>visible</em>. Plus, if position is not set to <em>fixed</em> or <em>absolute</em>, the element would still take up space even if not visible. So using the <em>display</em> property felt safer and saved one line of code.</p><p>The risk with the <em>hidden</em> attribute instead, is that changing the value of the CSS <em>display</em> property on an element with the <em>hidden</em> attribute overrides the behavior of the <em>hidden</em> attribute. So I felt it would be safer to just use the CSS <em>display</em> property.</p><p>There <a href="https://www.tpgi.com/the-current-state-of-modal-dialog-accessibility/">seemed to be a bug </a>in iOS Safari + VoiceOver when using <em>display: “none” </em>as default, but the post where it is mentioned is over two years old, I could not find more information about it, and when testing it, I did not come across the mentioned bug.</p><p>You can see the <a href="https://github.com/MarianiGiacomo/accessible-modal"><strong>full project on GitHub</strong></a> or in action <a href="https://marianigiacomo.github.io/accessible-modal/"><strong>here</strong></a>. Please comment if you find bugs or ways of improving it, or submit an <a href="https://github.com/MarianiGiacomo/accessible-modal/issues">issue</a>.</p><p>If you found this post useful and want to thank me, you can <a href="http://buymeacoff.ee/jamomani">buy me a coffee</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d885004d0b3a" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/an-accessible-modal-dialog-with-html-css-and-javascript-d885004d0b3a">An Accessible Modal Dialog with HTML, CSS, and JavaScript</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 I use MongoDB triggers]]></title>
            <link>https://levelup.gitconnected.com/how-i-use-mongodb-triggers-1bc466ddb48e?source=rss-52173d834c78------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bc466ddb48e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[trigger]]></category>
            <dc:creator><![CDATA[Giacomo Mariani]]></dc:creator>
            <pubDate>Fri, 23 Jul 2021 18:33:37 GMT</pubDate>
            <atom:updated>2021-07-23T18:33:37.556Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GdVjZLLnSjdGWmVc6YF3LA.jpeg" /></figure><p>In this post I will show the function I use in my <a href="https://www.mongodb.com/">MongoDB</a> trigger. I use MongoDB in many of my personal projects, and since they are mostly for test and portfolio purposes, I need a way to reset the DB daily by leaving only the data I want. <a href="https://docs.mongodb.com/realm/triggers/">MongoDB triggers</a> are excellent for that, and you can set them up easily on your MongoDB account by following <a href="https://docs.mongodb.com/realm/triggers/">this guide</a>, which I won’t repeat here.</p><p>Here I want to show the function I use in the trigger, because it took me a while to figure out a working solution, so I hope I can help others that may encounter the same problems I had.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20c5635d7efd74d0e1193fa036f97f39/href">https://medium.com/media/20c5635d7efd74d0e1193fa036f97f39/href</a></iframe><p>The code above is the function for a <a href="https://docs.mongodb.com/realm/triggers/scheduled-triggers/">scheduled trigger</a>. The function first finds the user I want to keep in the DB, called <em>testuser</em> (line 4), then utilizes the user <strong>_id</strong> to remove the blogs that do not belong to <em>testuser </em>(line 13). Notice on line 13 the use of <a href="https://docs.mongodb.com/manual/reference/operator/query/ne/"><strong>$ne</strong></a>, which stands for “not equal”. The same logic is repeated to remove the unwanted comments (line 28). After that, to remove the unwanted comment references from the blog documents (stored in blog.comments array), I first get all the left blog documents (line 24) and all the left comment documents (line 25), then I save the returned <a href="https://mongodb.github.io/node-mongodb-native/4.0//classes/findcursor.html">FindCursors</a> as arrays (lines 26 a&amp; 27), filer only the comments references of existing comments from the blog document (line 30), and finally <a href="https://docs.mongodb.com/drivers/node/current/usage-examples/updateOne/">update</a> the blog document (line 31–35).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bc466ddb48e" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-i-use-mongodb-triggers-1bc466ddb48e">How I use MongoDB triggers</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[Node & Fetch(FE) to set and catch error messages]]></title>
            <link>https://giacomo-mariani.medium.com/set-error-message-with-node-display-it-in-the-browser-with-javascript-a0319af26cf9?source=rss-52173d834c78------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0319af26cf9</guid>
            <category><![CDATA[error-handling]]></category>
            <category><![CDATA[error-message]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Giacomo Mariani]]></dc:creator>
            <pubDate>Thu, 24 Jun 2021 10:55:34 GMT</pubDate>
            <atom:updated>2021-07-25T11:42:59.801Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hf1Ugrw-vphnPomfWva1MA.png" /><figcaption>Error message as displayed in the browser</figcaption></figure><p>While working on a client front-end and a back-end API, I bumped on the need to create a custom error message with <a href="https://nodejs.org/en/">Node</a> in the API, catch the message with <a href="https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch">fetch</a>, and display that message on the client side with JavaScript. Before sharing my solution, a reminder that <strong>user input should be checked on the client side before sending it to the API. </strong>Since we can’t foresee all possible error cases, it is a good idea to check the input also on the server side, respond with a meaningful error message, and display the message to the user on the client side.</p><p>This is a simplified version of the Express API router code, where I handle the post request to create a new user:</p><figure><img alt="Image with the server side code" src="https://cdn-images-1.medium.com/max/672/1*ucolUEePJ3US-mp1cMc4zQ.png" /><figcaption>The server side code handling the POST request</figcaption></figure><p>The part I was getting wrong at the beginning, is that instead of setting the error message in response.statusMessage, I was setting it in the body of the response, like response.stateus(400).end(&#39;Error message here&#39;). Because of that, I was not able read it when catching the error on the client side.</p><p>This is the service on the client side, that sends the request to the back-end API:</p><figure><img alt="The client side code sending the POST request with fetch" src="https://cdn-images-1.medium.com/max/411/1*IHT5hYsQ2mX2iQwMaunEUw.png" /><figcaption>The client side code sending the POST request with fetch</figcaption></figure><p>As you can see, I am not catching the error yet, but throwing a new error with the response.statusText, corrensponding to the statusMessage in Node, if the response status code is not within 200–299.</p><p>This is the handle that is triggered when the user submits the form. It also catches the error and sets the notification messages which are shown to the user:</p><figure><img alt="The server side code handling the form submission" src="https://cdn-images-1.medium.com/max/832/1*zfXAL-X-6OFlA25sWsYSbQ.png" /><figcaption>The server side code handling the form submission</figcaption></figure><p>The form, which is not displayed in here, has the mandatory fields set as required and input checks. Also, for a matter of brevity, I leave out the logic behind the props.setNotification function.</p><p>If this tutorial helped you, you can thank me by <a href="http://buymeacoff.ee/jamomani">buying me coffee</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0319af26cf9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A quick tutorial on Hugo templates & creating your theme]]></title>
            <link>https://levelup.gitconnected.com/a-quick-tutorial-on-hugo-templates-creating-your-theme-a4102b42a85f?source=rss-52173d834c78------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4102b42a85f</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[hugo]]></category>
            <category><![CDATA[blogging]]></category>
            <dc:creator><![CDATA[Giacomo Mariani]]></dc:creator>
            <pubDate>Tue, 15 Dec 2020 19:01:25 GMT</pubDate>
            <atom:updated>2020-12-15T19:01:25.282Z</atom:updated>
            <content:encoded><![CDATA[<h3>A quick tutorial on Hugo templates and creating your theme</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*AFj6T0QnJbFAK_xz-YdEEg.jpeg" /></figure><p>This quick hands-on tutorial helps in understanding the logic behind Hugo themes and templates. We will create our own website and theme from scratch, and see how the different template layouts interact with each other and the content.</p><p>Create the structure for our new website with the hugo new site command:</p><figure><img alt="Creating a new site by executing the hugo new site command" src="https://cdn-images-1.medium.com/max/504/1*E8jMmZdv_2UMeppDs5_Svw.png" /><figcaption>Creation of a new Hugo site with “hugo new site” command</figcaption></figure><p>As you can see, we have two options: using a ready theme or creating our own. I think that the best way to grasp how all the different layouts and content files interact is to create our own theme and work our way through. We start with the hugo new theme command:</p><figure><img alt="Creating a new theme with the “hugo new theme” command" src="https://cdn-images-1.medium.com/max/399/1*qeBZMnIJa58KnpcA4vRt7g.png" /><figcaption>Creation of a new theme with the “hugo new theme” command</figcaption></figure><p>The command creates a new empty theme, with the folder structure and necessary files.</p><figure><img alt="Folder structure of myTheme folder" src="https://cdn-images-1.medium.com/max/175/1*xCxlCRuDUR5xW1tagfIMwA.png" /><figcaption>Folder structure and content of the recently created theme</figcaption></figure><p>If we start the server with thehugo servercommand, we get some warnings like the one shown below (we’ll get back to that soon). Then, if we go to <a href="http://localhost:1313/">localhost:1313</a> we get a blank page, so it is working but we have no content. Let’s see which layout files are being used and how.</p><figure><img alt="Part of the terminal output when executing the hugo server command" src="https://cdn-images-1.medium.com/max/1024/1*ftyWeVM2TCVNq-sc8RiNQg.png" /><figcaption>The hugo server command</figcaption></figure><p>Before continuing though, we have to tell Hugo that we are now using our myTheme template, so it knows where to look for the layouts template files. We can do this in the <a href="https://gohugo.io/getting-started/configuration/#configuration-file">config.toml</a> file at the root of our project. Just add the theme line and change the name of the theme in case it is called something else:</p><pre>baseURL = “<a href="http://example.org/">http://example.org/</a>&quot;<br>languageCode = “en-us”<br>title = “My New Hugo Site”<br>theme = “myTheme”</pre><h4><strong>baseof.html</strong></h4><p>The <a href="https://gohugo.io/templates/base/">Hugo documentation</a> explains that</p><blockquote>baseof.html is the shell from which all your pages will be rendered unless you specify another *baseof.html closer to the beginning of the <a href="https://gohugo.io/templates/lookup-order/">lookup order</a>.</blockquote><p>So this is what Hugo used as the base for all our pages. Lets’ see the content of our themes/myTheme/layouts/_default/baseof.html:</p><figure><img alt="Content of the base.html file" src="https://cdn-images-1.medium.com/max/387/1*XZ1jPd9Yyle0zMmbML9wlw.png" /><figcaption>Content of the base.html file</figcaption></figure><p>base.html pulls the content from the <strong>head.html, header.html, and footer.html </strong><a href="https://gohugo.io/templates/partials/">partial templates</a><strong> </strong>found in the myTheme/layout/partial folder. It also pulls the content from the <strong>main</strong> block.</p><blockquote>The <strong>main block</strong> comes from an html template, and <strong>the template used depends on the type of page</strong>.</blockquote><p>The blank landing page for example, where does its content come from? That blank page is our <a href="https://gohugo.io/templates/homepage/">Homepage</a>, which Hugo considers as an own type of <a href="https://gohugo.io/templates/lists/">list page</a>. Like other list pages, it is formed out of a template HTML file giving the structure, and a Markdown file with the content, which we explore next.</p><h4>Homepage</h4><p>For the Homepage we need:</p><ul><li>layouts/index.html</li><li>content/_index.md</li></ul><p>The layouts/index.html file for our theme is under themes/myTheme/layouts/index.html, and it is empty. We can fix this using the example template given in the <a href="https://gohugo.io/templates/homepage/#example-homepage-template">Hugo documentation</a> and adding it to our theme’s <strong>index.html</strong> file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/073192a064f60a6ddeb83df828c6b097/href">https://medium.com/media/073192a064f60a6ddeb83df828c6b097/href</a></iframe><p>What happens here? Hugo is pulling the title (line 4), subtitle (lines 4–6), and content (line 10) from the _index.md file, and the template for the summary of all pages under the Homepage (lines 13–15).</p><p>Now that we have the structure, we still miss the Homepage <a href="https://gohugo.io/content-management/">content</a>.</p><blockquote>The <strong>content folder</strong> structure and organisation reflects how the site is rendered. Its subfolders give the page path, determine content Type, and therefore the layout being used.</blockquote><p>The content for the Homepage is <a href="https://gohugo.io/templates/homepage/#add-content-and-front-matter-to-the-homepage">pulled from content/_index.md file</a>, which we are still missing, so let’s add it. Create the <strong>_index.md</strong> file under the content folder and add this content to it:</p><pre>---<br>title: &quot;Homepage&quot;<br>subtitle: &quot;Here I am&quot;<br>date: &quot;2020–012–09&quot;<br>menu: &quot;main&quot;<br>draft: &quot;false&quot;<br>---</pre><pre>Hello World! </pre><p>What you see above between the dashed lines is called the <a href="https://gohugo.io/content-management/front-matter#readout">Frontmatter</a>, and it contains metadata for the page. It can be used, among other things, to specify a specific type or layout for overriding the default ones.</p><p>Now, if you have saved the changes and Hugo server is still running, you should be able to see the content of the Homepage at <a href="http://localhost:1313/">localhost:1313</a>.</p><h4>Single pages (blog posts or other)</h4><p>For our blog post we need:</p><ul><li>content/post/first-post.md</li><li>layouts/_default/single.html</li><li>restart the server</li></ul><p>We continue by adding a blog post, but the same procedure is valid for any type of single page you want to create. Create a new blog post by executing in the terminal hugo new post/first-post.md. The command will add the content/post folder, and the first-post.md file to it, with a ready <a href="https://gohugo.io/content-management/front-matter#readout">Frontmatter</a>. In the Frontmatter, change draft: false to draft: true , otherwise, Hugo will not show the post when using the normal hugo server command. To build and serve also drafts, you would have to use hugo server -D.</p><p>Next, we add the <a href="https://gohugo.io/templates/single-page-templates/">html template for single pages</a> to our myTheme in layouts/_default/single.html . We can copy the template from <a href="https://gohugo.io/templates/single-page-templates/#example-single-page-templates">Hugo documentation</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9edc91c91fa9499c48de83b1e5c4ecf/href">https://medium.com/media/f9edc91c91fa9499c48de83b1e5c4ecf/href</a></iframe><p>Stop the Hugo server with Ctrl+c and then restart it executing hugo server. Now you should see your blog post from <a href="http://localhost:1313/post/first-post/">http://localhost:1313/post/first-post/</a>.</p><p>As you can see from the URL and path of your post, <a href="https://gohugo.io/content-management/organization/">Hugo takes the path from the folder name, and the slug from the file name</a>.</p><h4>List pages</h4><p>For the list page we need:</p><ul><li>content/post/_index.md</li><li>layouts/_default/list.html</li></ul><p>List pages can be useful if you want for example to list your posts on one page or list the content of any other section. In our case, we want a page in <a href="http://localhost:1313/post/first-post/">http://localhost:1313/post</a>, that lists all our blog posts.</p><p>Create the content/post/_index.md file from the terminal executing thehugo new post/_index.md command and change draft to false. Also, add some text after the dashed lines:</p><pre>---<br>title: &quot;Post&quot;<br>date: 2020-12-13T07:41:10+02:00<br>draft: false<br>---<br>Have a look at my blog posts!</pre><p>Next, add the template to myTheme in layouts/_default/list.html , we can again use the <a href="https://gohugo.io/templates/lists/#example-project-directory">Hugo documentation</a> for this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1db77563c2d1a53420d23187c13a856e/href">https://medium.com/media/1db77563c2d1a53420d23187c13a856e/href</a></iframe><p>Now the <a href="http://localhost:1313/post/">localhost:1313/post/</a> should show you the post-page with your blog post listed.</p><h4>Conclusion</h4><p>This was just an introduction to using Hugo themes and templates. There is much more to it, but now that you have an understanding of the logic, I think you can take full advantage of the <a href="https://gohugo.io/documentation/">Hugo documentation</a>. Go ahead, add more content, links, and images (check <a href="https://gohugo.io/content-management/image-processing/">this</a> and <a href="https://gohugo.io/content-management/shortcodes/#figure">this</a>) to your site!</p><p>There is still one little caveat. Do you remember this block from the layouts/index.html file in myTheme?</p><pre>{{ range first 10 .Site.RegularPages }}<br>  {{ .Render &quot;summary&quot;}}<br>{{ end }}</pre><p>Why it is not showing the summary of the blog post? Check <a href="https://gohugo.io/functions/render/#readout">this</a> out and see if you can fix it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4102b42a85f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/a-quick-tutorial-on-hugo-templates-creating-your-theme-a4102b42a85f">A quick tutorial on Hugo templates &amp; creating your theme</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[Create a Simple JSON Viewer for your Web Application]]></title>
            <link>https://levelup.gitconnected.com/create-a-simple-json-viewer-for-your-web-application-222c2891ea60?source=rss-52173d834c78------2</link>
            <guid isPermaLink="false">https://medium.com/p/222c2891ea60</guid>
            <category><![CDATA[html]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[json]]></category>
            <dc:creator><![CDATA[Giacomo Mariani]]></dc:creator>
            <pubDate>Thu, 21 May 2020 12:51:47 GMT</pubDate>
            <atom:updated>2020-05-25T19:23:31.953Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OI3-KUq5HpSw4hO8DK0Yew.png" /></figure><p>I needed to show the users of my web application the content of JSON files stored in the DB, so I created this simple visualizer that offers the possibility to expand and shrink the content of the JSON file, and also to choose if to show HTML content from the JSON file as a string or as HTML.</p><p>Since it is quite small, I keep all the code in index.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc861cde0ebde742036c96fac9b7dfe2/href">https://medium.com/media/fc861cde0ebde742036c96fac9b7dfe2/href</a></iframe><p>Then I also created an HTML document to test it (on line 47 and 49 you can see I am calling the functions from index.js):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1eba71920325599d938c3bc5184d4da/href">https://medium.com/media/e1eba71920325599d938c3bc5184d4da/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=222c2891ea60" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/create-a-simple-json-viewer-for-your-web-application-222c2891ea60">Create a Simple JSON Viewer for your Web Application</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[MQTT over WebSocket in a React App]]></title>
            <link>https://levelup.gitconnected.com/mqtt-over-websocket-in-a-react-app-35ce96cd0844?source=rss-52173d834c78------2</link>
            <guid isPermaLink="false">https://medium.com/p/35ce96cd0844</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mqtt-client]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Giacomo Mariani]]></dc:creator>
            <pubDate>Wed, 29 Jan 2020 15:07:13 GMT</pubDate>
            <atom:updated>2021-07-15T02:17:37.692Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/368/1*U9xCExMct8MpTgWRY6l2Zg.png" /></figure><p>Recently I had to use MQTT over WebSocket in a React web application to fetch live location from an API. Here is my solution. I tried to make the MQTT module as functional as possible.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JcDwisxNU9zTl-RA" /><figcaption>Photo by <a href="https://unsplash.com/@heytowner?utm_source=medium&amp;utm_medium=referral">JOHN TOWNER</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>The MQTT service module</h3><p>I have used the mqtt npm package, which you can install with <strong>npm install mqtt</strong><em> </em>command. This is the MQTT module I created:</p><pre>import mqtt from &quot;mqtt&quot;;</pre><pre>const websocketUrl = &quot;wss://&lt;SERVER-ADDRESS&gt;:443/mqtt&quot;;<br>const apiEndpoint = &quot;&lt;API-ENDPOINT&gt;/&quot;;</pre><pre>function getClient(errorHandler) {<br>  const client = mqtt.connect(websocketUrl);<br>  client.stream.on(&quot;error&quot;, (err) =&gt; {<br>    errorHandler(`Connection to ${websocketUrl} failed`);<br>    client.end();<br>  });<br>  return client;<br>}</pre><pre>function subscribe(client, topic, errorHandler) {<br>  const callBack = (err, granted) =&gt; {<br>    if (err) {<br>      errorHandler(&quot;Subscription request failed&quot;);<br>    }<br>  };<br>  return client.subscribe(apiEndpoint + topic, callBack);<br>}</pre><pre>function onMessage(client, callBack) {<br>  client.on(&quot;message&quot;, (topic, message, packet) =&gt; {<br>    callBack(JSON.parse(new TextDecoder(&quot;utf-8&quot;).decode(message)));<br>  });<br>}</pre><pre>function unsubscribe(client, topic) {<br>  client.unsubscribe(apiEndpoint + topic);<br>}</pre><pre>function closeConnection(client) {<br>  client.end();<br>}</pre><pre>const mqttService = {<br>  getClient,<br>  subscribe,<br>  onMessage,<br>  unsubscribe,<br>  closeConnection,<br>};</pre><pre>export default mqttService;</pre><h3>Initiating connection</h3><p>In the app I initiate the MQTT connection in the <strong>useEffect</strong> hook and save the MQTT client in the Redux store. The function <strong>storeError</strong> is from my Redux reducer, it is for storing error messages and I pass it as a callback when creating the client. The <strong>callBack</strong> function is to pass newly received mqtt messages to the message handler. Finally the <strong>useEffect</strong> hook returns the function to be called when the component unmounts (close the connection).</p><pre>import mqttService from &quot;./path/to/mqttWwebsocket&quot;;</pre><pre>...<br>....</pre><pre>useEffect(() =&gt; {<br>  const client = mqttService.getClient(storeError);<br>  storeMqttClient(client);<br>  const callBack = (mqttMessage) =&gt; handleMessage(mqttMessage);<br>  mqttService.onMessage(client, callBack);<br>  return () =&gt; mqttService.closeConnection(client);<br>}, []);<br>...<br>....</pre><h3><strong>Subscribing and unsubscribing from MQTT topics</strong></h3><p>I have a table from where the users can choose which location to follow (that would be the topic in MQTT terms). When the user chooses a different line from the table, the app unsubscribes from the old topic and subscribes to the new one.</p><pre>function rowSelectionHandler(newTopic) {<br> const topicHasChanged = // Check if I the topic has changed<br> const topic = // The current topic<br> if (topicHasChanged) {<br>   mqttService.unsubscribe(mqttClient, topic);<br> }<br> mqttService.subscribe(mqttClient, newTopic, storeError);<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35ce96cd0844" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/mqtt-over-websocket-in-a-react-app-35ce96cd0844">MQTT over WebSocket in a React App</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[Work on Overleaf Projects Offline]]></title>
            <link>https://giacomo-mariani.medium.com/work-on-overleaf-projects-offline-420fc16ca31b?source=rss-52173d834c78------2</link>
            <guid isPermaLink="false">https://medium.com/p/420fc16ca31b</guid>
            <category><![CDATA[overleaf]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[latex]]></category>
            <dc:creator><![CDATA[Giacomo Mariani]]></dc:creator>
            <pubDate>Fri, 03 Jan 2020 16:13:27 GMT</pubDate>
            <atom:updated>2021-07-25T11:42:29.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*hIF1brG6RTZvIprp4d5THQ.jpeg" /></figure><p>This is a guide to work with Overleaf projects locally, even when your are offline. Since Overleaf can be only used online, we will have to rely on other software. In this guide I present how I did it on Ubuntu, but the same can be done on other operating systems following the same principles, and using different software specific for the operating systems you are on.</p><p>The main steps are:<br>- Install the full version of LaTex<br>- Clone your Overleaf project<br>- Use a tool to work on the <em>.tex</em> file<br>- Use a tool to export <em>.tex</em> to <em>pdf</em> with bibliography<br>- Synchronize your local project with Overleaf</p><p><strong>Install the full version of LaTex</strong><br>You might not need the full version of the <strong>texlive</strong> package for a small project, but when working with LaTex you will probably quite soon start to use many different packages, therefore I recommend the full version if you can afford to use about 5 Gb of space for it. Install the <strong>texlive</strong> full version open your terminal and enter:</p><pre>sudo apt install texlive-full</pre><p><strong>Clone the Overleaf project<br></strong>Next we are going to clone our project from Overleaf to our hard drive. Go to you Overleaf project and click on the Menu icon on the top left corner. Next click on Git to open the window containing the link to clone the project, like show in the picture below:</p><figure><img alt="Screenshot from Overleaf with git link in pop-up window" src="https://cdn-images-1.medium.com/max/1024/1*PvlAytUdn6eq84-7epcmUA.png" /></figure><p>You can also get the link by using <strong>https://git.overleaf.com/&lt;YOUR-PROJECT-ID&gt;</strong>. You can see the project id in the URL after /project.<br>If you don’t yet have git installed, you can install it with:</p><pre>sudo apt update<br>sudo apt install git</pre><p>Now yon can clone your project, after which you will have a folder with the project name containing the files:</p><pre>git clone https://git.overleaf.com/&lt;YOUR-PROJECT-ID&gt;</pre><p>Before continuing further, is a good idea to create a <em>.gitignore</em> file. Exporting your <em>.tex</em> file to <em>pdf</em> will create files which is not necessary to push to Overleaf (like the <em>pdf</em> files itself). To tell git not to follow changes in some files, we have to create a <em>.gitignore</em> file in the project folder. The <em>.gitignore</em> file contains a list of files to be ignored by git.</p><p>The name of the <em>.tex</em> file I work on is <em>main.tex</em>, and the one containing the bibliography is <em>main.bib</em>, so I tell to ignore all other files which are created during compilation and creation of the <em>pdf</em> file. This is the content of my <em>.gitignore</em> file:</p><pre>main.aux<br>main.log<br>main.out<br>main.pdf<br>main.toc<br>main.xmpdata<br>pdfa.xmpi<br>main.bbl<br>main.blg</pre><p>You can create your own <em>.gitignore</em> file and copy in it the content above, taking care of changing “main” with the right name.</p><p><strong>Edit the .tex file</strong><br>To work on the <em>main.tex</em> file I use <strong>gedit</strong>, with added the <strong>gedit-latex-plugin</strong>. Any text editor can be used, and also any LaTex specific text editors, like TeXstudio or LaTeXila (they also export the .tex file to pdf), but I prefer using <strong>gedit</strong> and exporting the <em>.tex</em> file to <em>pdf</em> myself, like shown in the next step. If you decide to use <strong>gedit</strong>, the<strong> gedit-latex-plugin</strong> can be installed with:</p><pre>sudo apt install gedit-latex-plugin</pre><p>The plugin has also to be activated from <strong>gedit</strong> &gt; Preferences &gt; Plugins tab</p><p><strong>Export to pdf</strong><br>To easily export the <em>.tex</em> file to <em>pdf</em>, I created a script file and moved it to <em>/usr/bin/</em>, so that I can call it from any location. Here is the content of the file:</p><pre>!#/bin/bash<br>FILE=$1<br>pdflatex $FILE<br>bibtex $FILE<br>pdflatex $FILE<br>pdflatex $FILE </pre><p>To create the script file:<br>-Create a new file and name it so that you understand what it does, like “texToPdf”.<br>- Make the file executable with the command “sudo chmod 744 &lt;YOUR-SCRIPT-FILE&gt;”, like “sudo chmod 744 texToPdf”.<br>- Move the script file to <em>/usr/bin/</em> with “sudo mv &lt;YOUR-SCRIPT-FILE&gt; /usr/bin/”.<br>- To convert your <em>.tex</em> file to <em>pdf</em>, you can now do &lt;YOUR-SCRIPT-FILE&gt; &lt;YOUR FILE.tex&gt;, like “texToPdf main.tex”. You might need to press enter, yes or not few times during the execution when asked, depending if errors are encountered and which errors.</p><p><strong>Synchronize with Overleaf</strong><br>To <strong>check which tracked files have been changed</strong> (remember that file named in <em>.gitignore</em> are not tracked), when in the project folder you can type in the terminal “git status”. From now on, every time you want your local changes to be pushed to Overleaf, or the remote changes to be pulled from Overleaf, you will have to use the git commands illustrated below.</p><p>To <strong>add to the git stage</strong> all the tracked files which have been changed locally, before commit use “git add .” (replace the dot with a file name if you want to add a specific file).</p><p>To <strong>commit the changes</strong> after adding them to the stage use “git commit -m ‘write a show description of the changes here’ ”.</p><p>Now, if you want to <strong>avoid inserting username and password every time</strong> you push the changes to Overleaf, use the command below, otherwise ship to “push the changes” part. The <em>timeout option</em> specifies for how long in milliseconds the credentials are stored, in this example it corresponds to 6 months. Be aware that the <strong>credentials are stored in a plaintext</strong> file in <em>~/.git-credentials</em>.</p><pre>git config --global credential.helper ‘cache --timeout 15552000000’</pre><p>To <strong>push the changes</strong> to Overleaf (this will ask your Overleaf username and password) use “git push” from the project folder.</p><p>To <strong>pull changes</strong> from Overleaf use “git pull” from the project folder.</p><p>I hope this guide can be useful for people who like me don’t always have Internet connection when working.</p><p>If this tutorial helped you, you can thank me by <a href="http://buymeacoff.ee/jamomani">buying me coffee</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=420fc16ca31b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>