Categories
JavaScript Nodejs

Use GraphQL APIs in Vue.js Apps

GraphQL is a query language made by Facebook for sending requests over the internet. It uses its own query but still sends data over HTTP. It uses one endpoint only for sending data.

The benefits of using GraphQL include being able to specify data types for the data fields you are sending and being able to specify the types of data fields that are returned.

The syntax is easy to understand, and it is simple. The data are still returned in JSON for easy access and manipulation. This is why GraphQL has been gaining traction in recent years.

GraphQL requests are still HTTP requests. However, you are always sending and getting data over one endpoint. Usually, this is the graphql endpoint. All requests are POST requests, no matter if you are getting, manipulating, or deleting data.

To distinguish between getting and manipulating data, GraphQL requests can be classified as queries and mutations. Below is one example of a GraphQL request:

{  
  getPhotos(page: 1) {  
    photos {  
      id  
      fileLocation  
      description  
      tags  
    }  
    page  
    totalPhotos  
  }  
}

In this story, we will build a Vue.js app that uses the GraphQL Jobs API located at https://graphql.jobs /to display jobs data. To start building the app, we first install the Vue CLI by running npm i @vue/cli. We need the latest version of Node.js LTS installed. After that, we run vue create jobs-app to create new Vue.js project files for our app.

Then, we install some libraries we need for our app, which include a GraphQL client, Vue Material, and VeeValidate for form validation. We run:

npm i vue-apollo vue-material vee-validate@2.2.14 graphql-tag

This installs the packages. Vue Apollo is the GraphQL client, and graphQL-tag converts GraphQL query strings into queries that are usable by Vue Apollo.

Next, we are ready to write some code. First, we write some helper code for our components. We add a mixin for making the GraphQL queries to the Jobs API. Create a new folder called mixins, and add a file called jobMixins.js to it. Then in the file, we add:

import { gql } from "apollo-boost";

export const jobsMixin = {  
  methods: {  
    getJobs(type) {  
      const getJobs = gql`  
      query jobs(  
          $input: JobsInput,  
        ){  
          jobs(  
            input: $input  
          ) {  
            id,  
            title,  
            slug,  
            commitment {  
              id,  
              title,  
              slug  
            },  
            cities {  
              name  
            },  
            countries {  
              name  
            },  
            remotes {  
              name  
            },  
            description,  
            applyUrl,  
            company {  
              name  
            }  
          }  
        }  
      `;  
      return this.$apollo.query({  
        query: getJobs,  
        variables: {  
          type  
        }  
      });  
    }, 

    getCompanies() {  
      const getCompanies = gql`  
      query companies{  
          companies {  
            id,  
            name,  
            slug,  
            websiteUrl,  
            logoUrl,  
            twitter,  
            jobs {  
              id,  
              title  
            }  
          }  
        }  
      `;  
      return this.$apollo.query({  
        query: getCompanies  
      });  
    }  
  }  
}

These functions will get the data we require from the GraphQL Jobs API. The gql in front of the string is a tag. A tag is an expression, which is usually a function that is run to map a string into something else.

In this case, it will map the GraphQL query string into a query object that can be used by the Apollo client.

this.$apollo is provided by the Vue Apollo library. It is available since we will include it in main.js.

Next, in the view folder, we create a file called Companies.vue, and we add:

<template>  
  <div class="home">  
    <div class="center">  
      <h1>Companies</h1>  
    </div>  
    <md-card md-with-hover v-for="c in companies" :key="c.id">  
      <md-card-header>  
        <div class="md-title">  
          <img :src="c.logoUrl" class="logo" />  
          {{c.name}}  
        </div>  
        <div class="md-subhead">  
          <a :href="c.websiteUrl">Link</a>  
        </div>  
        <div class="md-subhead">Twitter: {{c.twitter}}</div>  
      </md-card-header><md-card-content>  
        <md-list>  
          <md-list-item>  
            <h2>Jobs</h2>  
          </md-list-item>  
          <md-list-item v-for="j in c.jobs" :key="j.id">{{j.title}}</md-list-item>  
        </md-list>  
      </md-card-content>  
    </md-card>  
  </div>  
</template>

<script>  
import { jobsMixin } from "../mixins/jobsMixin";  
import { photosUrl } from "../helpers/exports";

export default {  
  name: "home",  
  mixins: [jobsMixin],  
  computed: {  
    isFormDirty() {  
      return Object.keys(this.fields).some(key => this.fields[key].dirty);  
    }  
  },  
  async beforeMount() {  
    const response = await this.getCompanies();  
    this.companies = response.data.companies;  
  },  
  data() {  
    return {  
      companies: []  
    };  
  },  
  methods: {}  
};  
</script>

<style lang="scss" scoped>  
.logo {  
  width: 20px;  
}

.md-card-header {  
  padding: 5px 34px;  
}  
</style>

