<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Lee Freeman</title>
    <description>The latest articles on DEV Community by Lee Freeman (@leefreemanxyz).</description>
    <link>https://dev.to/leefreemanxyz</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F105065%2F6f345627-1e92-4830-8294-b35c0fb36114.jpg</url>
      <title>DEV Community: Lee Freeman</title>
      <link>https://dev.to/leefreemanxyz</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/leefreemanxyz"/>
    <language>en</language>
    <item>
      <title>Timing functions with TypeScript decorators</title>
      <dc:creator>Lee Freeman</dc:creator>
      <pubDate>Fri, 08 May 2020 00:00:00 +0000</pubDate>
      <link>https://dev.to/leefreemanxyz/timing-functions-with-typescript-decorators-7i8</link>
      <guid>https://dev.to/leefreemanxyz/timing-functions-with-typescript-decorators-7i8</guid>
      <description>&lt;p&gt;So around November/December last year, I really felt like I was stagnating at work. I wasn’t feeling particularly challenged, was undervalued, distracted by my upcoming holiday in Mexico and wasn’t making the progress as a developer that I would have liked. So I decided to try and tackle the last issue as I felt I had the most control of it and I signed up to some courses on Udemy and pick up some new skills. One of those new skills I was interested in was TypeScript – it’s becoming more prevalent in the job market, offers an incremental adoption process and some blockers to adoption at work had been removed.&lt;/p&gt;

&lt;p&gt;So I signed up to Stephen Grider’s &lt;a href="https://www.udemy.com/course/typescript-the-complete-developers-guide/"&gt;TypeScript: The Complete Developer’s Guide&lt;/a&gt; and I’ve been slowly working through it over the last few months. One of the sections later on in the course is about decorators. I’d seen decorators applied to React-Redux a couple of years ago and I didn’t really understand them/see the need for them and they just generally seemed like confusing &lt;em&gt;magic&lt;/em&gt;. Since then I’ve seen similar looking code in my backend colleague’s Spring/Java code, in some Django project I worked with and when looking at some documentation for NestJS. It wasn’t until doing the section of Stephen’s course though that I began to understand them and see some uses for them.&lt;/p&gt;

&lt;p&gt;If you haven’t used decorators in Typescript before, then &lt;a href="https://www.typescriptlang.org/v2/docs/handbook/decorators.html"&gt;start with the documentation&lt;/a&gt;, but here I’m using them to modify a class method.&lt;/p&gt;

&lt;p&gt;I’ve written previously about using Neo4J at work, and I’m trying it out for a personal project, importing data from a postgres database using the JDBC driver. For this sort of importing job, I’ll create a base Neo4J class that accepts a Neo4J driver and add each step that I want to execute as a method to it.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class Neo4J {
  constructor(public driver: Driver) {}

  async runQuery() {
    try {
      const session = await this.driver.session();
      const res = await session.run(`
            // some cypher query
      `);

    } catch (error) {}
  }
}

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



&lt;p&gt;Now at work, we use Python to do the importing, and we call a logging function before and after each method, which prints a timestamp and a message. I didn’t really like this approach though, as there’s a lot of code repetition, so I decided to create a decorator factory for this (using a factory allows the message variable to be passed in for each method that it’s decorating).&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;
export function createTimestamps(message: string) {
  return function (target: any, name: string, descriptor: PropertyDescriptor) {
    const method = descriptor.value;
    descriptor.value = async function () {
      const startTime = new Date(Date.now());
      console.log(
        `${message} started at: ${startTime.toLocaleString("en-GB")}`
      );
      await method.apply(this);
      const endTime = new Date(Date.now());
      console.log(
        `${message} completed at: ${endTime.toLocaleString("en-GB")}`
      );
      console.log(
        `${message} took ${
          endTime.getTime() - startTime.getTime()
        }ms to complete.`
      );
    };
  };
}

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



&lt;p&gt;This decorator logs the start time of a function, then calls it (with &lt;code&gt;await method.apply(this)&lt;/code&gt;) and then logs the finish time and calculates how many milliseconds it took for the function to complete. To use it, import the &lt;code&gt;createTimestamps&lt;/code&gt; function and &lt;em&gt;decorate&lt;/em&gt; the method you want to collect timestamps for.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;export class Neo4J {
  constructor(public driver: Driver) {}

  @createTimestamps('Run query')
  async runQuery() {
    try {
      const session = await this.driver.session();
      const res = await session.run(`
            // some cypher query
      `);

    } catch (error) {}
  }
}

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



&lt;p&gt;When you call the &lt;code&gt;runQuery()&lt;/code&gt; method from now on, you’ll get some easy-to-digest information about how long each function took to run (and the code to modify this is neatly stored in just one place). Because this worked really well in Typescript for my use case, I looked up how to do the same thing in Python and opened a pull request at work to add the timestamps automatically (I borrowed some code I found online for this):&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;from datetime import datetime

import functools
import time

