node-firestore-import-export
Version:
Firestore data import and export
62 lines (61 loc) • 2.28 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
// From https://stackoverflow.com/questions/8495687/split-array-into-chunks
const admin = require("firebase-admin");
var DocumentReference = admin.firestore.DocumentReference;
var GeoPoint = admin.firestore.GeoPoint;
const array_chunks = (array, chunk_size) => {
return Array(Math.ceil(array.length / chunk_size))
.fill(null)
.map((_, index) => index * chunk_size)
.map((begin) => array.slice(begin, begin + chunk_size));
};
exports.array_chunks = array_chunks;
const serializeSpecialTypes = (data) => {
const cleaned = {};
Object.keys(data).map(key => {
let value = data[key];
if (value instanceof Date) {
value = { __datatype__: 'timestamp', value: value.toISOString() };
}
else if (value instanceof GeoPoint) {
value = { __datatype__: 'geopoint', value: value };
}
else if (value instanceof DocumentReference) {
value = { __datatype__: 'documentReference', value: value.path };
}
else if (value === Object(value)) {
value = serializeSpecialTypes(value);
}
cleaned[key] = value;
});
return cleaned;
};
exports.serializeSpecialTypes = serializeSpecialTypes;
const unserializeSpecialTypes = (data, fs) => {
const cleaned = {};
Object.keys(data).map(key => {
let value = data[key];
if (value instanceof Object) {
if ('__datatype__' in value && 'value' in value) {
switch (value.__datatype__) {
case 'timestamp':
value = new Date(value.value);
break;
case 'geopoint':
value = new admin.firestore.GeoPoint(value.value._latitude, value.value._longitude);
break;
case 'documentReference':
value = fs.doc(value.value);
break;
}
}
else {
value = unserializeSpecialTypes(value, fs);
}
}
cleaned[key] = value;
});
return cleaned;
};
exports.unserializeSpecialTypes = unserializeSpecialTypes;