It uses the mixin function that we created to get the companies’ data and displays it to the user.

In Home.vue, we replace the existing code with the following:

<template>  
  <div class="home">  
    <div class="center">  
      <h1>Home</h1>  
    </div>  
    <form @submit="search" novalidate>  
      <md-field :class="{ 'md-invalid': errors.has('term') }">  
        <label for="term">Search</label>  
        <md-input type="text" name="term" v-model="searchData.type" v-validate="'required'"></md-input>  
        <span class="md-error" v-if="errors.has('term')">{{errors.first('term')}}</span>  
      </md-field> <md-button class="md-raised" type="submit">Search</md-button>  
    </form>  
    <br />  
    <md-card md-with-hover v-for="j in jobs" :key="j.id">  
      <md-card-header>  
        <div class="md-title">{{j.title}}</div>  
        <div class="md-subhead">{{j.company.name}}</div>  
        <div class="md-subhead">{{j.commitment.title}}</div>  
        <div class="md-subhead">Cities: {{j.cities.map(c=>c.name).join(', ')}}</div>  
      </md-card-header> <md-card-content>  
        <p>{{j.description}}</p>  
      </md-card-content><md-card-actions>  
        <md-button v-on:click.stop.prevent="goTo(j.applyUrl)">Apply</md-button>  
      </md-card-actions>  
    </md-card>  
  </div>  
</template>

<script>  
import { jobsMixin } from "../mixins/jobsMixin";  
import { photosUrl } from "../helpers/exports";export default {  
  name: "home",  
  mixins: [jobsMixin],  
  computed: {  
    isFormDirty() {  
      return Object.keys(this.fields).some(key => this.fields[key].dirty);  
    }  
  },  
  beforeMount() {},  
  data() {  
    return {  
      searchData: {  
        type: ""  
      },  
      jobs: []  
    };  
  },  
  methods: {  
    async search(evt) {  
      evt.preventDefault();  
      if (!this.isFormDirty || this.errors.items.length > 0) {  
        return;  
      }  
      const { type } = this.searchData;  
      const response = await this.getJobs(this.searchData.type);  
      this.jobs = response.data.jobs;  
    }, goTo(url) {  
      window.open(url, "_blank");  
    }  
  }  
};  
</script>

<style lang="scss">  
.md-card-header {  
  .md-title {  
    color: black !important;  
  }  
}

.md-card {  
  width: 95vw;  
  margin: 0 auto;  
}  
</style>

In the code above, we have a search form to let users search for jobs with the keyword they entered. The results are displayed in the card.

In App.vue, we replace the existing code with the following:

<template>  
  <div id="app">  
    <md-toolbar>  
      <md-button class="md-icon-button" @click="showNavigation = true">  
        <md-icon>menu</md-icon>  
      </md-button>  
      <h3 class="md-title">GraphQL Jobs App</h3>  
    </md-toolbar>  
    <md-drawer :md-active.sync="showNavigation" md-swipeable>  
      <md-toolbar class="md-transparent" md-elevation="0">  
        <span class="md-title">GraphQL Jobs App</span>  
      </md-toolbar><md-list>  
        <md-list-item>  
          <router-link to="/">  
            <span class="md-list-item-text">Home</span>  
          </router-link>  
        </md-list-item><md-list-item>  
          <router-link to="/companies">  
            <span class="md-list-item-text">Companies</span>  
          </router-link>  
        </md-list-item>  
      </md-list>  
    </md-drawer><router-view />  
  </div>  
</template>

<script>  
export default {  
  name: "app",  
  data: () => {  
    return {  
      showNavigation: false  
    };  
  }  
};  
</script>

<style lang="scss">  
.center {  
  text-align: center;  
}

form {  
  width: 95vw;  
  margin: 0 auto;  
}

.md-toolbar.md-theme-default {  
  background: #009688 !important;  
  height: 60px;  
}

.md-title,  
.md-toolbar.md-theme-default .md-icon {  
  color: #fff !important;  
}  
</style>

This adds a top bar and left menu to our app and allows us to toggle the menu. It also allows us to display the pages we created in the router-view element.

In main.js, we put:

import Vue from 'vue'  
import App from './App.vue'  
import router from './router'  
import store from './store'  
import VueMaterial from 'vue-material';  
import VeeValidate from 'vee-validate';  
import 'vue-material/dist/vue-material.min.css'  
import 'vue-material/dist/theme/default.css'  
import VueApollo from 'vue-apollo';  
import ApolloClient from 'apollo-boost';

Vue.config.productionTip = false  
Vue.use(VeeValidate);  
Vue.use(VueMaterial);  
Vue.use(VueApollo);const client = new ApolloClient({  
  uri: '[https://api.graphql.jobs'](https://api.graphql.jobs'),  
  request: operation => {  
    operation.setContext({  
      headers: {  
        authorization: ''  
      },  
    });  
  }  
});\

