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

@mobi4tech/config-client

v1.4.0

Published

Cliente TypeScript agnóstico para o Mobitech Config Server

Downloads

383

Readme

@mobi4tech/config-client

Cliente TypeScript para consumir configurações do Mobitech Config Server.
Ele busca variables, secrets, flags e images, com suporte a cache e retry automático.

O que esta biblioteca resolve

Use este pacote quando sua aplicação precisar:

  • buscar configuração em tempo de execução;
  • centralizar secrets e feature flags;
  • evitar chamadas repetidas com cache;
  • tolerar falhas temporárias com retry.

Instalação

yarn add @mobi4tech/config-client
# ou
npm install @mobi4tech/config-client

Uso básico

import { MobiConfigClient } from '@mobi4tech/config-client';

const client = new MobiConfigClient({
  baseUrl: 'https://seu-config-server.com',
  token: 'seu-token-aqui',
});

const apiUrl = await client.getVariable('API_URL');
const apiKey = await client.getSecret('API_KEY');
const darkMode = await client.getFlag('DARK_MODE');
const bannerUrl = await client.getImage('banner-home');

// valor padrão opcional quando a chave não existir
const env = await client.getVariable('NODE_ENV', 'development');
const maintenance = await client.getFlag('MAINTENANCE_MODE', false);

Opções de configuração

new MobiConfigClient({
  baseUrl: 'https://seu-config-server.com',
  token: 'seu-token-aqui',
  cacheTtlMs: 60_000,
  timeout: 5_000,
  retry: {
    attempts: 3,
    delayMs: 500,
    backoff: 'exponential',
  },
});

Contrato esperado da API

O client consome GET /config/me e espera uma resposta neste formato:

{
  "variables": { "API_URL": "https://api.exemplo.com" },
  "secrets": { "API_KEY": "secret-123" },
  "flags": { "DARK_MODE": false },
  "images": [
    { "nome": "banner-home", "url": "https://cdn.exemplo.com/banner.png" }
  ]
}

Valores vazios em variables e secrets são aceitos. flags deve conter booleanos.

Integração com NestJS

Crie um provider global para compartilhar o client na aplicação.

// config-client.module.ts
import { Global, Module } from '@nestjs/common';
import { MobiConfigClient } from '@mobi4tech/config-client';

@Global()
@Module({
  providers: [
    {
      provide: MobiConfigClient,
      useFactory: () =>
        new MobiConfigClient({
          baseUrl: process.env.CONFIG_SERVER_URL!,
          token: process.env.CONFIG_SERVER_TOKEN!,
          cacheTtlMs: 30_000,
        }),
    },
  ],
  exports: [MobiConfigClient],
})
export class ConfigClientModule {}

Use o client em qualquer service:

import { Injectable } from '@nestjs/common';
import { MobiConfigClient } from '@mobi4tech/config-client';

@Injectable()
export class PaymentService {
  constructor(private readonly configClient: MobiConfigClient) {}

  async getStripeKey() {
    return this.configClient.getSecret('STRIPE_SECRET_KEY');
  }
}

Se preferir, você também pode injetar um transport personalizado no construtor para facilitar testes e mocks avançados.

Integração com React

Crie uma instância única e use dentro de hooks ou services de frontend.

// src/lib/configClient.ts
import { MobiConfigClient } from '@mobi4tech/config-client';

export const configClient = new MobiConfigClient({
  baseUrl: import.meta.env.VITE_CONFIG_SERVER_URL,
  token: import.meta.env.VITE_CONFIG_SERVER_TOKEN,
  cacheTtlMs: 60_000,
});
// src/components/Banner.tsx
import { useEffect, useState } from 'react';
import { configClient } from '../lib/configClient';

export function Banner() {
  const [imageUrl, setImageUrl] = useState<string | null>(null);

  useEffect(() => {
    configClient.getImage('banner-home').then(setImageUrl).catch(() => {
      setImageUrl(null);
    });
  }, []);

  if (!imageUrl) return null;

  return <img src={imageUrl} alt="Banner" />;
}

API disponível

  • getVariable(key) retorna Promise<string>
  • getSecret(key) retorna Promise<string>
  • getFlag(key) retorna Promise<boolean>
  • getImage(name) retorna Promise<string>
  • todos os getters aceitam um defaultValue opcional
  • getAll() retorna Promise<ResolvedConfig>
  • refresh() força uma nova leitura do servidor
  • invalidateCache() força nova busca no próximo acesso

Estrutura do projeto

  • src/client.ts implementa o client principal.
  • src/types.ts contém os tipos públicos.
  • src/index.ts exporta a API pública.
  • dist/ é gerado no build e não deve ser editado manualmente.

Desenvolvimento

yarn build   # compila TypeScript para dist/
yarn dev     # recompila em modo watch
yarn clean   # remove dist/

Licença

MIT