nikvector-js
v1.0.0
Published
Production-ready TypeScript SDK for Vector Context DB - Multi-tenant vector database with AI pattern recognition
Maintainers
Readme
nikvector-js
Production-ready TypeScript SDK for Vector Context DB - A multi-tenant vector database platform with built-in AI pattern recognition.
Features
- 🔐 Complete Authentication - Sign up, sign in, password management
- 🏢 Multi-Tenant Support - Manage multiple projects with isolated data
- 🔑 API Key Management - Create, rotate, and revoke API keys with role-based scopes
- 🔍 Vector Search - Semantic search with pgvector
- 🤖 AI Operations - Query suggestions and template execution
- 📊 GraphQL API - Flexible data queries with Apollo Client
- 🔄 Retry Logic - Automatic retry with exponential backoff
- ⏱️ Request Timeout - Configurable timeouts with AbortController
- 🐛 Debug Mode - Detailed logging for development
- 📦 Batch Operations - Efficient bulk indexing and deletion
- 💪 TypeScript - Full type safety with TypeScript
Installation
npm install nikvector-js
# or
yarn add nikvector-js
# or
pnpm add nikvector-jsQuick Start
import { createClient } from 'nikvector-js';
// Create client
const client = createClient({
url: 'https://your-instance.vercel.app',
anonKey: process.env.VECTOR_DB_ANON_KEY, // Optional
tenantId: 'your-tenant-id', // Optional
debug: true, // Enable debug logging
maxRetries: 3, // Retry failed requests
timeout: 30000, // 30 second timeout
});
// Sign up
const session = await client.auth.signUp('[email protected]', 'password', 'John Doe');
// Sign in
const { user, access_token } = await client.auth.signIn('[email protected]', 'password');
// Create a project
const project = await client.tenants.create('My Project', 'my-project');
// Select tenant for operations
client.tenants.select(project.id);
// Index content
const doc = await client.vector.index({
text: 'Vector databases are essential for AI applications',
source: 'document.pdf',
metadata: { category: 'AI', tags: ['vector', 'database'] },
});
// Search vectors
const results = await client.vector.query({
query: 'What are vector databases?',
threshold: 0.7,
limit: 10,
});
console.log(results);Authentication
Sign Up
const session = await client.auth.signUp(
'[email protected]',
'secure-password',
'Display Name' // Optional
);
console.log('User:', session.user);
console.log('Access Token:', session.access_token);Sign In
const session = await client.auth.signIn('[email protected]', 'password');Get Current User
const user = await client.auth.getUser();
if (user) {
console.log('Logged in as:', user.email);
}Change Password
await client.auth.changePassword('old-password', 'new-password');Sign Out
client.auth.signOut();Multi-Tenant Operations
List Projects
const projects = await client.tenants.list();
projects.forEach(project => {
console.log(`${project.name} (${project.slug})`);
});Create Project
const project = await client.tenants.create('My New Project', 'my-new-project');
console.log('Created:', project.id);Get Project Details
const project = await client.tenants.get('project-id');
console.log(project.name, project.databaseUrl);Select Tenant
// All vector operations will use this tenant
client.tenants.select('project-id');
// Get current tenant
const currentTenantId = client.tenants.getCurrent();API Key Management
Create API Key
// With default scopes based on role
const key = await client.apiKeys.create({
tenantId: 'project-id',
name: 'Production Key',
role: 'SERVICE', // ANON, SERVICE, or ADMIN
});
console.log('API Key:', key.raw); // Save this securely!
console.log('Prefix:', key.prefix);
console.log('Scopes:', key.scopes);Custom Scopes
const key = await client.apiKeys.create({
tenantId: 'project-id',
name: 'Custom Key',
role: 'SERVICE',
scopes: ['graphql.read', 'vector.read', 'vector.write'],
});Default Scopes by Role
- ANON:
['graphql.read', 'vector.read'] - SERVICE:
['graphql.read', 'graphql.write', 'vector.read', 'vector.write', 'graphql.execute'] - ADMIN: All scopes including
'admin'
List API Keys
// List all keys
const keys = await client.apiKeys.list();
// List keys for specific tenant
const tenantKeys = await client.apiKeys.list('tenant-id');
keys.forEach(key => {
console.log(`${key.name}: ${key.prefix}...${key.lastFour}`);
});Revoke API Key
await client.apiKeys.revoke('key-id');Rotate API Key
const newKey = await client.apiKeys.rotate('old-key-id');
console.log('New key:', newKey.raw);Vector Operations
Index Document
const doc = await client.vector.index({
text: 'Your document content here',
source: 'document.pdf',
metadata: {
category: 'technical',
author: 'John Doe',
tags: ['ai', 'ml'],
},
});Batch Indexing
const documents = [
{ text: 'First document', metadata: { id: 1 } },
{ text: 'Second document', metadata: { id: 2 } },
{ text: 'Third document', metadata: { id: 3 } },
];
const results = await client.vector.indexBatch(documents);
console.log(`Indexed ${results.length} documents`);Search Vectors
const results = await client.vector.query({
query: 'machine learning applications',
threshold: 0.7, // Minimum similarity (0-1)
limit: 10, // Max results
});
results.forEach(result => {
console.log(`Similarity: ${result.similarity}`);
console.log(`Content: ${result.content}`);
console.log(`Metadata:`, result.metadata);
});Delete Document
const success = await client.vector.delete('document-id');Batch Delete
const ids = ['doc-1', 'doc-2', 'doc-3'];
const success = await client.vector.deleteBatch(ids);GraphQL Operations
Direct GraphQL Query
const data = await client.db.graphql(`
query {
documents {
id
source
metadata
createdAt
}
}
`);With Variables
const data = await client.db.query(
`
query GetDocument($id: ID!) {
document(id: $id) {
id
source
chunks {
content
}
}
}
`,
{ id: 'document-id' }
);GraphQL Mutation
const data = await client.db.mutate(
`
mutation CreateDocument($input: IndexTextInput!) {
indexText(input: $input) {
id
source
}
}
`,
{
input: {
text: 'Document content',
source: 'file.txt',
},
}
);AI Operations
Query Suggestions
const suggestions = await client.ai.suggestQuery('how to use the API', 5);
suggestions.forEach(template => {
console.log(`${template.name}: ${template.description}`);
console.log(`Similarity: ${template.similarity}`);
});Run Template
const result = await client.ai.runTemplate('template-id', {
category: 'technical',
limit: 10,
});
console.log('Query:', result.finalQuery);
console.log('Results:', result.result);
console.log('Latency:', result.latencyMs, 'ms');Error Handling
The SDK provides a comprehensive error handling system:
import { VectorDBError } from 'nikvector-js';
try {
await client.vector.query({ query: 'test' });
} catch (error) {
if (error instanceof VectorDBError) {
console.error('Error code:', error.code);
console.error('Status:', error.statusCode);
console.error('Message:', error.message);
console.error('Details:', error.details);
// Handle specific errors
switch (error.code) {
case 'UNAUTHORIZED':
// Refresh token or redirect to login
break;
case 'RATE_LIMITED':
// Wait and retry
break;
case 'NOT_FOUND':
// Resource doesn't exist
break;
default:
// Handle other errors
}
}
}Error Codes
UNAUTHORIZED(401): Invalid or expired credentialsFORBIDDEN(403): Insufficient permissionsNOT_FOUND(404): Resource not foundCONFLICT(409): Resource already existsRATE_LIMITED(429): Rate limit exceededSERVER_ERROR(500+): Server-side errorTIMEOUT(408): Request timeoutNETWORK_ERROR: Network connectivity issueGRAPHQL_ERROR: GraphQL query/mutation error
Retry Logic
The SDK automatically retries failed requests:
const client = createClient({
url: 'https://your-instance.vercel.app',
maxRetries: 3, // Number of retry attempts (default: 3)
retryDelay: 1000, // Initial delay in ms (default: 1000)
});- Automatic retry for 429 (rate limit) and 5xx errors
- Exponential backoff:
delay * (2 ^ attempt) - Respects
Retry-Afterheader for rate limits - Network errors are also retried
Request Timeout
Configure request timeouts to prevent hanging:
const client = createClient({
url: 'https://your-instance.vercel.app',
timeout: 30000, // 30 seconds (default)
});Requests are automatically cancelled after the timeout using AbortController.
Debug Mode
Enable debug logging for development:
const client = createClient({
url: 'https://your-instance.vercel.app',
debug: true,
});Debug mode logs:
- All HTTP requests and responses
- Request/response timing
- Retry attempts
- GraphQL operations
Advanced Usage
Custom Apollo Client Configuration
The SDK uses Apollo Client for GraphQL operations with optimized defaults:
fetchPolicy:network-only(always fetch fresh data)errorPolicy:all(return partial data with errors)- Automatic authentication headers
- Request/response caching
Working with Multiple Tenants
// Create client
const client = createClient({ url: 'https://your-instance.vercel.app' });
// Sign in
await client.auth.signIn('[email protected]', 'password');
// List projects
const projects = await client.tenants.list();
// Switch between projects
for (const project of projects) {
client.tenants.select(project.id);
// Perform operations on this project
const results = await client.vector.query({
query: 'search query',
limit: 5,
});
console.log(`Results for ${project.name}:`, results.length);
}Using with API Keys
// Create client with API key (no authentication needed)
const client = createClient({
url: 'https://your-instance.vercel.app',
anonKey: 'your-service-api-key',
tenantId: 'your-tenant-id',
});
// Direct access to vector operations
const results = await client.vector.query({
query: 'search query',
});Best Practices
- Store API Keys Securely: Never commit API keys to version control
- Use Environment Variables: Store configuration in environment variables
- Enable Debug Mode: Use debug mode during development
- Handle Errors: Always handle errors gracefully
- Batch Operations: Use batch operations for multiple documents
- Select Tenant: Always select a tenant before vector operations
- Retry Configuration: Adjust retry settings based on your use case
- Monitor Usage: Track API usage and implement rate limiting on your side
TypeScript Support
The SDK is written in TypeScript and provides complete type definitions:
import {
VectorNikVectorsClient,
VectorNikVectorsClientOptions,
VectorDBError,
User,
Tenant,
ApiKey,
Document,
SearchResult,
QueryTemplate,
} from 'nikvector-js';Examples
See the /examples directory for complete examples:
- RAG Application
- Chatbot with Vector Search
- Multi-Tenant SaaS
- API Key Management
- Batch Processing
API Reference
Full API documentation is available at https://docs.vectorcontextdb.com
Building from Source
# Install dependencies
npm install
# Build
npm run build
# Output: dist/index.js and dist/index.d.tsPublishing
# Update version in package.json
npm version 1.0.0
# Build
npm run build
# Publish to npm
npm publish --access publicContributing
Contributions are welcome! Please read our Contributing Guide for details.
License
MIT
Support
- 📧 Email: [email protected]
- 💬 Discord: Join our community
- 📖 Documentation: https://docs.vectorcontextdb.com
- 🐛 Issues: GitHub Issues
