@magicbell/react-headless
Version:
Hooks to build a notification inbox
63 lines • 2.1 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const humps_1 = tslib_1.__importDefault(require("humps"));
const ajax_js_1 = require("../../lib/ajax.js");
/**
* Class to represent a client that interacts with the MagicBell API.
*
* @example
* class NotificationRepo extends RemoteRepository<Notification, NotificationStore> {}
*/
class RemoteRepository {
remotePathOrUrl;
constructor(remotePathOrUrl) {
this.remotePathOrUrl = remotePathOrUrl;
}
/**
* Get an element from the API server by ID.
*
* @example
* const notification = await repo.get('3df592eb-5f09dd6b');
*/
async get(id) {
const url = `${this.remotePathOrUrl}/${id}`;
const json = await (0, ajax_js_1.fetchAPI)(url);
return humps_1.default.camelizeKeys(json);
}
/**
* Get elements that match params from the API server.
*
* @example
* const notifications = await repo.findBy({ read: false });
*/
async findBy(queryParams) {
try {
const json = await (0, ajax_js_1.fetchAPI)(this.remotePathOrUrl, queryParams);
return humps_1.default.camelizeKeys(json);
}
catch (error) {
// Don't throw Network Errors. Browsers log these themselves and the realtime connection makes
// MagicBell sensitive to connection errors. We don't want to have these flooding consumer logs.
if (/Network Error/.test(error.message)) {
return;
}
// rethrow so upstream can handle all other errors
throw error;
}
}
/**
* Delete an element by ID from the API server.
*
* @example
* const deleted = await repo.delete('3df592eb-5f09dd6b');
*/
delete(id) {
const url = `${this.remotePathOrUrl}/${id}`;
return (0, ajax_js_1.deleteAPI)(url)
.then(() => true)
.catch(() => false);
}
}
exports.default = RemoteRepository;
//# sourceMappingURL=RemoteRepository.js.map