sgrove / DEV-blog-demo

DEV & GraphQL
https://DEV-blog-demo.netlify.com
0 stars 0 forks source link

Ionic made faster: Build & deploy hybrid apps in minutes. #15

Open sgrove opened 4 years ago

sgrove commented 4 years ago

Ionic Framework is a popular hybrid app development framework. The Hasura JS SDK can be used with Ionic to super-power your application with backend capabilities like authentication, data and file APIs. It lets you add these features without writing a single line of code.

This guide lays out the required information for you to kick start developing your Ionic application using Hasura backend APIs. We are using Ionic V1 apps which make use of AngularJS.

We have also made an Ionic-Hasura starter-kit which has complete working pages that demonstrates the capabilities of Hasura’s Backend APIs. You can refer to these to get started or even use this kit directly for your applications.

Including the Hasura JS SDK

The Hasura JS SDK is available on GitHub. The minified SDK is included in the starter-kit by default. In case you are starting your own app, download hasura.min.js and add the following snippet to your app’s index.html.

<script src="js/hasura.min.js"></script>

This script will expose a global variable called hasura which is available in the window scope. For normal JS applications, this would be enough. But, for AngularJS which is being used by Ionic, relying on global variables are not recommended. We need to inject this object to the components that would require it. For that purpose, we wrap this object inside an AngularJS Factory and make it available as an AngularJS component.

In order to do this, we create a new component under the scope of the AngulaJS module. Create a file called hasura.js with the following content and add include it in index.html.

'use strict';
angular.module('starter')
  .factory('hasura', function ($window) {
    return $window.hasura;
  });

Note: This assumes that the SDK has already loaded. Hence, make sure that the snippet including SDK comes before this file.

Now, you can inject hasura into any AngularJS component, like controllers etc. Before we can use the SDK to make queries and executing other actions, the SDK has to be initialised with a Hasura project. This can be done in the AngularJS app’s run section. If your application is for logged in users only, you can also make that check in the same section.

angular
  .module('starter', [
    'ionic',
  ])
  .run(function(hasura, $location){
    hasura.setProject('caddy89'); // if your domain is caddy89.hasura-app.io

    // Uncomment the following lines if you want to force users to login
    /**
    if (hasura.user.id === 0) {
      $location.path('/login')
    }
    */
  })

NOTE: This step also assumes that you have a Hasura project ready. In case you don’t have one, please log in to the Hasura Dashboard and create a project.

Auth APIs

Signup/Register

Sample controller for using Signup API is given below. Complete working example can be seen in the Ionic Hasura Starter-Kit

angular.module('starter.controllers')
  .controller('RegisterCtrl', function($scope, hasura, $ionicPopup) {
    $scope.loginData = {
      username: '',
      password: '',
      repassword: '',
      email: ''
    };
    $scope.doRegister= function() {
      if($scope.loginData.password !== $scope.loginData.repassword) {
        $ionicPopup.alert({
          title: 'Error',
          template: 'Passwords do not match'
        });
      } else {
        hasura.setUsername($scope.loginData.username);
        hasura.auth.signup($scope.loginData.password, {}, function(){
          console.log('signup success');
          $ionicPopup.alert({
            title: 'Success',
            template: 'Register success'
          });
          $scope.$apply();
        }, function(error){
          console.log('signup error');
          $ionicPopup.alert({
            title: 'Error',
            template: 'Register failed'
          });
        });
      }
    };
});

Login

A sample controller for using Login API is given below. A complete working example can be seen in the Ionic Hasura Starter-Kit

angular.module('starter.controllers')
  .controller('LoginCtrl', function($scope, hasura, $ionicPopup) {
    $scope.loginData = {
      username: '',
      password: ''
    };
    $scope.doLogin = function() {
      hasura.setUsername($scope.loginData.username);
      hasura.auth.login($scope.loginData.password, function(success) {
        console.log('login success');
        console.log(hasura.user);
        $ionicPopup.alert({
          title: 'Success',
          template: 'Login success'
        });
        $scope.$apply();
        // execute code after login
      }, function(error){
        console.log('login failed');
        console.log(error);
        $ionicPopup.alert({
          title: 'Error',
          template: 'Login failed'
        });
        // handle login error
      });
    };
});

Data APIs

In order to use the Data APIs, you need to create tables and configure permissions using the Hasura Console. The example provided in this starter-kit is a ToDo app, where you can add todos and mark them as completed. You can also delete todos. The advantage of using Hasura Data APIs is that you get instant JSON APIs to access and manipulate data along with an easy-to-use permissions model to implement access controls.

  1. id : Integer (auto-increment)

  2. title : Text

  3. user_id : Integer

  4. completed : Boolean

Note: A complete working example can be seen in the Ionic Hasura Starter-Kit

You can now use the following APIs:

Select

In order to select all the todos that belongs to a user, you can execute the following query:

hasura.data.query({
  type: 'select',
  args: {
    table: 'todo',
    columns: ['id', 'user_id', 'title', 'completed'],
    order_by: ['+completed', '+id']
  }},
  function(data){
    $scope.todos = data;
    $scope.$apply(); // Need to do this since angular wouldn't know when to re-render the scope
  },
  function(error){
    console.log(error);
  }
});

Insert

Create a new ToDo

hasura.data.query({
  type: 'insert',
  args: {
    table: 'todo',
    objects: [{
      user_id: hasura.user.id,
      title: title,
      completed: false
    }]
  }},
  function(data){
    console.log(data);
  },
  function(error){
    console.log(error);
  }
);

Update

Toggle completed state of an existing ToDo

hasura.data.query({
  type: 'update',
  args: {
    table: 'todo',
    where: { id: id },
    $set: { completed: !status }
  }},
  function(data){
    console.log(data);
  },
  function(error){
    console.log(error);
  }
);

Delete

Delete a ToDo

hasura.data.query({
  type: 'delete',
  args: {
    table: 'todo',
    where: { id: id }
  }},
  function(data){
    console.log(data);
  },
  function(error){
    console.log(error);
  }
);

File API

Upload

var input = document.getElementById('file-upload');
hasura.file.upload(
  input,
  function (successResponse) {
    fileId = successResponse.file_id;
    $scope.file = fileId;
    $scope.$apply();
    console.log('Uploaded file: ' + fileId);
  },
  function (errorResponse) {
    console.log('Error uploading file');
    console.log(errorResponse);
  });

Download

hasura.file.download(file, function(success){
  alert('file downloaded');
}, function(error){
  alert('download failed');
}); // This will use the HTML5 download attribute to start downloading the file

Delete

hasura.file.delete(file, function(success){
  alert('file deleted');
  $scope.file = undefined;
  $scope.$apply();
}, function(error){
  alert('file delete failed');
});

Hasura is a Postgres BaaS + Kubernetes PaaS to help you build and deploy backends super fast. Try it out at: https://hasura.io

Originally published at docs.hasura.io.

{"source":"medium","postId":"34e828ab4130","publishedDate":1504101325801,"url":"https://medium.com/@HasuraHQ/ionic-made-faster-build-deploy-hybrid-apps-in-minutes-34e828ab4130"}