@quickly-desk/sdk
v0.0.2
Published
SDK para integração fácil do Quickly Desk em aplicações React e React Native
Maintainers
Readme
Quickly Desk SDK
SDK for easy integration of Quickly Desk in React and React Native applications.
Installation
npm install @quickly-desk/sdk
# or
yarn add @quickly-desk/sdkUsage
React (Web)
import React, { useMemo } from "react";
import {
QuicklyDeskProvider,
useCustomerAuth,
useChatsWithWebSocket,
} from "@quickly-desk/sdk";
function App() {
const config = useMemo(
() => ({
publicKey: "your-public-key",
customerReference: "unique-customer-id",
customerName: "Customer Name",
metadata: {
phone: "11999999999",
// other optional metadata
},
}),
[]
);
return (
<QuicklyDeskProvider config={config}>
<YourApp />
</QuicklyDeskProvider>
);
}function YourApp() { const { loading, error, signOut } = useCustomerAuth(); const { chats, messages, sendMessage, createChat } = useChatsWithWebSocket();
// Use the hooks as needed return ...; }
### React Native
```tsx
import React, { useMemo } from "react";
import {
QuicklyDeskProvider,
useCustomerAuth,
useChatsWithWebSocket,
} from "@quickly-desk/sdk";
function App() {
const config = useMemo(
() => ({
publicKey: "your-public-key",
customerReference: "unique-customer-id",
customerName: "Customer Name",
metadata: {
phone: "11999999999",
},
}),
[]
);
return (
<QuicklyDeskProvider config={config}>
<YourApp />
</QuicklyDeskProvider>
);
}Features
- No caching: The SDK always authenticates when the provider is executed
- Automatic token refresh: Tokens are automatically refreshed when expired
- Request queue: Failed requests are queued and retried after token refresh
- WebSocket support: Real-time chat functionality with WebSocket connections
API
Hooks
useCustomerAuth()
Hook for managing customer authentication.
const { loading, error, signOut } = useCustomerAuth();loading: Loading state during authentication (boolean)error: Error message if authentication fails (string | null)signOut(): Function to sign out manually
useChatsWithWebSocket()
Hook principal para gerenciar chats e mensagens. Gerencia automaticamente a conexão WebSocket com base no ciclo de vida do componente.
Características:
- ✅ Conecta automaticamente ao WebSocket quando o componente monta
- ✅ Aguarda a conexão WebSocket estar pronta antes de carregar chats
- ✅ Chama
loadChats()automaticamente após conectar - ✅ Desconecta automaticamente quando o componente desmonta (se for o último componente usando)
- ✅ Usa contador de referências para manter conexão durante navegação entre telas
- ✅ Proteção contra race conditions e múltiplas chamadas
- ✅ Tratamento robusto de erros e timeouts
- ✅ Pode ser usado em múltiplos componentes simultaneamente
const {
chats,
currentChat,
messages,
participants,
ws,
loading,
sendMessageLoading,
createChatLoading,
loadChats,
loadChatHistory,
sendMessage,
createChat,
} = useChatsWithWebSocket();Propriedades retornadas:
chats: Lista de chats (Chat[])currentChat: Chat atual selecionado (Chat | null)messages: Mensagens do chat atual (ChatMessage[])participants: Participantes ativos por chat ID ({ [id_chat: string]: { participants: string[]; typingStatus: { [id_user: string]: string } } })ws: Conexão WebSocket (WebSocket | null)loading: Estado de carregamento (boolean)sendMessageLoading: Estado de envio de mensagem (boolean)createChatLoading: Estado de criação de chat (boolean)loadChats(): Carrega lista de chatsloadChatHistory(id_chat): Carrega histórico de um chat específicosendMessage(id_chat, content): Envia uma mensagemcreateChat(): Cria um novo chat
Exemplos de uso:
// Tela de listagem de chats
function ChatsListScreen() {
const { chats, loading, loadChats, createChat } = useChatsWithWebSocket();
// WebSocket conecta automaticamente ao montar
// loadChats() é chamado automaticamente após conexão
// WebSocket desconecta automaticamente ao desmontar
const onRefresh = async () => {
await loadChats(); // Pode ser chamado manualmente para refresh
};
return (
<FlatList
data={chats}
renderItem={({ item }) => <ChatListItem chat={item} />}
onRefresh={onRefresh}
refreshing={loading}
/>
);
}
// Tela de chat individual
function ChatScreen({ id_chat }: { id_chat: string }) {
const { messages, loadChatHistory, sendMessage, loading } = useChatsWithWebSocket();
// Pode usar o mesmo hook - conexão WebSocket é compartilhada
// Não precisa gerenciar conexão manualmente
useEffect(() => {
if (id_chat) {
loadChatHistory(id_chat);
}
}, [id_chat, loadChatHistory]);
return (
<View>
<FlatList data={messages} renderItem={({ item }) => <MessageBubble message={item} />} />
<MessageInput onSend={(content) => sendMessage(id_chat, content)} />
</View>
);
}Types
interface Chat {
id_chat: string;
id_tenant: string;
id_customer: string;
created_at?: string;
updated_at?: string;
customer_name?: string;
last_message?: string | null;
last_message_time?: string | null;
unread_count?: number;
}
interface ChatMessage {
id_chat_message: number;
id_chat: string;
sender: string;
id_sender: string;
read: boolean;
content: string;
created_at?: string;
}Configuration
SDKConfig
interface SDKConfig {
apiUrl?: string; // API URL (optional)
wsUrl?: string; // WebSocket URL (optional)
publicKey: string; // Public key (required)
customerReference: string; // Unique customer ID (required)
customerName: string; // Customer name (required)
metadata?: Record<string, any>; // Optional metadata
}Authentication Flow
The SDK automatically:
- Authenticates when the provider is executed (calls
/auth/customer) - Stores the token in memory (no persistent storage)
- Refreshes the token automatically when it expires
- Queues failed requests during token refresh and retries them after refresh
Edge Cases e Comportamentos
Limites e Validações
- Tamanho máximo de mensagem: 5000 caracteres
- Tamanho máximo da fila de requisições: 50 requisições
- Timeout da fila: 30 segundos
- Timeout de conexão WebSocket: 10 segundos (padrão)
- Máximo de tentativas de retry WebSocket: 3 tentativas
- Máximo de mensagens processadas em memória: 100 IDs
Comportamentos Automáticos
- Reconexão WebSocket: O SDK reconecta automaticamente se a conexão fechar inesperadamente (code !== 1000)
- Prevenção de duplicatas: Mensagens duplicadas são automaticamente ignoradas usando um Set de IDs processados
- Validação de mensagens: Todas as mensagens WebSocket são validadas antes de serem processadas
- Retry automático: WebSocket tenta reconectar até 3 vezes com backoff exponencial (1s, 2s, 4s, max 10s)
- Limpeza de recursos: Todos os timeouts e listeners são limpos adequadamente ao desmontar componentes
Tratamento de Erros
O SDK classifica erros em tipos específicos:
NetworkError: Erros de conexão de redeTimeoutError: Timeouts de requisição ou conexãoAuthenticationError: Erros de autenticaçãoValidationError: Erros de validação de entrada
Múltiplos Componentes
Você pode usar useChatsWithWebSocket em múltiplos componentes simultaneamente:
- A conexão WebSocket é compartilhada entre todos os componentes
- Um contador de referências gerencia quando conectar/desconectar
- A conexão só fecha quando o último componente se desinscreve
Navegação entre Telas
- Ao navegar da lista de chats para um chat específico, a conexão WebSocket é mantida
- Ao sair da tela de listagem, a conexão fecha automaticamente
- Mensagens continuam chegando mesmo quando não está na tela de listagem (se outro componente estiver usando)
Troubleshooting
Para problemas comuns e soluções, consulte TROUBLESHOOTING.md.
License
MIT
