Cooking up some Code Firebase v9

REACT JS with some backbones from spoony API and a dash of firebase. Initially this was supposed to be a quick build since I was overseeing a tutorial. I decided to add a firebase to be able to allow any user to add any cuisine of their choosing. I was meat with harsh resistance because of firebase. Only to find that firebase had been updated to version 9.

INTERESTING CODE FEATURE

The syntax change did put me off, but like any professional you have to get back in the bus. The modular construct was something that I look forward to use moving forward.

const imageReference = ref(storage, `images/${v4() + imageUpload.name}`)
    uploadBytes(imageReference, imageUpload)
    .then((snapshot) => {
      getDownloadURL(snapshot.ref).then((url) => {
        ////////////////////////////////////////////////
        const collectRecipes = collection(fire, 'recipes')
          addDoc(collectRecipes, { "name":titleRef.current.value, 
              "instructions":instructionRef.current.value,
              "ingredients":ingridentsList ,
              "url" : url
            }).then(response => {
                console.log(response);
                setMsg("Recipe added for the dish");
                titleRef.current.value = "";
                instructionRef.current.value = "";
                setIngridientsList([]);
                setImageUpload(null)
                setProcessingIcon(false)
            }).catch(error => {
              console.log("ERRROR");
              console.log(error);
              setProcessingIcon(false)
            });
        ////////////////////////////////////////////////
      })
    })
VoteLog – Project

Being in a third world country brings forward many challenges that would be present in a first world country. One would think with the state of lack the would be a high number of opportunities of development projects for people to hire a developer, especially for your undeveloped settlements. Yet the lack of knowledge tends to keep local business’s to value the same traditional systems that they are used to.

Yet this very weakness with a different lens eye’s out opportunities that would not be commonly seen. In this project I’ve developed a SAAS platform for people to run any form of voting competition that they want. Targeting pageants to even having dance, rap, singing etc basically anything that could required a pole for people to vote online.

INTERESTING CODE FEATURE

This snipped of JavasScript code is there to take action if a user copies an iFrame from youtube to share for a specific contestant. The script will extract the src code url and remove everything else that isn’t necessary so that the user does not have to deal with trying to figure out how to extract the url link, especially if they are not coders, which is to be expected. 

 if($("#can_youtubeurl").length > 0){
            //check for Iframe
            $("input#can_youtubeurl").on("input", function() {
                let textArea = $(this).val();
                let checkFrame = textArea.indexOf("<iframe");
             
                if(checkFrame == 0){
                    let stringIndex = textArea.indexOf("https://www.youtube.com/embed");
                    
                    let result = textArea.substring(stringIndex);
                    let stringColonIndex = result.indexOf('"');
                    let frameurl = result.substr(0, stringColonIndex);
                                        
                    $('input#can_youtubeurl').val(frameurl)
                }
              
            });
        }

Vocal Technologies: WP PHP, JavaScript

Third world coder epiphany

Being a developer has its ups and downs and for the most part it is a lucrative career to go after. Looking and the rate of growth in the industry and terms like a unicorn company, it is no now wonder the field sparks a lot of interest. Before you start thinking you’ll write your next app and the accolades will follow, one needs to take a step to remember that they are in a third world country and different rules apply.

For the most part most of the information we gather about how cool the field is turns out to be true, yet when one resides in a third world country in africa, they need to view things in this filter.

I call it “African Teck Tax”‘

One of the first things to face in this filter is that at a certain development skillset, you still will battle to gain clients or battle to get a well paying job even though if you where in a first world country it could have been enough to get well off. The reality tends to be that the are not enough clients willing to pay or even interested in a solution brought by a developer because they think they don’t need it. In any case they would need to change a lot of how the business is ran. So this creates a situation where as a developer you are forced to scale up your skill set by either specializing in specific languages or becoming more business minded. Taking into consideration that this career requires the person to frequently re-study the everchanging technologies each year.

Specializing

This option has the most extreme results. If you choose a language that is to be faced out in the long term, you will be faced out yourself. There are languages that at best you can be hired on a job to maintain legacy code. So one needs to research well why they want to master a language. Understand its uses and primarily invest to a be an expert in that language. Sounds like a killing a social life for a very long time. For a lot of people this is not even practical to spend 5 to 10 years without getting any realistic income due to having been exposed to the industry late to begin with. Most of the time under this filter we tend to be exposed to programming after high school or after working in a dead end job for a while. Which in theory should be fine but the ideal point to be exposed to programming would be starting high school. This gives a great opportunity to specialize. An expert becomes in demand for the highest paying jobs or even those high paying clients, which is not that many.

