Showing posts with label tutorial. Show all posts
Showing posts with label tutorial. Show all posts

Friday, November 23, 2018

Getting Started with GraphQL and Express

Interested in learning a lot more about GraphQL? Get a deep dive with The Road to GraphQL 

You can employ GraphQL in your Express server using a middleware. If you get a request that goes to the endpoint POST /graphql, it will pass through the GraphQL Express middleware and handle the response for you.

Installing Packages


npm install express express-graphql graphql

The first package is for the Express server. You might already have that.

The second package is the Express GraphQL middleware.

The third package allows us to use GraphQL constructs in Nodejs.

Setting Up


const express = require('express');
const graphqlHTTP = require('express-graphql');

const schema = require('./schema');

const app = express();
const PORT = 3000;

app.use('/graphql', graphqlHTTP({
  schema: schema
}));

app.listen(PORT, () => {
  console.log(`Server running at port ${PORT}`);
});

The express-graphql middleware requires an Express app. You apply the middleware using app.use(). The first argument is the endpoint where GraphQL will be listening. The code above uses the standard /graphql route. The second argument calls on the middleware with a schema property that can be defined in a separate file:

// schema.js
const {
  GraphQLObjectType,
  GraphQLSchema,
  GraphQLString,
} = require('graphql');

const RootQueryType = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    fruit: {
      type: GraphQLString,
      resolve() {
        return 'Banana';
      }
    }
  }
});

module.exports = new GraphQLSchema({
  query: RootQueryType
});

The GraphQL schema is defined using an object with the query property. That will be the entry point for the queries requested by the client. Under fields, you can specify different types of resources you can query. In the example, we add a field called "fruit" that corresponds to a resource for a fruit and will always return the string "Banana."

You will likely start off creating a new GraphQLObjectType. Then, you define the name and fields properties. For the name, you can call it after the resource type. Each field has a type and a resolve() method that tells GraphQL how to find that resource and return it to the client. There are different types depending on the data type you are using. For example: GraphQLInt, GraphQLList, GraphQLString, etc.

Testing Queries with GraphiQL

GraphiQL Running on Localhost 3000 graphql

It might be helpful, especially if you don't have a frontend to work with, to use the GraphiQL tool to test queries on the browser. To enable it, add the graphiql property when you apply the middleware:

app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true
}));

With that, you can now access http://localhost:3000/graphql in your browser and it will open up a GraphiQL interface. You can try queries out there. For example, try the following:

query {
  fruit
}

You should expect the following response:

{
  "data": {
    "fruit": "Banana"
  }
}


Creating a Custom Type


Having only one field is uninteresting and does not show the true power of GraphQL. Let us turn out fruit into an object with the following properties: id, name, description, isTasty, calories. You can isolate that FruitType in a different variable:

const {
  GraphQLBoolean,
  GraphQLID,
  GraphQLInt,
  GraphQLObjectType,
  GraphQLSchema,
  GraphQLString,
} = require('graphql');

const FruitType = new GraphQLObjectType({
  name: 'FruitType',
  fields: {
    id: {
      type: GraphQLID
    },
    name: {
      type: GraphQLString
    },
    description: {
      type: GraphQLString
    },
    isTasty: {
      type: GraphQLBoolean
    },
    calories: {
      type: GraphQLInt
    }
  }
});

You can create the new type using a new GraphQLObjectType. Then you define a name property. Then you define a list of fields the object will have. For each field, the property is the field name and the value an object with the type property. Notice how we used different kinds of GraphQL built-in types.

Updating the Root Query


Once you defined your own FruitType, your RootQueryType then becomes like this:

const RootQueryType = new GraphQLObjectType({
  name: 'RootQueryType',
  fields: {
    fruit: {
      type: FruitType,
      resolve() {
        return {
          id: '507f1f77bcf86cd799439011',
          name: 'Banana',
          description: 'This fruit is delicious',
          isTasty: true,
          calories: 121
        };
      }
    }
  }
});

Notice how the type of fruit is no longer just a GraphQLString. It is now a FruitType, which happens to be a GraphQLObjectType.

The resolver method is also changed to reflect the new data structure for a Fruit. Typically, you would make a database call (e.g. via ORM) or an API call with an HTTP request in the resolve() method; then the data value for the specific resource would be returned. The resolve() method takes care to unwrap promises if you do provide them as the return value, so do not worry about doing that yourself.

One interesting thing to notice is the GraphQLID assumes the id property is a string, so be aware of that. You can check out the documentation for all the different GraphQL types here.

Trying a New Query


Now you can try the following query in GraphiQL in your browser:

query {
  fruit {
    id
    name
    description
    isTasty
    calories
  }
}

To which you will get the following response:

