Best Practices on Web Application Architecture – Late 2020

Do you even remember when was the first website created?

In the early 90’s Tim-Berner Lee (Born in London UK, 1955) created HTML, using which people could access documents through internet. We have come a long way from that to what we have today.

https://www.history.com/news/the-worlds-first-web-site

Four specific things we will be focusing on this article:

Single Page Application

When we say SPA it does not necessarily mean using frameworks like Angular, React or Vue. You can even create SPA using traditional Javascript and AJAX Requests or to make it easier simply use jQuery.

Popular SPA Frameworks of Javascript

SPA does not only mean faster loading of contents but also has deeper connection with isolation of frontend code to backend code. By creating single page application you start writing your backend code purely in server side because of which you reduce the cohesion already.

By creating SPA you also reduce load to your server. No need to call the server and load the whole page every time you click something. That way you can even reduce the cost by an enormous amount if you are receiving a huge user volume.

RESTful APIs

APIs are not a new thing. If you can remember using a login page where you enter your details and see an error without refreshing the whole page then Yeah! thats when you saw an API being used.

REST Endpoints naming standards

But the term RESTful is different. REST determines how the API looks like. The URL, Request Body, Response Body, Request Method and so on. You need to follow the standards to say that you have build a RESTful API.

By developing your web application through API based approach, releasing new versions or updates becomes far more easier.

Although following best practices can be difficult in many cases, building your application through API first approach should be your major priority. With API based approach of development you are already separating your frontend with your core backend logic which not only has one but many many benefits like testing those layers separately, route based load balancing and many more.

By following RESTful practices most of the APIs are self documented as well. For example; if you wrote a POST method that means the API is responsible for creating new data similarly GET, PUT, DELETE are self explanatory.

Docker

Now after having your web app developed and ready for deployment next comes the question of choosing the right deployment platform. Popular web host services like Bluehost, Godaddy etc provide pre-configured server environments with PHP, Python, MySQL. The problem with these hosting is that the versions and the additional libraries you install them are manually done and aren’t documented anywhere.

Documentation is key to success.

A dockerfile with steps to compile & deploy a simple frontend app

This is where containerisation comes in action. You need to write down each and every step of what you require in your server. Docker has been the number one choice to build & run containers.

Microservices

With my years and years of experience in web development, one thing that I have noticed is developers tend to create logics so complicated, a function or a class that is literally responsible to do everything. This is a bad thing to do.

Monolithic vs. Microservice Architecture

Tight coupling is a bad design.

Micro-service is a concept of physically isolating the features of an application. That way each feature or a service has to talk to each other through mediums like APIs or Message Queues or something similar. They cannot directly interact with each other through hard coded logic.

Conclusion

Web is a rapidly progressing technology sector. Every month there is something new evolving to become better or something new being introduced to add value. My suggestion is do not panic because of the introduction of new tech stack but instead admire the passion of people for creating these amazing new technologies to make things easier and efficient.

Keep Learning!

Youtube Video:
https://youtu.be/56J-KLjzO9I

Text pop-in screen: Link here
Text Templates: Link here

Export postgres database tables to csv

Below function/procedure will create a csv file for each table in the database.

CREATE OR REPLACE FUNCTION db_to_csv(path TEXT) RETURNS void AS $$
declare
   tables RECORD;
   statement TEXT;
begin
FOR tables IN 
   SELECT (table_schema || '.' || table_name) AS schema_table
   FROM information_schema.tables t INNER JOIN information_schema.schemata s 
   ON s.schema_name = t.table_schema 
   WHERE t.table_schema NOT IN ('pg_catalog', 'information_schema')
   AND t.table_type NOT IN ('VIEW')
   ORDER BY schema_table
LOOP
   statement := 'COPY ' || tables.schema_table || ' TO ''' || path || '/' || tables.schema_table || '.csv' ||''' DELIMITER '','' CSV HEADER';
   EXECUTE statement;
END LOOP;
return;  
end;
$$ LANGUAGE plpgsql;

Simply run the select command which will create file in provided path. Remember to provide chmod 777 /your/path so that the folder is writable.

SELECT db_to_csv('/your/path');

If you’re creating this inside a docker container use following command to copy it from container to host:

docker cp <container_id>:/your/path /your/host/path

Reference:

https://stackoverflow.com/questions/17463299/export-postgres-database-into-csv-file

PHPUnit Upload file testing

Testing file upload using phpunit can be challenging. Below are two ways you can test file uploads in phpunit integration tests.

When you’re testing an API with file upload, API Payload and File Payload must be sent separately.

Using fake file:

public function testUpload()
{
    $fileData = [
        'attachment' => UploadedFile::fake()->create('fakefile.pdf', 100)
    ];    

    $data = [
        'first_name' => 'John',
        'last_name' => 'Doe',
    ];    

    $url = 'http://localhost/upload';    

    $this->call(
      'POST', 
      $url, $data, [], $fileData, 
      $this->transformHeadersToServerVars([
        'Authorization' => 'Bearer xxxx'
      ])
    );    

    $this->assertResponseOk();
}

Using Original/Real file:
Here UploadedFile function has 6th parameter called testing which needs to be set true.

public function testUpload()
{
    $filePath = storage_path('realfile.pdf'); 

    $fileData = [
        'attachment' => new UploadedFile($file, null, null, null, null, true); 
    ]; 

    $data = [
        'first_name' => 'John',
        'last_name' => 'Doe',
    ];    

    $url = 'http://localhost/upload';    

    $this->call(
      'POST', 
      $url, $data , [], $fileData, 
      $this->transformHeadersToServerVars([
        'Authorization' => 'Bearer xxxx'
      ])
    );    

    $this->assertResponseOk(); 
}