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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@opens/accesshub-frontend

v0.0.2

Published

Frontend client for AccessHub resources with localStorage caching

Downloads

5

Readme

AccessHub Client

Biblioteca leve e eficiente para acessar recursos de empresas com cache no navegador.

Recursos

  • ⚡️ Rápida e eficiente
  • 🔄 Cache automático com TTL configurável
  • 🛡️ Fallback para dados em cache quando a API falha
  • 🧩 API limpa e intuitiva
  • 📱 Suporta browsers modernos
  • 🔧 Totalmente tipada (TypeScript)

Instalação

npm install @opens/accesshub-client

Uso Básico

import { ResourceClient } from '@opens/accesshub-client';

// Criar uma instância do cliente
const client = new ResourceClient({
  accessHubURL: 'https://api.example.com/api',
  token: 'your-auth-token',
});

// Obter todos os recursos de uma empresa
const response = await client.getCompanyResources('company-123');
const allResources = response.resources;

// Verificar a origem dos dados (cache, API, fallback)
if (response._metadata.fromCache) {
  console.log('Dados obtidos do cache');
}

// Limpar cache para uma empresa específica
await client.clearCache('company-123');

Integração com Vue

Exemplo Vue 2

// Em um componente Vue
export default {
  data() {
    return {
      resources: {},
      loading: true,
      error: null,
    };
  },

  async created() {
    const client = new ResourceClient({
      accessHubURL: process.env.VUE_APP_API_URL,
      token: this.$store.getters.token,
    });

    try {
      const response = await client.getCompanyResources('company-123');
      this.resources = response.resources;
    } catch (err) {
      this.error = err.message;
    } finally {
      this.loading = false;
    }
  },
};

Exemplo Vue 3 Composition API

import { ref, onMounted } from 'vue';
import { ResourceClient } from '@opens/accesshub-client';

export function useResources(companyId) {
  const resources = ref({});
  const loading = ref(true);
  const error = ref(null);

  const client = new ResourceClient({
    accessHubURL: import.meta.env.VITE_API_URL,
    token: localStorage.getItem('token'),
  });

  async function fetchResources() {
    loading.value = true;

    try {
      const response = await client.getCompanyResources(companyId);
      resources.value = response.resources;
    } catch (err) {
      error.value = err.message;
    } finally {
      loading.value = false;
    }
  }

  onMounted(fetchResources);

  return {
    resources,
    loading,
    error,
    refresh: fetchResources,
  };
}

Exemplo Nuxt 2

// Em uma página ou componente Nuxt
export default {
  data() {
    return {
      resources: {},
      loading: true,
    };
  },

  async fetch() {
    const client = new ResourceClient({
      accessHubURL: process.env.apiUrl,
      token: this.$auth.getToken(),
    });

    const response = await client.getCompanyResources('company-123');
    this.resources = response.resources;
    this.loading = false;
  },
};

Opções de Configuração

import { ResourceClient } from '@opens/accesshub-client';
import type { ClientConfig } from '@opens/accesshub-client';

// Configuração completa (todos os valores são opcionais)
const config: ClientConfig = {
  accessHubURL: 'https://api.example.com/api', // URL base da API
  cacheTTL: 300, // TTL do cache em segundos (padrão: 600)
  token: 'your-auth-token', // Token de autenticação opcional
};

const client = new ResourceClient(config);

Tratamento de Erros

O cliente lida com falhas de forma elegante:

try {
  const resources = await client.getCompanyResources('company-id');

  // Verificar se os dados vieram de fallback (API inacessível)
  if (resources._metadata.fromFallback) {
    console.warn('API inacessível, usando dados em cache');
  }
} catch (error) {
  console.error('Falha ao obter recursos:', error.message);
}

Compatibilidade com Navegadores

  • Chrome, Firefox, Edge, Safari (últimas 2 versões)
  • IE11 não é suportado

Uso com Bundlers

// Usando bundlers como webpack, rollup ou esbuild
import { ResourceClient } from '@opens/accesshub-client';

// Configuração é a mesma independente do ambiente
const client = new ResourceClient({
  accessHubURL: 'https://api.example.com/api',
  token: 'your-token',
});

API Completa

ResourceClient

| Método | Descrição | | ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | | getCompanyResources(companyId, requiredResources?) | Obtém todos os recursos de uma empresa. Opcionalmente, pode-se especificar quais recursos são obrigatórios | | clearCache(companyId?) | Limpa o cache para uma empresa específica (opcional) |

Tipos

// Configuração do cliente
interface ClientConfig {
  accessHubURL: string; // URL base da API
  cacheTTL: number; // Tempo de vida do cache em segundos
  token?: string; // Token de autenticação opcional
}

// Recurso
interface Resource {
  id: string;
  name: string;
  description: string;
  // ... outras propriedades
}

// Resposta da API
interface ResourceResponse {
  resources: Record<string, Resource>;
  _metadata: {
    fromCache: boolean; // Indica se veio do cache
    fromFallback: boolean; // Indica se é fallback por falha na API
    lastUpdated: string; // Data da última atualização
    expiredAt?: number; // Indica se o cache está expirado
  };
}