{
  "data": {
    "fruit": {
      "id": "507f1f77bcf86cd799439011",
      "name": "Banana",
      "description": "This fruit is delicious",
      "isTasty": true,
      "calories": 121
    }
  }
}

With GraphQL, you do not need to always get back all the fields from a resource. GraphQL allows you to ask only for the data you really need.

For example, the fruit object above does not have many fields, but a real world example would likely contains many, many fields.

Many times the client ends up not using all of the fields, so there is a lot of bandwidth waste. Users with a slow mobile connection would have to wait longer to download the larger set of data, only to end up using only part of it.

Other times, you end up not having enough data, so have to make additional requests to retrieve the missing parts.

GraphQL allows you to ask specifically for all the fields you are going to need to use in the client side. No more, no less. So you could just ask for the fruit id and name if you do not care about its description, nor if it is tasty, nor the calorie count:

query {
  fruit {
    id
    name
  }
}

And GraphQL will give you just that:

{
  "data": {
    "fruit": {
      "id": "507f1f77bcf86cd799439011",
      "name": "Banana"
    }
  }
}

Isn't that wonderful? :)

Read The Road to GraphQL to deep dive into the world of GraphQL!

Tuesday, June 28, 2016

Ruby Hashes

Need a reference text for the Ruby programming language? Get the Well-Grounded Rubyist.

An important data structure in Ruby is the hash. Hashes is a data structure of key-value pairs. In other programming languages, it might be called a dictionary or an associative array. If you know JavaScript, Ruby hashes are very similar to Objects. Let us take a look at the most basic aspects of Ruby hashes.

Creating a Hash

You can create a hash using literal notation, with curly braces:

hash = {}

The above is very similar to creating empty arrays, except for hashes you have to use curly braces.

Populating the Hash

To populate the hash, you can use bracket notation. Let us say we want to keep track of a todo list and use the key as the day of the week and the value as what we need to do. Populate the hash for Monday as so:

todo = {}
todo[:monday] = "clean the dishes"

Verify the contents of the hash:

=> {:monday=>"clean the dishes"}

A hash is a data structure of key-value pairs, so in the code above, we are associating the key :monday with the value "clean the dishes." One thing to notice is that we are using a symbol as the key. You could have used a string as the key, but it is common to use symbols as the key to Ruby hashes. Generally, using symbols will speed things up, as ultimately a string key will eventually (and internally) be converted to a symbol anyway.

Let us add one more todo to the hash:

todo[:wednesday] = "karate practice"

Now, the contents of the hash are:

=> {:monday=>"clean the dishes", :wednesday=>"karate practice"}

Hashes are represented using curly braces, with each key-value pair separated by a comma. The mapping between a key and a value is represented using the rocket or arrow symbol =>.

In general, you could have the key or value as any kind of object, not just a string or a symbol. For instance, you could use an integer as the key, but this would seem much like an array. You could also use, say, an array as the value to a certain key. That is perfectly fine in Ruby.

Accessing Nonexistent Key-Value Pairs

Now, what happens if you try to access a key for which the key-value pair does not exist?

=> {:monday=>"clean the dishes", :wednesday=>"karate practice"}

todo[:friday]
=> nil

The answer is nil. If you try to access a key for which there is not value associated with it, you will get nil. This behavior, however, can be changed if you create a new hash using new and then give it an argument for the default value. For instance:

todo = Hash.new
=> {}
todo[:tuesday]
=> nil

The above creates a new hash using Hash.new instead of using just {}. That results in the same outcome. When you try to refer to a key that points to no value, you get nil. Now, if you give new a default value:

todo = Hash.new("DOES NOT EXIST")
=> {}
todo[:tuesday]
=> "DOES NOT EXIST"

todo
=> {}

In the case above, whenever you try to access some key that does not have an associated value, you will get the string "DOES NOT EXIST", because you told Hash.new that that would be the default value in that situation. Mind, however, that the actual hash is still empty even though you got back "DOES NOT EXIST."

Creating a Hash with Initial Key-Value Pairs

So far we had to create a hash from scratch and add key-value pairs one by one. You could also have defined a hash with initial key-value pairs like so:

todo = { :monday => "clean the dishes", :wednesday => "karate practice" }

You can access the value to which a key points to using bracket notation and passing the key as the parameter:

todo[:monday]
=> "clean the dishes"

todo[:wednesday]
=> "karate practice"

Alternative Notation

There is an alternative notation to write hashes. If you are familiar with JavaScript, this will look just like writing JavaScript objects. Given the following definition:

todo = { :monday => "clean the dishes", :wednesday => "karate practice" }

Remove the arrow => and move the colon from the left-hand side of the symbol name to its right-hand side:

