reduct-js
Version:
ReductStore Client SDK for Javascript/NodeJS/Typescript
92 lines (91 loc) • 2.78 kB
JavaScript
import Stream from "stream";
import { Buffer } from "buffer";
/**
* Represents a record in an entry for reading
*/
export class ReadableRecord {
/**
* Constructor which should be call from Bucket
* @internal
*/
constructor(time, size, last, head, stream, labels, contentType, arrayBuffer) {
this.labels = {};
this.time = time;
this.size = size;
this.last = last;
this.stream = stream;
this.labels = labels;
this.contentType = contentType;
this.arrayBuffer = arrayBuffer;
if (head) {
this.arrayBuffer = new ArrayBuffer(0);
}
}
/**
* Read content of record
*/
async read() {
if (this.arrayBuffer !== undefined) {
return new Promise((resolve, reject) => {
try {
resolve(Buffer.from(this.arrayBuffer));
}
catch (error) {
reject(error);
}
});
}
const chunks = [];
return new Promise((resolve, reject) => {
this.stream.on("data", (chunk) => chunks.push(chunk));
this.stream.on("error", (err) => reject(err));
this.stream.on("end", () => resolve(Buffer.concat(chunks)));
});
}
/**
* Read content of record and convert to string
*/
async readAsString() {
return (await this.read()).toString();
}
}
/**
* Represents a record in an entry for writing
*/
export class WritableRecord {
/**
* Constructor for stream
* @internal
*/
constructor(bucketName, entryName, options, httpClient) {
this.bucketName = bucketName;
this.entryName = entryName;
this.httpClient = httpClient;
this.options = options;
}
/**
* Write data to record asynchronously
* @param data stream of buffer with data
* @param size size of data in bytes (only for streams)
*/
async write(data, size) {
let contentLength = size || 0;
if (!(data instanceof Stream)) {
contentLength = data.length;
}
const { bucketName, entryName, options } = this;
const headers = {
"Content-Length": contentLength.toString(),
"Content-Type": options.contentType ?? "application/octet-stream",
};
for (const [key, value] of Object.entries(options.labels ?? {})) {
headers[`x-reduct-label-${key}`] = value.toString();
}
if (options.ts === undefined) {
throw new Error("Timestamp must be set");
}
await this.httpClient.post(`/b/${bucketName}/${entryName}?ts=${options.ts}`, data, {
headers: headers,
});
}
}