def timer(func):
    """Print the runtime of the decorated function"""
    @functools.wraps(func)
    def wrapper_timer(*args, **kwargs):

        print(
            f"[{datetime.now().strftime('%d/%m/%Y %H:%M:%S')}] Starting {func. __name__ }")
        start_time = time.perf_counter() # 1
        value = func(*args, **kwargs)
        end_time = time.perf_counter() # 2
        run_time = end_time - start_time # 3
        print(f"[{datetime.now().strftime('%d/%m/%Y %H:%M:%S')}] Finished {func. __name__!r} in {run_time:.4f} secs")
        return value
    return wrapper_timer

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



&lt;p&gt;While I was apprehensive before about decorators, I’m now one of the converted 🥰&lt;/p&gt;

</description>
      <category>typescript</category>
      <category>decorators</category>
      <category>javascript</category>
    </item>
    <item>
      <title>Multiline strings in GraphQL with Neo4J</title>
      <dc:creator>Lee Freeman</dc:creator>
      <pubDate>Thu, 07 May 2020 10:00:00 +0000</pubDate>
      <link>https://dev.to/leefreemanxyz/multiline-strings-in-graphql-with-neo4j-1j4p</link>
      <guid>https://dev.to/leefreemanxyz/multiline-strings-in-graphql-with-neo4j-1j4p</guid>
      <description>&lt;p&gt;For the last year or so I’ve been working with GraphQL with NodeJS quite a lot, both as a wrapper around some REST microservices and with the graph database Neo4J. While it hasn’t been a problem with the REST microservice project, line length has been a real problem when working with Neo4J schemas. This week I’ve found out two ways to solve this.&lt;/p&gt;

&lt;p&gt;When working with Neo4J I normally can let the library infer all my schemas and resolvers from the database contents, but sometimes I need to write some custom cypher (Cypher is Neo4j’s graph query language that allows users to store and retrieve data from the graph database).&lt;/p&gt;

&lt;p&gt;Here is an example from their docs:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const types = gql`
    type Movie {
    movieId: ID!
    title: String
    year: Int
    plot: String
    similar(first: Int = 3, offset: Int = 0): [Movie]
        @cypher(
        statement: "MATCH (this)-[:IN_GENRE]-&amp;gt;(:Genre)&amp;lt;-[:IN_GENRE]-(o:Movie) RETURN o ORDER BY COUNT(*) DESC"
        )
    }
`

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



&lt;p&gt;The &lt;code&gt;similar&lt;/code&gt; field is resolved using this custom &lt;a class="comment-mentioned-user" href="https://dev.to/cypher"&gt;@cypher&lt;/a&gt;
 directive, and while this is quite a simple query, it’s easy to find yourself writing much longer and more complex queries and you can’t just stick a line break in there. So here are two solutions.&lt;/p&gt;

&lt;p&gt;Despite working with GraphQL so much over the last year, I’m sure I haven’t even scratched the surface of what it’s capable of, and one of those things is how it supports multiline strings or &lt;a href="https://spec.graphql.org/June2018/#BlockStringCharacter"&gt;Block Strings&lt;/a&gt;, by wrapping the string in triple quotation marks “””. I’d seen this syntax in our Python loading scripts for Neo4J, and hadn’t realised that the same syntax was available with GraphQL (and, after all, as a Javascript/Typescript developer, I would normally just use a template literal for multiline blocks). So, the example above can be rewritten as:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const types = gql`
    type Movie {
    movieId: ID!
    title: String
    year: Int
    plot: String
    similar(first: Int = 3, offset: Int = 0): [Movie]
        @cypher(
        statement: """MATCH (this)-[:IN_GENRE]-&amp;gt;(:Genre)&amp;lt;-[:IN_GENRE]-(o:Movie)
                        RETURN o ORDER BY COUNT(*) DESC"""
        )
    }
`

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



&lt;p&gt;It’s not a drastic improvement here, but for longer queries, it really improves the readability.&lt;/p&gt;

&lt;p&gt;The other solution is even better - the latest release of the &lt;a href="https://github.com/neo4j-graphql/neo4j-graphql-js"&gt;neo4j-graphql-js&lt;/a&gt; library that I use has added an export of a &lt;code&gt;cypher&lt;/code&gt; template literal tag, which also enables syntax highlighting 😍. The previous example using this new syntax instead:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight"&gt;&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const similarQuery = cypher`
    MATCH (this)-[:IN_GENRE]-&amp;gt;(:Genre)&amp;lt;-[:IN_GENRE]-(o:Movie)
    RETURN o ORDER BY COUNT(*) DESC
`

const types = gql`
    type Movie {
        movieId: ID!
        title: String
        year: Int
        plot: String
        similar(first: Int = 3, offset: Int = 0): [Movie] @cypher(${similarQuery})
    }
`

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



&lt;p&gt;So much better 😊.&lt;/p&gt;

</description>
      <category>graphql</category>
      <category>neo4j</category>
      <category>cypher</category>
      <category>javascript</category>
    </item>
  </channel>
</rss>