todo = { monday: "clean the dishes", wednesday: "karate practice" }

One thing to keep in mind is that you can only use that notation if the key is a symbol. Also, internally, hashes are still represented using the => notation:

todo
=> {:monday=>"clean the dishes", :wednesday=>"karate practice"}

Hash Size and Searching the Hash for Existence of Key/Values

You can find out how many key-value pairs there are in the hash using the size method:

todo
=> {:monday=>"clean the dishes", :wednesday=>"karate practice"}

todo.size
=> 2

Two useful methods to determine the existence of a certain key or certain value are: has_key? and has_value?

Here is an example:

todo.has_key? :monday
=> true

todo.has_key? :tuesday
=> false

Because we have :monday as one of the keys in the todo hash, we get true. However, the hash does not have the key :tuesday, so we get false for that.

Similarly, you can check whether some value is present in the hash:

todo.has_value? "wash the car"
=> false

todo.has_value? "clean the dishes"
=> true

There are many other useful methods that you can find in the Ruby documentation. So check it out

Hashes as the Last Argument to Methods

Say we have a method like so:

def greeting(name, hash)
  puts "Hello, #{name} !"
end

greeting("James", {})

Output:

Hello, James !

The method will simply say Hello followed by whatever name you give as the first argument. For the second argument, I just passed in an empty hash. Let us work with that hash next:

def greeting(name, hash)
  puts "Hello, #{name} !"
  puts "It seems that you have to #{hash[:monday]} on Monday"
end

greeting("James", { :monday => "wash the car" })

Output:

Hello, James !
It seems that you have to wash the car on Monday

So we passed a hash as an argument to greeting. That method then took the value in the hash whose key is :monday and used it to display a message about what the person needs to do.

Now that you understand what the method does, let us get to the point: if the last argument to a method call is a hash, you can omit the curly braces:

greeting("James", :monday => "wash the car")

You will see that a lot. Furthermore, you can also use the alternative notation:

greeting("James", monday: "wash the car")

To me, that looks a lot better. But you have to watch out for what it really means! That is just a hash in disguise. Keep in mind that because the hash is the last argument to the method call, you can omit the curly braces. And then you can also use the alternative notation, because the key is a symbol. It does not matter how many key-value pairs the hash has, the following would be totally okay too:

greeting("James", monday: "wash the car", tuesday: "do the laundry")

Fetch versus Bracket Notation to Retrieve a Value

Given the example:

todo
=> {:monday=>"clean the dishes", :wednesday=>"karate practice"}

You already know that to access a hash's value, you have to give the key within the square brackets:

todo[:monday]
=> "clean the dishes"

You can achieve the same outcome using the fetch method:

todo.fetch(:monday)
=> "clean the dishes"

But is there any difference at all? Consider the case where the key does not exist (i.e. no such key-value pair exists in the hash)

todo[:friday]
=> nil

todo.fetch(:friday)
KeyError: key not found: :friday
from (irb):63:in `fetch'
from (irb):63
from /usr/bin/irb:12:in `<main>'

While using bracket notation returns nil for a key that does not map to any value, using the fetch method will actually raise an exception! Let us go back to our example with the greeting method:

def greeting(name, hash)
  puts "Hello, #{name} !"
  puts "It seems that you have to #{hash[:friday]} on Monday"
  p hash[:friday]
end

greeting("James", { :monday => "wash the car" })

I changed the hash key in the greeting method to :friday (which does not have an associated value) and added a p statement to check the value of hash[:friday]. The output is:

Hello, James !
It seems that you have to  on Monday
nil

Now, if we use fetch instead:

def greeting(name, hash)
  puts "Hello, #{name} !"
  puts "It seems that you have to #{hash.fetch(:friday)} on Monday"
  p hash[:friday]
end

greeting("James", { :monday => "wash the car" })

Output:

Hello, James !
KeyError: key not found: :friday
from (irb):80:in `fetch'
from (irb):80:in `greeting'
from (irb):84
from /usr/bin/irb:12:in `<main>'

When we used bracket notation, the program kept executing and whenever we tried to access an unexistent key, we just got nil and things were just fine. But when we used fetch, it raised a KeyError exception and halted program execution right away. That is the difference between fetch and [] notation: the former raises an exception while the latter only returns nil. If you use fetch, make sure to rescue the exception and do something about it; otherwise, your program will come to a halt and stop. With bracket notation, the program will still keep going, even though having nil in certain places might have undesired effects in what you are trying to do. So handle the nil as well! :)

Conclusion

Ruby hashes are an important data structure that allows you to store data in key-value pairs. Make sure to understand them well, play with irb and make your own hashes. Try doing crazy things with it. Give it different kinds of keys and values and see what you get. Try accessing something that does not exist. Have fun! :)

Looking for a reference text for Ruby? Get the Well-Grounded Rubyist.

Tuesday, December 1, 2015

C++ Arrays

Interested in learning the C++ programming language? Try doing it with One Hour a Day.

Using arrays lets you assemble multiple data into a single entity. Using a primitive data type variable like an int or a double only allows you to store a single value. But when you make that variable an array, then you can store more than one value in one single variable entity.

This article will only consider static arrays -- that is, their size is already pre-determined and cannot be changed once the array has been declared. If you are looking for arrays that can change their size after declaration, those are called dynamic arrays.

In C++, arrays are declared with the following syntax:

data_type arrayName[arraySize];

data_type arrayName[arraySize] = { firstVal, secVal, ..., lastVal };

First, you have to say the type of you data you will be using. That could be any primitive data type such as char, int, float, double or more complex data types such as objects.

After that, give the array a name and tell its size (or length) within the brackets. The size has to be a constant, something that has already been pre-determined. Additionally, you may also want to initialize the array with given values. You do that enclosing each value in a comma-separated-list, within braces (you have to match the number of items with the array size). If you initialize the array right away, you can omit the arraySize and make the compiler guess the size from the number of items in the list. Note that the values have to be all of the same data type because you are declaring an array of a specific type.

As a concrete example:

// Declares an array of integers with 8 elements
int myIntegerArray[8];

// Declares and initializes an array of doubles with 6 elements
double myDoubleArray[6] = { 2.43, 1.24, 1.7, 1.234, 1.9, 3.0 };

// Declares and initializes an array of characters with 3 elements
// (array size guessed from number of items in the comma-separated list)
char myCharArray[] = { 'a', 'b', 'c' };

Note the above array of integers was not initialized, so there is not any meaning value assigned to each element yet.

To go through the items of each array, you usually do a for loop:

for (int i = 0; i < arraySize; i++)
{
    // goes through each array element
}

The loop starts at the first element -- which is always element "0" because array elements are counted from 0 and not one. The last array element is always the array size minus one, so we use just the greater-than operator; the loop stops after "i" becomes the same value as the array size.

As a concrete example:

// Goes through the array of integers (that has size 8) and
// sets each element to current value of i multiplied by 2
for (int i = 0; i < 8; i++)
{
    myIntegerArray[i] = i * 2;

    // Displays the current element value that was just assigned above
    cout << myIntegerArray[i] << endl;
}

Output:

0
2
4
6
8
10
12
14

One thing to keep a watch on is that in C++, you might find yourself accidentaly trying to find an element that is out of bounds in an array. Say your array has 8 elements. The last element has index [7] because you start counting elements from [0]. So the last element would be referred to myArray[7] in this case. But what if you tried to access myArray[8]? Well, this element does not really exist -- you are going out of bounds! It is like you have gone into someone else's property. Your C++ compiler might not complain about that. It will just assume that you are a good person and have not tresspassed into anyone else's property. Watch for this, especially when you do a "for" loop. Always make sure the loop condition uses the right comparison operator (typically you would use <, but you could also use <=) to prevent you from accessing elements beyond the array size.

Let us now look at another example using the last two previously declared arrays:

// Store the array size in an integer variable
int myDoubleArraySize = 6;

for (int i = 0; i < myDoubleArraySize; i++)
{
    cout << "myDoubleArray[" << i << "] has value " << myDoubleArray[i] << endl;
}

Output:

myDoubleArray[0] has value 2.43
myDoubleArray[1] has value 1.24
myDoubleArray[2] has value 1.7
myDoubleArray[3] has value 1.234
myDoubleArray[4] has value 1.9
myDoubleArray[5] has value 3

The above just goes through each element in the array of doubles and displays the corresponding value.

// Store the array size in an integer variable
int myCharArraySize = 3;

for (int i = 0; i <= (myCharArraySize - 1); i++)
{
    cout << myCharArray[i] << endl;
}

Output:

a
b
c

The above goes through each of the three elements in the array of chars. Note how my loop condition is different from the previously used less-than only operator. Here, instead of using i < arraySize, I am using i <= arraySize MINUS 1. That is exactly the same thing as checking for "i" less than the array size. I placed parenthesis between the expression just for emphasis. The loop ends when we reach arraySize minus 1, which is exactly the last element in the array.

Arrays are great when you have large amounts of data and you want to keep them organized and encapsulated into a single variable entity. When you work with arrays, always start counting from 0; the last array element is located at the size of array minus one. Arrays work well with loops because you can handle data conveniently by just using a single statement to take care of each and all of the array elements. Typically, you would use a for loop to go through the elements of an array, either for assignment or just to display their value.

Learning the C++ programming language? How about doing it with One Hour a Day.