Business minded

This is actually a much more practical approach. Third world countries have third world problems, so you can’t really create an app then lease it to a company  who solves that problem. You have to start that type of business that solves that problem then use that app solution that you have. So if the site is about people buying something that people can use then, the focus is more the logistics of having it delivered more than the site to start the process. So as a developer you have to widen up your skillset to go beyond IT itself. I will prove to be a lot of work as well, yet it will yield better results sooner depending on the business you go into solving.

Laravel Passport

How to make use of an authentication token for your API.

In some cases your API will not be used in possible attack pron platforms. Like when the end points are exposed in a private mobile platform. Yet in other cases your end points may need to be highly available for public use. So in these cases it is very important to make use of an authentication token.

Assuming you already have a laravel project created and before you even migrate your database tables, you would need to install the passport service provider. I mean calling it passport, what are we trying ship to the UK.  I do find the name a bit over the top but thats what they named it. We start the process with the following line.


composer require laravel/passport

This passport service provider will create its own database migrations. Now you can migrate your tables if you are already happy with the table structure. Then you run the following command to migrate all the tables.


php artisan migrate

The next step is to rush over to your Users model. The path should be app/Users.php. Then the code you add being HasApiTokens right after the “use Notifiable“. Not forgetting to import it as well.


namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

class User extends Authenticatable
{
    use Notifiable, HasApiTokens;

   

Browse through to the AuthServiceProvider file to add the code Passport::routes(); in the function boot. You would still need to remember to add the use Laravel\Passport\Passport;

Then change the authentication driver to passport. Path config/auth.php


  'api' => [
            'driver' => 'passport',
            'provider' => 'users',
            'hash' => false,
        ],
   

Create a Controller ideally where you are going to create your methods. Then the following code allows you to register a user whom when you login, you will receive an access token. The token will permit you to go through all endpoints.




use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class AuthController extends Controller
{
   public function register(Request $request){

      $validatedData = $request->validate([
          'name'      => 'required|max:55',
          'email'     => 'email|required',
          'password'  => 'required|confirmed'
      ]);

      //encrypt the password
      //$validatedData['password'] = bcrypt($validatedData['password']);
      $validatedData['password'] = bcrypt($request->password);

      $user = User::create($validatedData);

      $accessToken = $user->createToken('authToken')->accessToken;

      return response(['user' => $user, 'access_token'=> $accessToken]);

    }

My testing on postman still required me to ensure we send the request with headers with the rule that we accept json application. Once it works, then it means you are good to go.



  public function login(Request $request){

      $loginData = $request->validate([
          'email'     => 'email|required',
          'password'  => 'required'
      ]);

      
      if(!auth()->attempt($loginData)){
        return response(['message' => 'Invalid credentials']);
      }
      $accessToken = auth()->user()->createToken('authToken')->accessToken;
      return response(['user' => auth()->user(), 'access_token'=> $accessToken]);
    }
}
Future builder

A widget that builds itself according to the latest snapshot. I created a news app just to review how the future builder works. This is how I did it. Ensure that you utilise a stateful widget because its built to be able to change in its lifetime.

I removed the counter app code that comes default with every project created, then I added a tab controller function along with the TabBarView widget. I created new dart files to make models. These are classes that will carry the fields that I am expecting to get from my backend.

The code itself pretty much has 2 sections. The function that you call on the future field attribute of the builder, which retrieves the data from your backend. and the snapshot where you build up what to place on your display.

In my example below I used a switch case. While the data has not yet returned to the widget for display, I want a loading bar to be displayed. If the is an error, then rather that error should be displayed as a test. As soon as the data is ready to be displayed then the loading bar will be replaced with the data.