const apolloProvider = new VueApollo({  
  defaultClient: client,  
})

new Vue({  
  router,  
  store,  
  apolloProvider,  
  render: h => h(App)  
}).$mount('#app')

This adds the libraries we use in the app (such as Vue Material) and adds the Apollo Client to our app so we can use them in our app.

The this.$apollo object is available in our components and mixins because we inserted apolloProvider in the object we use in the argument of new Vue.

In router.js, we put:

import Vue from 'vue'  
import Router from 'vue-router'  
import Home from './views/Home.vue'  
import Companies from './views/Companies.vue'Vue.use(Router)export default new Router({  
  mode: 'history',  
  base: process.env.BASE_URL,  
  routes: [  
    {  
      path: '/',  
      name: 'home',  
      component: Home  
    },  
    {  
      path: '/companies',  
      name: 'companies',  
      component: Companies  
    }  
  ]  
})

Now we can see the pages we created when we navigate to them.

Categories
JavaScript Nodejs

How to Send Email with SendGrid in Node.js Apps

SendGrid is a great service made by Twilio for sending emails. Rather than setting up your own email server for sending email with your apps, we use SendGrid to do the hard work for us. It also decrease the chance of email ending up in spam since it is a known trustworthy service.

It also has very easy to use libraries for various platforms for sending emails. Node.js is one of the platforms that are supported.

To send emails with SendGrid, install the SendGrid SDK package by running npm i @sendgrid/mail . Then in your code, add const sgMail = require(‘@sendgrid/mail’); to import the installed package.

Then in your code, you send email by:

sgMail.setApiKey(process.env.SENDGRID_API_KEY);  
const msg = {  
  to: email,  
  from: 'email@example.com',  
  subject: 'Example Email',  
  text: `  
    Dear user, Here is your email.  
  `,  
  html: `  
    <p>Dear user,</p> <p>Here is your email.</p>  
  `,  
};  
sgMail.send(msg);

where process.env.SENDGRID_API_KEY is the SendGrid’s API, which should be stored as an environment variable since it is a secret.

Testing is easy since you don’t need to set up a local development email server.

Sending email is this simple and easy with SendGrid API. It is also free if you send small amounts of email, which is a great benefit.

Categories
JavaScript Nodejs

How to Deploy Node.js Web App to Heroku from Bitbucket

Note that the Git command is pushing a subfolder to Heroku, but you can push the root folder as well.

Then we to make a Procfile in the root folder of the back end app.\

release: npx sequelize db:migrate  
release: npm install -g sequelize-cli forever  
release: npm i  
web: node app.js

In this example, migrations are run, then packages are installed and the app is restarted.

Once you push your code in the branch you specified in the BITBUCKET_BRANCH variable, then all the commands you specified in the Procfile will run. The build steps are specified in the release: lines and the line running the web app is specified in the web: line of the Procfile .

Once the Procfile commands finished running, your app will be running.

Categories
JavaScript Nodejs

How to Use Sequelize to Manipulate Databases

Sequelize is a Node.js ORM with which has one of the most comprehensive features sets available.

It is similar to other ORMs like ActiveRecord, in that they are based on creating migrations with the Sequelize CLI, allowing you to write code to modify your database’s structure.

However, there are a few catches which someone has to be aware of. The migration functionality is not as smart as ActiveRecord. You cannot roll back database migration withour creating a down migration.

Also, migrations are not transactions, which means it may fail with a partially run migration where some parts of it failed to execute, leaving you with some changes made, but others not.

Sequelize CLI has to be installed separately from the library. You can run npm run --save-dev sequelize-cli to install it. After that, run npx sequelize model:generate to create your first model with its associated migration.

Add Model with Migration

For example, to create a User model with a Users table, run:

$ npx sequelize-cli model:generate --name User --attributes firstName:string,lastName:string,email:string

You may have to have administrator privileges in Windows to run this. This will create a firstName field, a lastName field, and an email field in the User model and when npx sequelize-cli migration is run, then a Users table will be created with the columns firstName , lastName and email .

The migration file should have this code:

'use strict';

module.exports = {  
  up: (queryInterface, Sequelize) => {  
    return queryInterface.createTable('Users', {  
      id: {   
        allowNull: false,  
        autoIncrement: true,  
        primaryKey: true,  
        type: Sequelize.INTEGER  
      },  
      firstName: {  
        type: Sequelize.STRING  
      },  
      email: {  
        type: Sequelize.STRING  
      },  
    });  
   }, down: (queryInterface, Sequelize) => {  
     return queryInterface.dropTable('Users');  
   }  
};

Note the id column is created automatically, and there is a down migration in the down function where the reverse of the up migration is included. If the code in the down function is not included, then you cannot run npx sequelize-cli db:migrate:undo to undo your migration.

