beeswax-node-client
Version:
TypeScript/JavaScript client library for the Beeswax DSP API
124 lines • 3.98 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.BaseResource = void 0;
const helpers_1 = require("../utils/helpers");
class BaseResource {
constructor(client, endpoint, idField) {
this.client = client;
this.endpoint = endpoint;
this.idField = idField;
}
async find(id) {
const body = {};
body[this.idField] = id;
const response = await this.client.request('GET', this.endpoint, { body });
return {
success: true,
payload: response.payload?.[0]
};
}
async query(body) {
const response = await this.client.request('GET', this.endpoint, { body: body || {} });
return {
success: true,
payload: response.payload || []
};
}
async queryAll(body) {
const results = [];
const batchSize = 50;
let offset = 0;
while (true) {
const queryBody = {
...body,
rows: batchSize,
offset: offset,
sort_by: this.idField
};
const response = await this.client.request('GET', this.endpoint, { body: queryBody });
const batch = response.payload || [];
results.push(...batch);
if (batch.length < batchSize) {
break;
}
offset += batchSize;
}
return {
success: true,
payload: results
};
}
async create(body) {
if (!(0, helpers_1.isPOJO)(body) || Object.keys(body).length === 0) {
return {
success: false,
code: 400,
message: 'Body must be non-empty object'
};
}
const response = await this.client.request('POST', `${this.endpoint}/strict`, { body });
if (response.success && response.payload?.id) {
return await this.find(response.payload.id);
}
return response;
}
async edit(id, body, failOnNotFound = false) {
if (!(0, helpers_1.isPOJO)(body) || Object.keys(body).length === 0) {
return {
success: false,
code: 400,
message: 'Body must be non-empty object'
};
}
const updateBody = { ...body };
updateBody[this.idField] = id;
try {
await this.client.request('PUT', `${this.endpoint}/strict`, { body: updateBody });
return await this.find(id);
}
catch (error) {
const notFound = this.isNotFoundError(error, 'update');
if (notFound && !failOnNotFound) {
return {
success: false,
code: 400,
message: 'Not found'
};
}
throw error;
}
}
async delete(id, failOnNotFound = false) {
const body = {};
body[this.idField] = id;
try {
const response = await this.client.request('DELETE', `${this.endpoint}/strict`, { body });
return {
success: true,
payload: response.payload?.[0]
};
}
catch (error) {
const notFound = this.isNotFoundError(error, 'delete');
if (notFound && !failOnNotFound) {
return {
success: false,
code: 400,
message: 'Not found'
};
}
throw error;
}
}
isNotFoundError(error, action) {
try {
const messages = error.error?.payload?.[0]?.message || [];
return messages.some((msg) => new RegExp(`Could not load object.*to ${action}`).test(msg));
}
catch {
return false;
}
}
}
exports.BaseResource = BaseResource;
//# sourceMappingURL=BaseResource.js.map