      child: FutureBuilder(
        future: _getNewsArticle(),
        builder: (BuildContext context, AsyncSnapshot snapshot){
          switch(snapshot.connectionState ){
            case ConnectionState.active:
              return _loading();
              break;
            case ConnectionState.waiting:
              return _loading();
              break;
            case ConnectionState.none:
            //error
              return _error("No connection has been made.");
              break;
            case ConnectionState.done:
            //complete
              if(snapshot.hasError){
                return _error(snapshot.error.toString());
              }
              if(snapshot.hasData){
                return _drawListOfNewsArticles(snapshot.data);
              }
              break;
          }
          return Container();
        },
      ),
So I want to take IT as my career

With just only two letters IT is a massive career to get into. As technology becomes the most ever growing facet in modern life it makes logical sense to take up a career in this field. Before handling this colossal beast, I always advice that people that want to venture into this field should know certain things.

Firstly the are two major aspects to deal with mainly hardware and software. In this post I’ll be giving a simple illustration on the most easiest component of sotware development. To be exact, we will build a simply web page, that will give someone that has no clue on what to expect in this career, to have something to stand on. So expect to get an idea on the art of software development. In software development we commonly use what can be referred to as programming languages to formulate certain types of solutions. Kind off like how you would stereotype aggression from the Zulu language, humor from Spedi, loudness from Sesotho and sceptical sophistication from isiXhosa. Okay maybe I am stretching it a bit but it does work similar. The are languages that are used to run mobile solutions like Android. Desktop language solutions, Java and web language solutions, PHP. In our demo we will look into Hyper Text Transfer Protocol (http), which despite the debate is protocol language that formats the diplay of all content rendered through a browser.

So if you load it through a browser (chrome, safari, firefox, internet explorer) then http is what it, was formatted with, for display.

Ideally you would need to download some good softwares that are used to develop in the particular software language. In the case of web pages you actually can do the development using simple notepad, that comes installed on your PC. Open notepad then click through on File then on the drop down click through on Save As. Then navigate to the directory that you want to save your first website. Once there you will be required to change file Save as type to All files from the default Text Document (*.txt). Then on the File Name, you will be required to name the file and add the extension at the end(.html). The extension will give the file web page type. So lets label this file index.html. Once you have done this, clicked save button and feel free to navigate to the saved directory to find your file, which should be a web page type. When you click it open and it uses a browser then you know everything is working as it should.

Now you will notice that the screen is blank though. Now to put content on our page.


<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="This is a demo web page">
    <meta name="author" content="Tshepo Makhaola">

    <title>First Page</title>
  </head>

  <body>
  </body>
</html>

This code forms as the skeleton to a webpage and everything that is in between a > sign and the > sign, are referred to as tag elements. Each type of tag element plays a specific role. In this demo page we will have 4 tag elements to focus on. Title, body, H, Div

Title refers to the title that will be displayed on the browser tab. The body being the element that carries all the content of a page. H tag being the tag you commonly would use to create headings and the Div tag being the tag used to create anything else that you want to place on your web page.


<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="This is a demo web page">
    <meta name="author" content="Tshepo Makhaola">

    <title>First Page</title>
  </head>

  <body>
    <div>
        Lorem Ipsum is placeholder text commonly used in the graphic, print, and publishing industries for previewing layouts and visual mockups.
      </div>
    
  </body>
</html>

You are free to download the following zip to see what kind off cool stuff you can come up with. Notice that the is now link tag which I have added. In this case it is used to access the free CSS framework known as bootstrap. and what is CSS you may ask? well its used for styling the content. Otherwise it would look like one long book. Read more on this link.


<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="This is a demo web page">
    <meta name="author" content="Tshepo Makhaola">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
    <title>First Page</title>
  </head>

  <body>
    <h1>Hello World</h1>
    <h2>Hello World</h2>
    <h3>Hello World</h3>

    <div class="container">
      <div>
        The are pretty much two major things that I was on the look out for when building this plugin. One was to use the update_options function to store the phone number in the backend. Two was to use the whatsapp api to perform a javascript call and everything would work.
      </div>
    </div>

