Express Sequelize Heroku Postgres Configuration Success

You are in flow developing on your local database and you decide to upload everything to heroku and share it with the world.

How do you configure your production database?

Its easier than you think. Lets assume you have already set up your site. (link)

If you used the sequelize init command, you will have a file db/models/index.js that looks like this

Usually, your sequelize database will initialize with the usual database, username password, etc but in the special case that your config has use_env_variable, sequelize will recognize that an environment variable (usually representing a URI) can be used in place of the usual credentials.

What is your env variable?

After you run heroku addon create ... a new environment variable will be created at your heroku application

Find this in your heroku settings or running $ heroku config

You can access this with process.env.DATABASE_URL in any of your node.js code (on production). Your local machine will have different environment variables set.

Step 1: Set use_env_variable

But set it to what? Set it what heroku designates as your database url, DATABASE_URL!

Thats it!

You may need to migrate your database if you aren’t using sync

Step 2: Migrate your database

Error: no pg_hba.conf entry for host…, SSL OFF

you need to set TWO attributes to specify ssl

Error: The server does not support SSL connections

So tried to migrate your empty production database by setting the correct environment variables for the command and running db:migrate

$ NODE_ENV=production DATABASEURL=<db_url> sequelize db:migrate

How do you set up your local machine to support SSL?? You could get a certificate and configure your sequelize config to use that BUT theres an easier way.

Simply run the command in the heroku environment

$ heroku run ./node_modules/.bin/sequelize db:migrate --debug

How does sequelize pluralize?

If you use .sync with sequlize and have a model name like User, your database ends up with a table called Users. More clearly, when you use the sequelize-cli model generator the generated file will show this pluralized table. Here is the code: (link)

What is Utils

* Note Sequelize has a directory called Utils AND a file at lib/utils.js.

What’s in lib/util.js?

 

We find the function! This is how sequelize defines utils.pluralize link

Util.pluralize IS inflection.pluralize

This is how its tested 

What is inflection?

Inflection is a port of Ruby on Rails Active Support Inflection classes into JavaScript built by DreamersLab in Taipei. (link)

So how does sequelize/inflection pluralize?

Inflection seems to have rules based on:

Eventually, inflection takes these rules, uses RegExp and applies them to your string. Theres a bunch of rules and at the end theres this

The common rule that is the exhausted else or case default rule that targets the end of the string with $. No rules for that singular term? Add an s

Setting environment variables

How to see and set your environment variables

Print all your current environment variables with 

$ printenv

See a the value for a specific variable with echo

$ printenv <YOUR_VARIABLE> or $ echo $<YOUR_VARIABLE>

For example:

$ printenv MY_API_KEY or $ echo $MY_API_KEY

How do I set the variable temporarily?

This will set your variable for ONLY your current shell session

$ export <YOUR_VARIABLE>=some-secret-pattern

You can also prepend values to a currently set variable

$ export <YOUR_VARIABLE>=some-secret-pattern:$<YOUR_VARIABLE>

This is why you see export PATH statements like this

export PATH=/usr/local/mysql/bin:$PATH

This is actually prepending /usr/local/mysql/bin to the existing PATH

How do I set the variable permanently?

You can run the same start up export command with every shell session if you put this in your .bash_profile

export <YOUR_VARIABLE>=some-secret-pattern

* Make sure you source your bash_profile to see the changes

$ source ~/.bash_profile

How do I see it in my code?

Using your node shell:

node> console.log(process.env)

Using your python shell

python> import os; print os.environ

what is curl?

curl is tool to transfer data from or to a server, using one of the supported protocols (HTTP, HTTPS, FTP, POP3 etc)

What can I do with curl?

You can get the weather:

$ curl https://wttr.in

You can download hacker news

$ curl https://news.ycombinator.com/

You can read a file from Github

$ curl https://raw.githubusercontent.com/facebook/react/master/README.md

You can even download files with the > command