You can also create migration and model files separately. They will be linked together if they are named in the correct pattern. Table name should be plural of the model name. For example Users table will map to the User model. To create migration without its associated mode, run npx sequelize migration:generate .

If you have multiple operations, you have to wrap them in an array and pass the array of operations into Promise.all and return that, since the return value of the up and down functions is a promise.

Adding Constraints

Adding constraints is simple. To do this, put the following in the up function of your migration file.

queryInterface.addConstraint(  
  "Users",  
  \["email"\],  
  {  
    type: "unique",  
    name: "emailUnique"  
})

To drop this, put:

queryInterface.removeConstraint(  
  'Users',  
  'emailUnique'  
)

Associations

To make has one, has many or many to many relations between tables, you can specify that using the Model.associate function. For example, if you have a Tweets table where multiple Tweets belong to one User , you can do:

Tweet.associate = function (models) { Tweet.belongsTo(models.User, {  
    foreignKey: 'userId',  
    targetKey: 'id'  
  });  
};

foreignKey is the ID referencing the external table and targetKey is the ID column of the table you’re referencing.

And in the User model:

User.associate = function (models) {  
  User.hasMany(models.Tweet, {  
    foreignKey: 'userId',  
    sourceKey: 'id'  
  });  
};

foreignKey is the ID referencing the current table in this case and sourceKey is the ID column of the table you’re referencing.

This specifies that each User has many Tweets.

Similarly, you can replace hasMany with hasOne to specifiy one to one relationship.

To make a many to many relationship, you need a join table between the 2 tables that you want to create relationship with, then you can use belongsToMany function of your model to create the relationship. You need this in both of your tables that you are creating the relationship with.

For example if multiple Users can belong in multiple ChatRooms , then do:

User.associate = function(models) {        
  User.belongsToMany(models.ChatRoom, {      
    through: 'UserChatRooms',      
    as: 'chatrooms',      
    foreignKey: 'userId',      
    otherKey: 'chatRoomId'    
  });  
};

And for the ChatRoom model:

ChatRoom.associate = function(models) {        
  ChatRoom.belongsToMany(models.User, {      
    through: 'UserChatRooms',      
    as: 'users',      
    foreignKey: 'chatRoomId',      
    otherKey: 'userId'    
  });  
};

foreingKey is the ID that the other table references, otherKey is the key that is in the current table.

Changing Columns

You can rename a column like this:

queryInterface.renameColumn('Tweets', 'content', 'contents')

The first argument is the table name, second is the original column, third one is the new column name.

Changing data type is simple:

queryInterface.changeColumn(   
  'Tweets',  
  'scheduleDate', {  
    type: Sequelize.STRING  
  }  
)

If you want to change string to date or time, do:

queryInterface.changeColumn(  
  'Tweets',   
  'scheduleDate', {  
    type: 'DATE USING CAST("scheduleDate" as DATE)'  
  }  
)queryInterface.changeColumn(  
  'Tweets',  
  'scheduleTime', {  
     type: 'TIME USING CAST("scheduleTime" as TIME)'  
  }  
)

To run migrations, run npx sequelize db:migrate .

And there we have it — a brief look into how to use Sequelize to manipulate databases! ?

Categories
JavaScript Nodejs

How to Incorporate Twitter Functionality into Your Node.js App

If you incorporated Twitter sign in functionality according to https://medium.com/@hohanga/how-to-add-twitter-sign-in-to-your-node-js-back-end-with-angular-app-as-the-front-end-d90213f95703, then it is very easy to incorporate Twitter functionality into your app by calling the Twitter API. To get the consumer key and secret, and find out how to get the OAuth access token and secret from Twitter which you will use with the Twitter API, follow https://medium.com/@hohanga/how-to-add-twitter-sign-in-to-your-node-js-back-end-with-angular-app-as-the-front-end-d90213f95703

Once you have the OAuth access token and secret, calling Twitter API is a piece of cake. For Node.js, I had success with https://www.npmjs.com/package/twit.

You simply pass in whatever credentials are requested to build the Twit object, which allows you to call the Twitter API.

Once that is done, you can do many things which otherwise has to be done manually.

According to https://www.npmjs.com/package/twit, here are the endpoints that it can call:

  • GET ‘statuses/update’
  • GET ‘search/tweets’
  • GET ‘followers/ids’
  • GET ‘account/verify_credentials’
  • POST ‘statuses/retweet/:id’
  • POST ‘statuses/destroy/:id’
  • GET ‘users/suggestions/:slug’
  • POST ‘media/upload’
  • ‘media/metadata/create’
  • ‘statuses/filter’

All the basic functionality like tweeting, uploading photos, and streaming can be used with this library, which means that you can automate tweeting and getting data from your account.

The full list of endpoints are at https://developer.twitter.com/en.html