UNPKG

reduct-js

Version:

ReductStore Client SDK for Javascript/NodeJS/Typescript

100 lines (99 loc) 3.18 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.WritableRecord = exports.ReadableRecord = void 0; const stream_1 = __importDefault(require("stream")); const buffer_1 = require("buffer"); /** * Represents a record in an entry for reading */ 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_1.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_1.Buffer.concat(chunks))); }); } /** * Read content of record and convert to string */ async readAsString() { return (await this.read()).toString(); } } exports.ReadableRecord = ReadableRecord; /** * Represents a record in an entry for writing */ 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_1.default)) { 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, }); } } exports.WritableRecord = WritableRecord;