curl -L https://bit.ly/express-hello-world > index.js

 

What if we build a knowledge map?

What is a core unit of knowledge?

Can you map out a graph of competence based on individual nodes of ability?

What does it take to implement a merge sort?

Unit: Have a computer

Unit: install a programming language

Unit: download a text editor

Unit: know how to type

… etc, etc,

This can possibly be infinite…

 

But what if you added a goal?

Goal: Implement binary search in javascript with arrays

I need to learn

  • how to iterate over a smaller and smaller range of indices of an array and terminate when done
  • how to return from a function
  • how to change the value of variables
  • how to perform a conditional check given an element
  • how to access elements by index
  • how to get the index of the last element in an array
  • how to access an element based on the midpoint of x and y
  • how to create multiple variables,
    • one pointing to x (type number)
    • one pointing to y (type number)
    • one to indicate success or failure (type boolean)
  • how to create functions in js
  • how to create variables in js
  • how to find the midpoint of the range (x, y)
  • how to create an array

This is likely what you will need to be “competent” in before you can achieve your goal, at least for a certain implementation.

You might know how to do none, one or many of these bullet points.

But knowing where you are is the important part.

And maybe if you knew where you stood, and you shared it, the people trying to help you know where to start.

 

Question: are these units reusable? 

Yes, you’ll likely reuse a lot of these

Question: who decides what goes in this list?

Anyone with a clear goal. The units of competence can be the “first principles” of ability that can be directed towards a goal. And everyone has different goals. In fact everyone may have different implementations for a goal. So maybe the goals are personal, but the units are universal.

Question: What is competence?

The ability to do something.

Ask yourself. Do you know how to do something, do you know how to do anything?

How do you know?

 


Deeper Questions:

So could you then take on the task of mapping ALL of your knowledge?

And would knowledge equal competence?

did.txt file

Goal: create an insanely simple “did” file accessible by terminal

Time flies by when you’re learning how to code. Its super important to take a second every once in a while to simple write down what you did during the past mental sprint. Writing down what you learned solidifies the knowledge.

Cue the did.txt file

This file is simply an ongoing timestamped list of what you’ve done. There are many other options, “Notes” on Mac, OneNote but since we do not want to lose the flow of coding, we need this in the terminal

Version 1. A simple txt file

Type in command into your terminal and simply type out what you did.

$ vim ~/did.txt

example did.txt file

Version 2. A simple txt file with time stamps

vim on your command line allows options and this includes running “ex commands”. Here we run the r read command and read the date command into the file as a timestamp at the top of the file.

$ vim +'r!date' ~/did.txt

Version 3. A simple txt file with natural time stamps

Its likely more natural for you to type at the bottom of the file so with normal Go we move the cursor to the bottom before reading from the date command.

$ vim +'normal Go' +'r!date' ~/did2.txt

example did.txt file

Final Version. An alias to open did.txt

Final Step: Create your alias and add this to your .bash_profile.

alias did="vim +'normal Go' +'r!date' ~/did.txt"

Congrats!

Now running $ did in your terminal will bring you to your very own did file!

example did.txt file

 

For more about vim

Who is the keyword “this”?

`this` – NBA Edition

The keyword `this` is a difficult javascript topic that has been debated and pondered over for centuries – more or less. Its meaning is ambiguous at first glance mainly because what the keyword `this` refers to changes depend on where it is called. Here we explore some of the various ways in which this will be changed throughout your use and we will use the NBA as the backdrop to the conversation. * Feel free to open your console in Chrome and follow along with the examples. The global scope is the NBA. If we open up our console in Chrome and type this, Chromes returns back the window object – or the NBA in our context. The same occurs with console.log(this).

Free Floating Functions belong to the NBA

function whoIsThis(){
  console.log(this);
}

whoIsThis(); // returns current context; 

When we call a free floating function like this, the keyword `this` is assigned to the context in which its called. If we type whoIsThis() in our console, `this` refers to the our global window scope. If we tried this in server side code, the keyword this refers to an internal node.js object.

Players and Methods use this Lets create Kevin Durant. Kevin has a method that references our whoIsThis function from above.

var kevinDurant = {
    shoot3pct: 0.391,
    jersey: "Durant",
    findOutWhoIsThis: whoIsThis
}

If a function is invoked as a method of a player/object the keyword `this` now refers to the player. Type `kevinDurant.findOutWhoIsThis()` in the console and the function returns the object! Remember, keyword `this` is set at run time. Using the same whoIsThis function above, `this` is now Kevin Durant and not the NBA.

Steal moves with Apply and Call Lets create a function to shoot 3 pointers

var shoot3PT = function() {
    if (this.shoot3pct === undefined) { 
        return "Error: NBA has no 3pt percentage";
    }
    if (Math.random() > this.shoot3pct) {
        return "3 points for "+ this.jersey +"!";
    } else {
        return "Shot missed, try again!";
    }
}

Try calling `shoot3PT()` in the console. Error! The first argument of the apply or call functions will set the context of the function. Since KD has a shoot3pct property, we will simulate a three point shot by Durant with these functions.

    shoot3PT.apply(kevinDurant) 
    // or shoot3PT.call(kevinDurant) 
    // both simulate a 3 pointer

Nightmare mode: Remember we can always refer to `shoot3PT` as a method on Kevin Durant. Imagine another player, say Stephen Curry, wants to also use that function. We could use `apply` to set the context to him.

    
    kevinDurant.shoot3PT = shoot3PT

    stephenCurry = {
       this.shoot3pct: 0.99,
       this.jersey: "Curry"
    } 

    // Here we call apply on a method 
    // from another Player object!

    kevinDurant.shoot3PT.apply(stephenCurry)

Stephen Curry is the context for the shoot3PT function because of apply. Think of the possibilities –
We can simulate an entire basketball game with Javascript!

Stay tuned: next week we will explore the Game of Thrones edition. 

LA Hacks

 

The event was billed as the largest hackathon on the West Coast and is the only one I know of that lasted both Friday and Saturday night. 36 hours of coding and the list of suggested items included, at the top, a laptop and a sleeping bag. At first I was hesitant to sign up for the waiting list because it seemed to be geared towards students so I sent the organizer an email.

LA Hacks ended Sunday and the very next morning was my first day at Hack Reactor, an intensive three month Javascript focused school in the heart of San Francisco. A couple minutes later I received an email from the founder of the event, Hadar, that read, “Sure, come! It’ll be really fun and you’ll learn a lot.”

This is the very reason I love the community around hackathons. Coding is what matters. For most, the event is about learning, creating, and working as a team in a caffeine fueled hyper productive environment. A fellow Hack Reactor student and I took the official bus from UC Berkeley and to our surprise half the students had never been to a hackathon and a third had never coded but wanted to spend the weekend learning.Pauley Pavilion Scoreboard

It was a freaking blast! We listened to talks from founders and developers, met students from all over the country, and slept in the bleachers at Pauley Pavilion. We learned about Node, Express and Azure for serving our app, the Passport npm module for user authentication, Firebase and Go Instant for data storage and Web Speech API voice recognition which we used to create chatrooms by speaking the word “create”. Sunday was dedicated to presentations and it was awesome to show off our app and see the other hacks.

As weekend came to a close, Sam Alton took the stage as the keynote speaker and said, “There are two people in this world. There are those who create. And those who don’t.”

I believe we all create in our own ways. We create space ships, bridges, music, books, paintings, vaccines, charities, relationships, companies, communities, families, encouragement, excitement, craft beer and we contribute the most when we do.

“Keep Building”

His talk ended with one message, “keep building,” and I feel blessed that now at Hack Reactor I am surrounded by incredibly bright people who all want to do just that, build.