hosby-ts
v1.4.4
Published
TypeScript client library to consume APIs created on Hosby.
Maintainers
Readme
hosby-ts
TypeScript client library for consuming APIs created on the Hosby Backend-as-a-Service platform.
Features
- 🔒 Secure Authentication: RSA signature verification, CSRF protection, and JWT token management
- 🔄 Complete CRUD Operations: Comprehensive set of methods for creating, reading, updating, and deleting data
- 📊 Advanced Querying: Filter, sort, populate, and paginate your data with a simple interface
- 📘 Strong TypeScript Support: Fully typed API for better developer experience and code safety
- 🚀 Modern JavaScript: Built with modern JavaScript features and ES modules support
Installation
# Using npm
npm install hosby-ts
# Using yarn
yarn add hosby-ts
# Using pnpm
pnpm add hosby-tsQuick Start
import { HosbyClient } from "hosby-ts";
class HosbyQuery {
private readonly _client: HosbyClient;
private isInitialized = false;
constructor() {
this._client = new HosbyClient({
baseURL: process.env.HOSBY_BASE_URL || "",
privateKey: process.env.HOSBY_PRIVATE_KEY || "",
apiKeyId: process.env.HOSBY_API_KEY_ID || "",
projectName: process.env.HOSBY_PROJECT_NAME || "",
projectId: process.env.HOSBY_PROJECT_ID || "",
userId: process.env.HOSBY_USER_ID || "",
});
this.initialize().catch(error => {
console.error("Failed to initialize Hosby client:", error);
throw new Error("Hosby client initialization failed");
});
}
private async initialize(): Promise<void> {
if (this.isInitialized) return;
try {
await this._client.init();
this.isInitialized = true;
console.log("Hosby client initialized successfully");
} catch (error) {
console.error("Error initializing Hosby client:", error);
throw new Error("Failed to initialize Hosby client. Check your connection and credentials.");
}
}
public get client(): HosbyClient {
if (!this.isInitialized) {
throw new Error("Hosby client not initialized. Ensure the service is loaded before use.");
}
return this._client;
}
}
export const hosbyQuery = new HosbyQuery().client;CRUD Operations
Read Operations
// Find multiple documents
const users = await client.find<User[]>('users');
// Find by ID
const user = await client.findById<User>(
'users',
[{ field: 'id', value: '123456789' }]
);
// Find by email
const userByEmail = await client.findByEmail<User>(
'users',
[{ field: 'email', value: '[email protected]' }]
);
// Count documents
const count = await client.count<{ count: number }>(
'users',
[{ field: 'active', value: true }]
);Create Operations
// Create a single document
const newUser = await client.insertOne<User>(
'users',
{
name: 'John Doe',
email: '[email protected]',
active: true
}
);
// Create multiple documents
const newUsers = await client.insertMany<User[]>(
'users',
[
{ name: 'John', email: '[email protected]', active: true },
{ name: 'Jane', email: '[email protected]', active: true }
]
);
// Upsert (create or update)
const upsertedUser = await client.upsert<User>(
'users',
{ name: 'John Doe', email: '[email protected]', active: true },
[{ field: 'email', value: '[email protected]' }]
);Update Operations
// Update a document
const updatedUser = await client.updateOne<User>(
'users',
{ active: false },
[{ field: 'id', value: '123456789' }],
);
// Update multiple documents
const result = await client.updateMany<{ modifiedCount: number }>(
'users',
{ active: false },
[{ field: 'role', value: 'guest' }]
);
// Find and update
const foundAndUpdated = await client.findOneAndUpdate<User>(
'users',
{ lastLoginDate: new Date() },
[{ field: 'email', value: '[email protected]' }],
);Delete Operations
// Delete a document
const deletedUser = await client.deleteOne<User>(
'users',
[{ field: 'id', value: '123456789' }]
);
// Delete multiple documents
const deleteResult = await client.deleteMany<{ deletedCount: number }>(
'users',
[{ field: 'active', value: false }]
);
// Find and delete
const foundAndDeleted = await client.findOneAndDelete<User>(
'users',
[{ field: 'email', value: '[email protected]' }]
);Advanced Usage
Query Filters
// Simple filter
[{ field: 'status', value: 'active' }]
// Multiple filters (AND condition)
[
{ field: 'role', value: 'admin' },
{ field: 'active', value: true }
]Query Options
// Pagination
{ skip: 10, limit: 10 }
// Population of referenced fields
{ populate: ['author', 'comments'] }
// Advanced query with operators
{
query: {
createdAt: { $gt: '2023-01-01' },
status: { $in: ['active', 'pending'] }
}
}Secure Configuration
import { createClient, SecureClientConfig } from 'hosby-ts';
const secureConfig: SecureClientConfig = {
baseURL: 'https://api.hosby.io',
privateKey: 'your-private-key',
apiKeyId: 'your-api-key-id',
projectName: 'your-project-name',
projectId: 'your-project-id',
userId: 'your-user-id',
// Advanced security options
httpsMode: 'strict',
httpsExemptHosts: ['localhost', '127.0.0.1'],
timeout: 5000,
retryAttempts: 3
};
const client = createClient(secureConfig);API Response Format
All methods return a standardized response object:
interface ApiResponse<T> {
success: boolean; // Whether the request was successful
status: number; // HTTP status code
message: string; // Response message
data: T; // Typed response data
}Error Handling
try {
const response = await client.find<User[]>('users');
if (response.success) {
// Handle successful response
const users = response.data;
} else {
// Handle unsuccessful response
console.error(`API Error: ${response.message} (${response.status})`);
}
} catch (error) {
// Handle unexpected errors
console.error('Unexpected error:', error);
}License
This project is licensed under the MIT License - see the LICENSE file for details.
Contributing
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
