Skip to content

Instantly share code, notes, and snippets.

@alex-oliveira
Last active May 10, 2018 18:19
Show Gist options
  • Save alex-oliveira/c87edcea482ab78435a97653bb2222c4 to your computer and use it in GitHub Desktop.
Save alex-oliveira/c87edcea482ab78435a97653bb2222c4 to your computer and use it in GitHub Desktop.
APP VERSION

APP VERSION

Códigos para forçar o frontend a se atualizar automáticamente quando uma nova versão está disponível.

Prerequisitos:

  • Frontend feito com AngularJS e backend feito com Laravel
  • Frontend e backend que compartilham o mesmo nome de versão
  • Procedimento externo que atualize o nome da versão atual

LARAVEL API CONFIGS

.env

APP_VERISON=1.0.0
.
.
.

\App\Http\Middleware\AppVersionHeader.php

<?php

namespace App\Http\Middleware;

class AppVersionHeader
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure $next
     * @return mixed
     */
    public function handle($request, \Closure $next)
    {
        $response = $next($request);

        $response->headers->set('X-App-Version', env('APP_VERSION'));

        return $response;
    }
    
}

\App\Http\Kernel.php

protected $middleware = [
    .
    .
    .
    \App\Http\Middleware\AppVersionHeader::class,
];

ANGULAJS FRONT CONFIGS

App Version Interceptor

(function () {
    'use strict';
    angular.module('shared').factory('AppVersionInterceptor', AppVersionInterceptor);

    AppVersionInterceptor.$inject = ['$q', 'LocalStorage', '$state'];

    function AppVersionInterceptor($q, LocalStorage, $state) {
        var pattern = new RegExp('viacep');
        return {
            'response': function (response) {
                var server_version = response.headers('X-App-Version');
                if (server_version !== null) {
                    var local_version = LocalStorage.get('local_version');
                    if (local_version !== server_version) {
                        LocalStorage.set('local_version', server_version);
                        if (local_version !== null) {
                            window.location.reload(true);
                        }
                    }
                }
                return response;
            }
        };
    }
})();

App Config

angular.module('app').config(['$httpProvider', function ($httpProvider) {

    $httpProvider.interceptors.push('AppVersionInterceptor');
    .
    .
    .

}])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment