x-api-sdk-ts
Version:
TypeScript Library for the X (ex-twitter) API V2
66 lines • 2.57 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AuthenticationError = exports.RateLimitError = exports.TwitterAPIError = exports.TwitterError = void 0;
exports.parseTwitterError = parseTwitterError;
class TwitterError extends Error {
constructor(message, code) {
super(message);
this.code = code;
this.name = 'TwitterError';
Object.setPrototypeOf(this, TwitterError.prototype);
}
}
exports.TwitterError = TwitterError;
class TwitterAPIError extends TwitterError {
constructor(message, code, errors) {
super(message, code);
this.errors = errors;
this.name = 'TwitterAPIError';
Object.setPrototypeOf(this, TwitterAPIError.prototype);
}
}
exports.TwitterAPIError = TwitterAPIError;
class RateLimitError extends TwitterError {
constructor(message, resetTime) {
super(message, 429);
this.resetTime = resetTime;
this.name = 'RateLimitError';
Object.setPrototypeOf(this, RateLimitError.prototype);
}
}
exports.RateLimitError = RateLimitError;
class AuthenticationError extends TwitterError {
constructor(message) {
super(message, 401);
this.name = 'AuthenticationError';
Object.setPrototypeOf(this, AuthenticationError.prototype);
}
}
exports.AuthenticationError = AuthenticationError;
function parseTwitterError(error) {
var _a, _b, _c;
if (error instanceof TwitterError) {
return error;
}
if (!error.response) {
return new TwitterError(error.message || 'Unknown error');
}
const { status, data, headers } = error.response;
if (status === 429) {
const resetTime = headers['x-rate-limit-reset']
? new Date(parseInt(headers['x-rate-limit-reset'], 10) * 1000)
: undefined;
return new RateLimitError('Twitter API rate limit exceeded', resetTime);
}
if (status === 401) {
return new AuthenticationError(data.error || ((_b = (_a = data.errors) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.message) || 'Authentication failed');
}
if (data.errors && Array.isArray(data.errors)) {
return new TwitterAPIError(((_c = data.errors[0]) === null || _c === void 0 ? void 0 : _c.message) || 'Twitter API error', status, data.errors);
}
if (data.error) {
return new TwitterAPIError(data.error.message || data.error, status, data.errors);
}
return new TwitterError('Twitter API error', status);
}
//# sourceMappingURL=error.js.map