@yamamotok/dataobject
Version:
Decorator based JSON serializer and deserializer.
50 lines • 2.98 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.IterableStrategy = void 0;
const DataObjectError_1 = require("../../DataObjectError");
const Strategy_1 = require("../Strategy");
class IterableStrategy extends Strategy_1.Strategy {
transform(opts) {
const { options, sourceValue, key } = opts;
if ((options === null || options === void 0 ? void 0 : options.typeInfo) === Map) {
if (sourceValue instanceof Map) {
return new Strategy_1.Transformed(new Map(sourceValue));
}
if (Array.isArray(sourceValue)) {
throw new DataObjectError_1.DataObjectError(`Type of "${key}" is Map but array was given`);
}
if (typeof sourceValue === 'object' && sourceValue) {
const ret = new Map();
Object.entries(sourceValue).forEach(([k, v]) => {
ret.set(k, this.recurse(Object.assign(Object.assign({}, opts), { key: opts.key + `.${k}`, options: Object.assign(Object.assign({}, options), { typeInfo: undefined }), sourceValue: v })));
});
return new Strategy_1.Transformed(ret);
}
throw new DataObjectError_1.DataObjectError(`Type of "${key}" is Map but Map-unlike value was given`);
}
if ((options === null || options === void 0 ? void 0 : options.typeInfo) === Set) {
if (sourceValue instanceof Set) {
return new Strategy_1.Transformed(new Set(sourceValue));
}
if (Array.isArray(sourceValue)) {
const ret = new Set();
sourceValue.forEach((v, i) => ret.add(this.recurse(Object.assign(Object.assign({}, opts), { key: opts.key + `[${i}]`, options: Object.assign(Object.assign({}, options), { typeInfo: undefined }), sourceValue: v }))));
return new Strategy_1.Transformed(ret);
}
throw new DataObjectError_1.DataObjectError(`Type of "${key}" is Set but Set-unlike value was given`);
}
if ((options === null || options === void 0 ? void 0 : options.isMap) && typeof sourceValue === 'object' && sourceValue) {
const ret = {};
Object.entries(sourceValue).forEach(([k, v]) => {
ret[k] = this.recurse(Object.assign(Object.assign({}, opts), { key: opts.key + `.${k}`, options: Object.assign(Object.assign({}, options), { isMap: false, typeInfo: undefined }), sourceValue: v }));
});
return new Strategy_1.Transformed(ret);
}
if (Array.isArray(sourceValue)) {
return new Strategy_1.Transformed(sourceValue.map((v, i) => this.recurse(Object.assign(Object.assign({}, opts), { key: opts.key + `[${i}]`, sourceValue: v }))));
}
return undefined;
}
}
exports.IterableStrategy = IterableStrategy;
//# sourceMappingURL=IterableStrategy.js.map