@webiny/api-headless-cms-ddb
Version:
DynamoDB storage operations plugin for Headless CMS API.
94 lines (91 loc) • 3.2 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.createLongTextStorageTransformPlugin = void 0;
var _error = _interopRequireDefault(require("@webiny/error"));
var _gzip = require("@webiny/utils/compression/gzip");
var _apiHeadlessCms = require("@webiny/api-headless-cms");
/**
* File is @internal
*/
const GZIP = "gzip";
const TO_STORAGE_ENCODING = "base64";
const FROM_STORAGE_ENCODING = "utf8";
const convertToBuffer = value => {
if (typeof value === "string") {
return Buffer.from(value, TO_STORAGE_ENCODING);
}
return value;
};
const createLongTextStorageTransformPlugin = () => {
return new _apiHeadlessCms.StorageTransformPlugin({
name: "headless-cms.storage-transform.long-text.default",
fieldType: "long-text",
fromStorage: async ({
field,
value: storageValue
}) => {
const typeOf = typeof storageValue;
if (!storageValue || typeOf === "string" || typeOf === "number" || Array.isArray(storageValue) === true) {
return storageValue;
} else if (typeOf !== "object") {
throw new _error.default(`LongText value received in "fromStorage" function is not an object in field "${field.storageId}" - ${field.fieldId}.`);
}
const {
compression,
value,
isArray
} = storageValue;
/**
* Check if possibly undefined, null, empty...
*/
if (!compression) {
throw new _error.default(`Missing compression in "fromStorage" function in field "${field.storageId}" - ${field.fieldId}.": ${JSON.stringify(storageValue)}.`, "MISSING_COMPRESSION", {
value: storageValue
});
} else if (compression !== GZIP) {
throw new _error.default(`This plugin cannot transform something not compressed with "GZIP".`, "WRONG_COMPRESSION", {
compression
});
}
try {
const buf = await (0, _gzip.decompress)(convertToBuffer(value));
const result = buf.toString(FROM_STORAGE_ENCODING);
if (!isArray) {
return result;
}
return JSON.parse(result);
} catch (ex) {
console.log("Error while transforming long-text.");
console.log(ex.message);
return "";
}
},
toStorage: async ({
value: initialValue
}) => {
/**
* There is a possibility that we are trying to compress already compressed value.
*/
if (initialValue && initialValue.hasOwnProperty("compression") === true) {
return initialValue;
}
const isArray = Array.isArray(initialValue);
const value = isArray ? JSON.stringify(initialValue) : initialValue;
const compressedValue = await (0, _gzip.compress)(value);
const result = {
compression: GZIP,
value: compressedValue.toString(TO_STORAGE_ENCODING)
};
if (!isArray) {
return result;
}
result.isArray = isArray;
return result;
}
});
};
exports.createLongTextStorageTransformPlugin = createLongTextStorageTransformPlugin;
//# sourceMappingURL=longText.js.map