npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@app-masters/js-lib

v1.2.23

Published

JS lib

Downloads

271

Readme

JS-Lib

Http

App Masters fetch class.

Configuration

On the project setup, set the base url for your API and the necessary headers:

import { Http } from '@app-masters/js-lib';

...

const version = '1.0.0'; // get from package.json
const client = 'mobile'; // use 'mobile', 'admin' or 'web'
const env = 'development'; // use 'development', 'staging' or 'production'
const contentType = 'application/json';
const baseURL = 'http://localhost.com:3000';
const token = 'JWT-0000000000000'; // user's authentication token

Http.setup(version, client, env, contentType);
Http.setBaseURL(baseURL);

// after the authentication process
Http.setAuthorization(token);

Setting your headers like this, will give you this headers:

{
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'mobile-version': '1.0.0',
    'client': 'mobile',
    'client-env': 'development',
    'authorization': 'JWT-0000000000000'
}

Also, you can set a endpoint param. This param is a key/value that will overwrite the key with the value every time that it's found in a fetch call.

Examples:


Http.setEndpointParam('{_userID}', user.id);
Http.setEndpointParam('{_maxItems}', 5);

...

Http.get('/{_userID)');
Http.get('/items/?quantity={_maxItems}');

Anytime you can reset the headers to the default setup using Http.reset(). This will reset your headers to what was set in Http.setup(), removing the authorization and all endpoint parameters.

Usage

The Http class have 4 main asynchronous methods for fetch: GET, POST, PUT and DELETE. After you set the base URL, you only need to pass the endpoint to fetch it.

Examples:


Http.get('/users').then(response => {
    console.log(response);
}).catch(error => {
    console.error(error);
});

// Using endpoint params
Http.get('/users/{_userID}').then(response => {
    console.log(response);
}).catch(error => {
    console.error(error);
});

Http.post('/users', {email: '[email protected]'}).then(response => {
    console.log(response);
}).catch(error => {
    console.error(error);
});

// Full URLs ignore the baseURL set.
Http.post('http://localhost.com:3001/otherUsers', {email: '[email protected]'}).then(response => {
    console.log(response);
}).catch(error => {
    console.error(error);
});

Http.put('/users/TH1S154U53R1D', {email: '[email protected]'}).then(response => {
    console.log(response);
}).catch(error => {
    console.error(error);
});

Http.delete('/users/TH1S154U53R1D').then(response => {
    console.log(response);
}).catch(error => {
    console.error(error);
});

The status codes considered as success are: 200, 201 and 204 (on delete).

AppBoostrap

App Masters default app setup process.

Create a config file with defaults environments:


const envs = {};

envs.development = {
    baseUrl: "http://localhost:3000/api",
    uploadCareToken: "someXPTOtoken",
    rollbarToken: "anotherCrazyToken"
};

envs.development_firebase = {
    baseUrl: "https://remotehost-dev.herokuapp.com:3000/api",
    uploadCareToken: "someXPTOtoken",
    rollbarToken: "anotherCrazyToken"
};

envs.staging = {
    baseUrl: "https://remotehost-staging.herokuapp.com:3000/api",
    uploadCareToken: "someXPTOtoken",
    rollbarToken: "anotherCrazyToken"
};

envs.production = {
    baseUrl: "https://remotehost-prod.herokuapp.com:3000/api",
    uploadCareToken: "someXPTOtoken",
    rollbarToken: "anotherCrazyToken"
};

export default envs;

Import and call AppBootstrap:

import {store, storage} from './store';
import packag from '../package.json';
import envs from './config';
import {AppBootstrap} from '@app-masters/js-lib';

class App extends Component {
    constructor () {
        super();
        try {
            let callbacks = {
                onMinVersionNotSatisfies: (version) => {
                    alert("Você deve atualizar sua versão agora! Por favor recarregue a página, se a mensagem continuar, limpe o cache do navegador.");
                },
                onNewVersion: (version) => {
                    alert('Bem vindo à nova versão!');
                    if (version === '0.2.0') {
                      // Some new version decision
                    }
                },
                onUncaughtError: (e) => {
                    if (e.message !== 'Failed to fetch') {
                        Rollbar.error(e);
                        alert("Houve um erro inesperado e os programadores responsáveis já foram avisados. \n\n Detalhes técnicos: " + e.message);
                    } else {
                        alert('Falha na conexāo');
                    }
                }
            };

            // Bootstrap
            AppBootstrap.setup("web", packag, envs, storage, callbacks);
        } catch (e) {
            alert("Houve um erro inesperado e os programadores responsáveis já foram avisados. \n\n Detalhes técnicos: " + e.message);
        }
    }
}

(callbacks are the same object used with AMActions.setup()).

Notification (web)

Service worker configuration

  • Create a file called 'firebase-messaging-sw.js' with the following content and put it on the public path of the project (generaly it is project-folder/public):
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/4.8.1/firebase-messaging.js');
firebase.initializeApp({
    messagingSenderId: "1072711350296"
});
const Notifier = firebase.messaging();
Notifier.setBackgroundMessageHandler(function(payload) {
    console.log('[firebase-messaging-sw.js] Received background message ', payload);
    // Customize notification here
    const notificationTitle = 'Background Message Title';
    const notificationOptions = {
        body: 'Background Message body.',
        icon: '/firebase-logo.png'
    };
    return self.registration.showNotification(notificationTitle, notificationOptions);
});
  • Add the following line on the index.html before the closing tag: </html>
<html>
    <head>...</head>
    <body>...</body>
    <!-- add this script -->
    <script src="https://www.gstatic.com/firebasejs/4.4.0/firebase.js"></script>
</html>

Firebase initialize and lib setup

  • Initialize the firebase and then setup the notification lib
// initializing the firebase
firebase.initializeApp({
    apiKey: '',
    authDomain: '',
    databaseURL: '',
    projectId: '',
    storageBucket: '',
    messagingSenderId: ''
});
// lib setup
Notification.setup(firebase);
Notification.getToken((token) => console.log('It has the token! Notification should work fine', token));
Notification.handleMessage((message) => {console.log('message received -> ', message)}, console.error);

Lib methods

setup

  • Receives the config param (can be a firebase instance or config params to set the cordova firebase plugin for example), sets the device info (cordova, web, native) and finnaly sets the messaging (object used to make all the firebase calls).

Change Log

Check all changes on changelog.