static possible pour une méthode avec promise ?

Discussion dans 'Développement d'un site Web ou d'une appli mobile' créé par ortolojf, 3 Février 2021.

  1. ortolojf
    ortolojf WRInaute accro
    Inscrit:
    14 Août 2002
    Messages:
    3 361
    J'aime reçus:
    24
    Bonjour

    C'est du Javascript.

    Cette méthode localTextJson(response) est dans une classe, et rend une Promise en mode json ou text.

    Est-il possible de la déclarer static ?

    Merci beaucoup.

    Amicalement.



    Code:
    
                    /**********************************/
                    /** CETTE FONCTON REND JSON/TEXT **/
                    /**   SUIVANT LE CONTENT-TYPE    **/
                    /**       DE LA REPONSE.         **/
                    /**********************************/
                    var localTextJson = function(response) {
                            return new Promise(
                                    function (resolve, reject) {
                                            if(response) {
                                                    var Resp = response.clone();
                                                    if(Resp.ok) {
                                                            if (Resp.headers.get("content-type").match('application/json')) {
                                                                    resolve(Resp.json());
                                                            } else {
                                                                    resolve(Resp.text());
                                                            }
                                                    } else {
                                                            reject('Error with response Status : ' + Resp.status + ' : ' + Resp.statusText);
                                                    }
                                            } else {
                                                    reject('Response undefined');
                                            }
                                    }, function(error) {
                                            reject('Response with error : ' + error.message);
                                    });
                    };
    
    
     
  2. ortolojf
    ortolojf WRInaute accro
    Inscrit:
    14 Août 2002
    Messages:
    3 361
    J'aime reçus:
    24
    Rebonjour

    Ma librairie a deux classes Javascript RESPONSE et TEXT, et permet de charger en GET automatiquement la version la plus récente d'une url, dans le cache ou par fetch de manière optimisée.

    Cà marche, mais j'ai de la difficulté à mettre les fonctions utilitaires de manière accessible.

    Je les met dans les constructor, et cela m'oblige à dupliquer le code.

    Comment déclarer ces fonctions ?

    Merci beaucoup.

    Voilà le code :

    Code:
    
    class RESPONSE {
            constructor(request) {
                    const    CACHE = 'pwa-conf-v1';
                    // Small library to improve on fetch() usage
                    var api = function(method, url, data, headers = {}){
                            return fetch(url, {
                                    method: method.toUpperCase(),
                                    body: data,                                            // send it as stringified json
                                    credentials: api.credentials,                        // to keep the session on the request
                                    headers: Object.assign({}, api.headers, headers)    // extend the headers
                            }).then(res => (res.ok) ? res : Promise.reject(res));
                    };
                    // Defaults that can be globally overwritten
                    api.credentials = 'include';
                    api.headers = {
                            //        'csrf-token': window.csrf || '',     // only if globally set, otherwise ignored
                            'mode': 'cors'
                            //        'Accept': 'text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8',    // receive text/html
                            //        'Content-Type': 'text/html; charset=utf-8'    // send text/html
                    };
                    // Convenient methods
                    ['get', 'post', 'put', 'delete'].forEach(method => {
                            api[method] = api.bind(null, method);
                    });
                    var Request        = null;
                    var fileRequest = null;
                    var file         = null;
                    var accept        = null;
                    var contentType = null;
                    if(typeof request === 'string') {
                            Request = request;
                            fileRequest = request;
                            file = request;
                            accept        = 'text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8';    // receive text/html
                            contentType = 'text/html; charset=utf-8';    // send text/html
                    } else {
                            Request = request.clone();
                            fileRequest = request.clone();
                            tmp_url = new URL(Request.url, location.href);
                            file = tmp_url.pathname;
                            accept        = Request.headers.get("accept");
                            contentType = Request.headers.get("content-type");
                    }
                    /**********************************/
                    /** CETTE FONCTON REND JSON/TEXT **/
                    /**       SUIVANT LE CONTENT-TYPE    **/
                    /**            DE LA REPONSE.        **/
                    /**********************************/
                    var textJson = function(response) {
                            return new Promise(
                                    function (resolve, reject) {
                                            if(response) {
                                                    var Resp = response.clone();
                                                    if(Resp.ok) {
                                                            if (Resp.headers.get("content-type").match('application/json')) {
                                                                    resolve(Resp.json());
                                                            } else {
                                                                    resolve(Resp.text());
                                                            }
                                                    } else {
                                                            reject('Error with response Status : ' + Resp.status + ' : ' + Resp.statusText);
                                                    }
                                            } else {
                                                    reject('Response undefined');
                                            }
                                    }, function(error) {
                                            reject('Response with error : ' + error.message);
                                    });
                    };
                    (function(){function p(a){this.data="";this.a=0;if("string"===typeof a)this.data=a;else if(b.D(a)||b.L(a)){a=new Uint8Array(a);try{this.data=String.fromCharCode.apply(null,a)}catch(f){for(var v=0;v<a.length;++v)this.M(a[v])}}else if(a instanceof p||"object"===typeof a&&"string"===typeof a.data&&"number"===typeof a.a)this.data=a.data,this.a=a.a;this.v=0}function w(a,f,b){for(var d,c,h,m,g,k,e,r,n,l,t,q,u,p=b.length();64<=p;){for(g=0;16>g;++g)f[g]=b.getInt32();for(;64>g;++g)d=f[g-2],d=(d>>>17|d<<15)^(d>>>19|d<<13)^d>>>10,c=f[g-15],c=(c>>>7|c<<25)^(c>>>18|c<<14)^c>>>3,f[g]=d+f[g-7]+c+f[g-16]|0;k=a.g;e=a.h;r=a.i;n=a.j;l=a.l;t=a.m;q=a.o;u=a.s;for(g=0;64>g;++g)d=(l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7),h=q^l&(t^q),c=(k>>>2|k<<30)^(k>>>13|k<<19)^(k>>>22|k<<10),m=k&e|r&(k^e),d=u+d+h+x[g]+f[g],c+=m,u=q,q=t,t=l,l=n+d|0,n=r,r=e,e=k,k=d+c|0;a.g=a.g+k|0;a.h=a.h+e|0;a.i=a.i+r|0;a.j=a.j+n|0;a.l=a.l+l|0;a.m=a.m+t|0;a.o=a.o+q|0;a.s=a.s+u|0;p-=64}}var m,y,e,b=m=m||{};b.D=function(a){return"undefined"!==typeof ArrayBuffer&&a instanceof ArrayBuffer};b.L=function(a){return a&&b.D(a.buffer)&&void 0!==a.byteLength};b.G=p;b.b=p;b.b.prototype.H=function(a){this.v+=a;4096<this.v&&(this.v=0)};b.b.prototype.length=function(){return this.data.length-this.a};b.b.prototype.M=function(a){this.u(String.fromCharCode(a))};b.b.prototype.u=function(a){this.data+=a;this.H(a.length)};b.b.prototype.c=function(a){this.u(String.fromCharCode(a>>24&255)+String.fromCharCode(a>>16&255)+String.fromCharCode(a>>8&255)+String.fromCharCode(a&255))};b.b.prototype.getInt16=function(){var a=this.data.charCodeAt(this.a)<<8^this.data.charCodeAt(this.a+1);this.a+=2;return a};b.b.prototype.getInt32=function(){var a=this.data.charCodeAt(this.a)<<24^this.data.charCodeAt(this.a+1)<<16^this.data.charCodeAt(this.a+2)<<8^this.data.charCodeAt(this.a+3);this.a+=4;return a};b.b.prototype.B=function(){return this.data.slice(this.a)};b.b.prototype.compact=function(){0<this.a&&(this.data=this.data.slice(this.a),this.a=0);return this};b.b.prototype.clear=function(){this.data="";this.a=0;return this};b.b.prototype.truncate=function(a){a=Math.max(0,this.length()-a);this.data=this.data.substr(this.a,a);this.a=0;return this};b.b.prototype.N=function(){for(var a="",f=this.a;f<this.data.length;++f){var b=this.data.charCodeAt(f);16>b&&(a+="0");a+=b.toString(16)}return a};b.b.prototype.toString=function(){return b.I(this.B())};b.createBuffer=function(a,f){void 0!==a&&"utf8"===(f||"raw")&&(a=b.C(a));return new b.G(a)};b.J=function(){for(var a=String.fromCharCode(0),b=64,e="";0<b;)b&1&&(e+=a),b>>>=1,0<b&&(a+=a);return e};b.C=function(a){return unescape(encodeURIComponent(a))};b.I=function(a){return decodeURIComponent(escape(a))};b.K=function(a){for(var b=0;b<a.length;b++)if(a.charCodeAt(b)>>>8)return!0;return!1};var z=y=y||{};e=e||{};e.A=e.A||{};e.F=e.A.F=z;z.create=function(){A||(n=String.fromCharCode(128),n+=m.J(),x=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],A=!0);var a=null,b=m.createBuffer(),e=Array(64),d={algorithm:"sha256",O:64,P:32,w:0,f:[0,0],start:function(){d.w=0;d.f=[0,0];b=m.createBuffer();a={g:1779033703,h:3144134277,i:1013904242,j:2773480762,l:1359893119,m:2600822924,o:528734635,s:1541459225};return d}};d.start();d.update=function(c,h){"utf8"===h&&(c=m.C(c));d.w+=c.length;d.f[0]+=c.length/4294967296>>>0;d.f[1]+=c.length>>>0;b.u(c);w(a,e,b);(2048<b.a||0===b.length())&&b.compact();return d};d.digest=function(){var c=m.createBuffer();c.u(b.B());c.u(n.substr(0,64-(d.f[1]+8&63)));c.c(d.f[0]<<3|d.f[0]>>>28);c.c(d.f[1]<<3);var h={g:a.g,h:a.h,i:a.i,j:a.j,l:a.l,m:a.m,o:a.o,s:a.s};w(h,e,c);c=m.createBuffer();c.c(h.g);c.c(h.h);c.c(h.i);c.c(h.j);c.c(h.l);c.c(h.m);c.c(h.o);c.c(h.s);return c};return d};var n=null,A=!1,x=null;self.forge_sha256=function(a){var f=e.F.create();f.update(a,b.K(a)?"utf8":void 0);return f.digest().N()}})();
    
                    var UUIDv5 = function() {
                            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                                    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
                                    return v.toString(16);
                            });
                    }
    
    var from_filename = function(str, sep) {
            return new Array(str.substring(0, str.lastIndexOf(sep)), str.substring(str.lastIndexOf(sep) + 1));
    }
    
    var EMPTY = function(str) {
            if(typeof str == 'undefined' ||
                    str === undefined ||
                    str === null ||
                    str === false ||
                    str === '') {
                    return true;
            }
            return false;
    }
    
    var requestHeaders = {
            'Cache-Control': 'no-store',
            'Accept': accept,
            'Content-Type': contentType
    };
    
    var chemin                = null;
    var avant_file_ndd        = null;
    var file_ndd            = null;
    var str                = new Array();
    var hash_code_file        = null;
    var Response            = null;
    var Response1            = null;
    var Response2            = null;
    var HashCodeResponse    = null;
    var HashCodeCache        = null;
    var text                = null;
    var tmp_text            = null;
    var hash_code_cache    = null;
    var hash_code            = null;
    var contentType        = null;
    str = from_filename(file, '/');
    chemin = str[0];
    avant_file_ndd = from_filename(from_filename(file, '/')[1], '.')[0];
    file_ndd = from_filename(file, '.')[1];
    hash_code_file = chemin + '/hash_code_' + avant_file_ndd + '.txt';
    /*************/
    /** FICHIER    **/
    /*************/
    file = new URL(file, location.href);
    /*****************/
    /**      FICHIER    **/
    /**    HASH CODE     **/
    /*****************/
    hash_code_file = new URL(hash_code_file, location.href);
    console.log('request for : ' + file + ' and : ' + hash_code_file);
    return new Promise(function(resolve, reject) {
            caches.open(CACHE).then(function (cache) {
                    console.log('file : ' + fileRequest + ' is being fetched from the cache.');
                    /*****************************************************/
                    /**    ON CHARGE LE HASH CODE DU FICHIER EN CACHE        **/
                    /*****************************************************/
                    /**        CE HASH CODE DOIT AVOIR ETE UPDATE LORS        **/
                    /**            DU DERNIER CHARGEMENT DU FICHIER.        **/
                    /*****************************************************/
                    cache.match(fileRequest).then(function(response) {
                            if (response) {
                                    Response = response.clone();
                                    textJson(Response).then(function(text) {
                                            if(!EMPTY(text)) {
                                                    HashCodeCache = forge_sha256(text);
                                            } else {
                                                    cache.delete(fileRequest).then(function(result) {
                                                            console.log('file : ' + fileRequest + ' deleted from the cache.');
                                                    }, function(error) {
                                                            console.log('file : ' + fileRequest + ' not in the cache, with error : ' + error.message);
                                                    })
                                            }
                                    }, function(error) {
                                            console.log('Error while reading file from the cache : ' + fileRequest + '  , with error : ' + error.message);
                                    })
                            } else {
                                    console.log('file not in cache : ' + fileRequest);
                            }
                    }, function(error) {
                            console.log('file not in cache : ' + fileRequest + '  , with error : ' + error.message);
                    })
                    /*****************************/
                    /**    LE FICHIER DE HASH CODE    **/
                    /** CONTIENT LE HASH CODE    **/
                    /**    DU FICHIER CHARGE.        **/
                    /*****************************/
                    api['get'](hash_code_file, null,  {'Cache-Control': 'no-store', 'Accept': 'text/plain', 'Content-Type': 'text/plain; charset=utf-8'}).then(function(response) {
                            if (response) {
                                    Response = response.clone();
                                    textJson(Response).then(function(text) {
                                            if(!EMPTY(text)) {
                                                    HashCodeResponse = text;
                                                    console.log('Succeded while fetching hash_code_file : ' + hash_code_file + ' with hash code : ' + HashCodeResponse);
                                                    console.log('HashCodeCache = ' + HashCodeCache);
                                                    console.log('HashCodeResponse = ' + HashCodeResponse);
                                                    if(HashCodeResponse !== null &&
                                                            HashCodeCache !== null &&
                                                            HashCodeResponse == HashCodeCache) {
                                                            /**********************/
                                                            /**    REPONSE DU CACHE **/
                                                            /**********************/
                                                            resolve(Response);
                                                    }
                                            } else {
                                                    console.log('hash_code_file empty or doesn\'t exist : ' + hash_code_file);
                                            }
                                    }, function(error) {
                                            console.log('Error while reading file : ' + fileRequest + '  , with error : ' + error.message);
                                    })
                            } else {
                                    console.log('Empty response while fetching hash code file : ' + hash_code_file);
                            }
                    }, function(error) {
                            console.log('The hash_code_file : ' + hash_code_file + '  , doesn\'t exist');
                    })
                    /*****************************/
                    /**       HASH CODE INVALIDE    **/
                    /**       ON LIT LE FICHIER    **/
                    /**        ET ON UPDATE        **/
                    /**        LE HASH CODE        **/
                    /*****************************/
                    api['get'](fileRequest, null, requestHeaders).then(function(response) {
                            if (response) {
                                    Response = response.clone();
                                    Response2 = response.clone();
                                    textJson(Response).then(function(text) {
                                            if(!EMPTY(text)) {
                                                    HashCodeResponse = forge_sha256(text);
                                                    console.log('Succeded while fetching file : ' + fileRequest + ' with hash code : ' + HashCodeResponse);
                                                    /*************************/
                                                    /**      ON MET EN CACHE    **/
                                                    /**        LE FICHIER        **/
                                                    /*************************/
                                                    cache.put(fileRequest, Response).then(function(result) {
                                                            console.log('file : ' + fileRequest + ' set to the cache.');
                                                    }, function(error) {
                                                            console.log('file : ' + fileRequest + ' not set in the cache, with error : ' + error.message);
                                                    })
                                                    /*************************/
                                                    /**        ON UPDATE        **/
                                                    /**        LE HASH CODE    **/
                                                    /*************************/
                                                    api['put'](hash_code_file, HashCodeResponse,  {'Cache-Control': 'no-store', 'Accept': 'text/plain', 'Content-Type': 'text/plain; charset=utf-8'}).then(function() {
                                                            console.log('Succeded while uploading hash_code_file : ' + hash_code_file + ' with hash code : ' + HashCodeResponse);
                                                    }, function(error) {
                                                            console.log('Error while uploading hash_code_file : ' + hash_code_file + ' with hash code : ' + HashCodeResponse + '  , with error : ' + error.message);
                                                    })
                                                    /************************/
                                                    /**    REPONSE DU FICHIER **/
                                                    /************************/
                                                    Response = Response2.clone();
                                                    resolve(Response);
                                            } else {
                                                    console.log('Empty file : ' + fileRequest);
                                                    Response = Response2.clone();
                                                    resolve(Response);
                                            }
                                    }, function(error) {
                                            reject('Error while fetching file : ' + fileRequest + ' with error : ' + error.message);
                                    })
                            } else {
                                    reject('Empty response while fetching file : ' + fileRequest);
                            }
                    }, function(error) {
                            reject('Error while fetching file : ' + fileRequest + ' with error : ' + error.message);
                    })
            }, function(error) {
                    reject('Error open cache : ' + CACHE + '  , with error : ' + error.message);
            })
    });
    }
    }
    
    class TEXT extends RESPONSE {
            constructor(request) {
                    /**********************************/
                    /** CETTE FONCTON REND JSON/TEXT **/
                    /**       SUIVANT LE CONTENT-TYPE    **/
                    /**            DE LA REPONSE.        **/
                    /**********************************/
                    var textJson = function(response) {
                            return new Promise(
                                    function (resolve, reject) {
                                            if(response) {
                                                    var Resp = response.clone();
                                                    if(Resp.ok) {
                                                            if (Resp.headers.get("content-type").match('application/json')) {
                                                                    resolve(Resp.json());
                                                            } else {
                                                                    resolve(Resp.text());
                                                            }
                                                    } else {
                                                            reject('Error with response Status : ' + Resp.status + ' : ' + Resp.statusText);
                                                    }
                                            } else {
                                                    reject('Response undefined');
                                            }
                                    }, function(error) {
                                            reject('Response with error : ' + error.message);
                                    });
                    };
                    return super(request).then(function(response) {
                            if (response) {
                                    return textJson(response);
                            } else {
                                    console.log('Empty response while reading file');
                                    return false;
                            }
                    }, function(error) {
                            console.log('Empty response while fetching file with error : ' + error.message);
                            return false;
                    })
            }
    }
    
    self.addEventListener('fetch', function(event) {
            // In a real app, you'd use a more sophisticated URL check.
            //        if (event.request.url.match(/.*/)) {
            //        event.respondWith(FETCH(event.request.url));
            Request = event.request.clone();
            file = Request.url;
            event.waitUntil(
                    fetch(Request).then(function(response) {
                            if(!response) {
                                    console.log('Response empty FETCHING file : ' + file);
                            }
                            return response;
                    }, function(error) {
                            console.log('Error while FETCHING file, with error : ' + error.message);
                            return false;
                    })
            );
    });
    
    staticAssets = [
            './',
            './index.html',
            './app.js',
            './styles.css'
    ];
    
    function initialize() {
            file = staticAssets[1];
            Text = new TEXT(file).then(function(text) {
                    if(text) {
                            console.log('Succeded while fetching file : ' + file + '  , with text : ' + text);
                    } else {
                            console.log('Empty file : ' + file + '  , with text : ' + text);
                    }
            }, function(error) {
                    console.log('Error while fetching file, with error : ' + error.message);
            })
    }
    
    /******************************/
    /**    INSTALL APP DEPENDENCIES **/
    /******************************/
    self.addEventListener('install', function(event) {
            console.log('The service worker is being installed.');
            // Bypass the waiting lifecycle stage,
            // just in case there's an older version of this SW registration.
            event.waitUntil(self.skipWaiting());
    });
    
    //allow sw to control of current page
    /*****************************/
    /**    CLEANUP THE RESOURCES    **/
    /*****************************/
    self.addEventListener('activate', function(event) {
            console.log('Claiming clients for current page');
            // Take control of all pages under this SW's scope immediately,
            // instead of waiting for reload/navigation.
            event.waitUntil(self.clients.claim());
            initialize();
    });
    
    
     
Chargement...
Similar Threads - static possible méthode Forum Date
Charger mes fonts via "fonts.gstatic.com" ou les héberger sois même ? Développement d'un site Web ou d'une appli mobile 21 Février 2017
Static HTML ?? Facebook 8 Juillet 2015
Application Facebook ou Static FBML ? Facebook 30 Octobre 2011
Static FBML et HTML Facebook 25 Octobre 2011
There are 7 static components without a far-future expiration date. URL Rewriting et .htaccess 12 Avril 2011
Personnalisation onglet Static FBML Facebook 13 Février 2011
Servir le contenu static à partir d'un domaine sans cookie sans risque de duplicate ? Développement d'un site Web ou d'une appli mobile 13 Août 2010
Est-il possible d'estimer le nombre de truviews sur youtube ads ? AdWords 6 Juin 2021
Impossible de créer un nom d'utilisateur sur ma page FB Facebook 26 Octobre 2020
Impossible de faire une redirect 301 ou permanent URL Rewriting et .htaccess 22 Octobre 2020