@goatlab/typesense
Version:
Modern TypeScript wrapper for Typesense search engine API
98 lines • 3.26 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ClientDestroyedError = exports.TypesenseError = void 0;
exports.isValidDocumentId = isValidDocumentId;
exports.validateTextMatches = validateTextMatches;
exports.validateVectorQuery = validateVectorQuery;
/**
* Enhanced error class for Typesense API errors with rate limit and response details
*/
class TypesenseError extends Error {
status;
statusText;
response;
rateLimitRemaining;
rateLimitReset;
retryAfter;
rateLimitLimit;
constructor(message, status, response, headers) {
super(message);
this.name = 'TypesenseError';
this.status = status;
this.statusText = status.toString();
this.response = response;
// Extract rate limit information from headers (Typesense format)
if (headers) {
const remaining = headers['X-RateLimit-Remaining'];
const resetMs = headers['X-RateLimit-ResetMs']; // Typesense uses milliseconds
const retryAfter = headers['Retry-After'];
const limit = headers['X-RateLimit-Limit'];
if (remaining)
this.rateLimitRemaining = parseInt(remaining, 10);
if (resetMs)
this.rateLimitReset = new Date(parseInt(resetMs, 10));
if (retryAfter)
this.retryAfter = parseInt(retryAfter, 10);
if (limit)
this.rateLimitLimit = parseInt(limit, 10);
}
}
/**
* Check if this error is due to rate limiting
*/
isRateLimited() {
return this.status === 429;
}
/**
* Get the time until rate limit reset (in milliseconds)
*/
getTimeUntilReset() {
if (!this.rateLimitReset)
return null;
return Math.max(0, this.rateLimitReset.getTime() - Date.now());
}
}
exports.TypesenseError = TypesenseError;
/**
* Type guard to check if a value is a valid document ID
*/
function isValidDocumentId(id) {
return (typeof id === 'string' && id.length > 0) || (typeof id === 'number' && !isNaN(id));
}
/**
* Validates text_matches parameter against per_page
*/
function validateTextMatches(textMatches, perPage) {
return textMatches <= perPage;
}
/**
* Validates vector search parameters
*/
function validateVectorQuery(query) {
const errors = [];
if (query.vector_query) {
// Vector queries cannot use pagination
if (query.page !== undefined || query.per_page !== undefined) {
errors.push('vector_query cannot be used with page or per_page parameters');
}
// Validate text_matches if present
if (query.text_matches && query.per_page && query.text_matches > query.per_page) {
errors.push('text_matches must be less than or equal to per_page');
}
}
return {
valid: errors.length === 0,
errors
};
}
/**
* Error thrown when client is destroyed
*/
class ClientDestroyedError extends Error {
constructor() {
super('TypesenseApi has been destroyed and cannot be used');
this.name = 'ClientDestroyedError';
}
}
exports.ClientDestroyedError = ClientDestroyedError;
//# sourceMappingURL=typesense.model.js.map