  </body>
</html>


You would note code with notepad under normal circumstances. Here are two softwares you could use to code that come for free.
Atom and Visual Studio Code

Whatsapper Whatsap Plugin

The are pretty much two major things that I was on the look out for when building this plugin. One was to use the update_options function to store the phone number in the backend. Two was to use the whatsapp api to perform a javascript call and everything would work.

So after enquiring all nessesary scripts I added the admin page as below.


//Admin Pages
function add_admin_pages(){
   add_menu_page( 'Whatsapper Plugin', 'Whatsapper', 'manage_options', 'whatsapper_plugin', 'whatsap_admin_page_block', plugins_url('/img/whats-dash.png', __FILE__), 110 );
}
add_action('admin_menu', 'add_admin_pages');

From then on it was a matter of setting up that field.



function whatsaper_shortcode_function($atts, $content= null){
   $directoryInf = dirname(__FILE__);
   $wNumber = esc_attr(get_option('whatsappnumber'));

    $content = '
'; $content .= '
<button id="whatsnumber" data-whatsnumber="+27'.$wNumber.'" class="lk-whatsapper">'; $content .= ' <img src="'.plugins_url('/img/Whatsapp-Icon-use-original.png', __FILE__).'" class="lk-icon"/> Book Now </button>'; $content .= '
'; $content .= '
'; return $content; }

Once I had completed all the php functionalities duties it as all now depending on javascript to do all the majic.


 document.getElementById("whatsnumber").addEventListener("click", function(){
     window.location = 'https://api.whatsapp.com/send?phone=' + number + '&text=%20'+ message;
  });
Bugs in my Member List

My task was pretty straight forward. The client wanted a solution where they could create a list of members to display in a particular page. The spanner was they wanted to create multiple member lists that they could easily reorder.

At quick glance I could have just created them a solution that allows a new listing of members each time. But that would have been horrendous to manage in the wordpress backend, seeing that the would be duplicate of the same members per list.

My solution was to create a plugin. In the plugin I would create a list of all the members with their details, stored on a custom post type. A page in the backend that will list all the members and allow simple drag and drop ordering.
Depending on what the check, that would be added in the list after giving the list a name and creating it. Then from there another custom post type would be the one that lists all the shortcodes.

Sounded easy enough. The first challenge was having to use jQuery to get the list of members then find a way to send them off to PHP, so that wordpress could be used to create the particular item saved in the post type. I used sent a post request on the wordpress ajax call after getting the list of ID’s. It took me hours to establish that I needed to add a site url variable in my wp_localize_script function.


 wp_localize_script('admin-reorder', 'LISTOBJECT', array(
            'secureCode' => wp_create_nonce('members-secret'),
            'siteURL'  => bloginfo('url')
         ));

I made this mistake because I was not aware that it wasn’t finding the ajax.php directory. Once that was handled my ajax call worked like a charm and I was even ready to go live after testing things out on my staging site.


  var ajaxurl = LISTOBJECT.siteURL + "/wp-admin/admin-ajax.php";
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                dataTye: 'json',
                data:{
                    action: 'save_mymembers',
                    list: lichecks.toString(),
                    name: name,
                    security: LISTOBJECT.secureCode
                },
                success: function (response){
                    if(true === response.success){
                        pgtitle.html('
Successfully saved your members list!
'); } else { pgtitle.html('
Something went wrong trying to save. Server orientated
'); } }, error: function (error){ pgtitle.html('
Something went wrong trying to save.
'); console.log(error); } });

To my suprise once I was live the member list shortcodes where not getting created. How could the same code that was working on my staging site, not work on the live site. After going through tunds of unnecessary if found out the following. The get_site_url functions retrieves the site url of any site but most of all it includes the appropriate ‘https’ or ‘http’ scheme. Which made the difference. The bloginfo(‘url’) that I was using using ws bringing me back an ‘http’ scheme and thats why it didn’t work.

And just like that my lady bug was working beautifully again.

To see the working functionality click through to Button

Handlebars js

Create html templates based on json data. 

I found it easier to understand unlike other frameworks ive gone through. A day or 2 of checking it out and 1 week later it was still on my mind to do some exploring.

I did exactly that. I was looking to create a laravel api to test things out but as a WordPress specialist, why shouldnt i test with something i go through on a daily bases.  So the wp-json endpoint became the perfect ginni pig for me to use.

I took an endpoint that contained artwork that I have been working on the last couple of months. My target was to list posts of a specific category, and allow a searching functionality.


var ourRequest = new XMLHttpRequest();
ourRequest.open(
  "GET",
  "https://www.tsdevcut.co.za/wp-json/wp/v2/artworks"
);

I did run into a problem when trying to filter by taxonomy. Nothing a WP rest filter couldn’t fix.